如在下面的步驟中提到保持運行所有的時間
1)在服務onStartCommand方法的返回START_STICKY的服務,您可以創建一個服務。
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());