1.启动Service代码,可以放在点击事件中
Intent i = new Intent(this, XXXService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(i);
} else {
startService(i);
}
2.Service关键代码
public class SocketAlarmService extends Service {
private static final long CHECK_SERVICE_ALIVE_PERIOD = HEARTBEAT * 2;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
startForeground();
}
void startForeground() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
MLog.i(FaceDetectionApp.TAG, "startForeground **************");
NotificationChannel channel = new NotificationChannel(XXXID, "xxx", NotificationManager.IMPORTANCE_LOW);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (manager != null) {
manager.createNotificationChannel(channel);
}
Notification notification = new Notification.Builder(this, FACE_DETECTION_FOREGROUND_NOTIFICATION_ID).build();
startForeground(-1, notification);
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
MLog.i(FaceDetectionApp.TAG, "onStartCommand");
AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent i = new Intent(this, SocketKeepAliveReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
if (someCondition/*不再维护声明周期,结束*/)) {
stopSelf();// After stopSelf(), onDestroy will be executed
return START_NOT_STICKY;
}
long triggerAtTime = SystemClock.elapsedRealtime() + CHECK_SERVICE_ALIVE_PERIOD;
if (manager != null) {
manager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);
}
return super.onStartCommand(intent, flags, startId);
}
}
3.自定义广播接收,用于启动Service,如果Service在运行,则只执行onStartCommon
public class XXXReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, XXXService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(i);
} else {
context.startService(i);
}
}
}
4.Manifest.xml
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/97/viewspace-2806369/ ,如需转载,请注明出处,否则将追究法律责任。