如在下面的步骤中提到保持运行所有的时间
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());