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
<service android:name=".poialert.XXXService"/> <receiver android:name=".poialert.XXXReceiver" android:permission="android.permission.RECEIVE_BOOT_COMPLETED"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED"/> </intent-filter> <intent-filter> <action android:name="RestartSerivcesForSystemEventReceiver"/> </intent-filter> <intent-filter> <action android:name="android.intent.action.MEDIA_MOUNTED"/> <action android:name="android.intent.action.MEDIA_UNMOUNTED"/> <action android:name="android.intent.action.MEDIA_EJECT"/> <data android:scheme="file"/> </intent-filter> </receiver>
随时随地看视频