당신은 서비스를 만들 수 있습니다.
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
2)는 관계없이 항상 경계 클라이언트의 수의 활성 상태를 유지하도록 startService (이면 MyService)를 사용하여 백그라운드에서 서비스를 시작합니다.
Intent intent = new Intent(this, PowerMeterService.class);
startService(intent);
3) 바인더를 만듭니다.
public class MyBinder extends Binder {
public MyService getService() {
return MyService.this;
}
}
4) 서비스 연결을 정의하십시오.
private ServiceConnection m_serviceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
m_service = ((MyService.MyBinder)service).getService();
}
public void onServiceDisconnected(ComponentName className) {
m_service = null;
}
};
5) bindService를 사용하여 서비스에 바인딩하십시오.
Intent intent = new Intent(this, MyService.class);
bindService(intent, m_serviceConnection, BIND_AUTO_CREATE);
6) 서비스가 끝난 후 적절한 활동을 시작하라는 알림이 필요할 수 있습니다.
private void addNotification() {
// create the notification
Notification.Builder m_notificationBuilder = new Notification.Builder(this)
.setContentTitle(getText(R.string.service_name))
.setContentText(getResources().getText(R.string.service_status_monitor))
.setSmallIcon(R.drawable.notification_small_icon);
// create the pending intent and add to the notification
Intent intent = new Intent(this, MyService.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
m_notificationBuilder.setContentIntent(pendingIntent);
// send the notification
m_notificationManager.notify(NOTIFICATION_ID, m_notificationBuilder.build());
}
7) 단일 최상위 모드에서 활동을 시작하려면 매니페스트를 수정해야합니다.
android:launchMode="singleTop"
8) 시스템에 리소스가 필요하고 서비스가 활발하지 않으면 서비스가 중지 될 수 있습니다. 이것이 받아 들일 수없는 경우 startForeground를 사용하여 서비스를 포 그라운드로 가져 오십시오.
startForeground(NOTIFICATION_ID, m_notificationBuilder.build());