这是一个完整的例子。希望对您有所帮助!
要启动或停止服务,你们都调用startService,所以传递一个
操作(“START_SERVICE”/“STOP_SERVICE”),以便在您的 WatcherService
onStartCommand(),您可以决定启动或停止您的服务
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// Start service
Intent intentService = new Intent(this, WatcherService.class);
intentService.setAction("START_SERVICE");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
this.startForegroundService(intentService);
} else {
this.startService(intentService);
}
} else {
Intent intentService = new Intent(this, WatcherService.class);
intentService.setAction("STOP_SERVICE");
Log.v(">>>", "Try to stop service");
startService(intentService);
}
}
});
请注意,从 Android 8 开始,您必须 startForegroundService(使用
通知)。你可以看到更多关于前景和背景的信息
服务于Foreground & Background Service
public class WatcherService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null && intent.getAction() != null) {
if (intent.getAction().equals("START_SERVICE")) {
Log.v(">>>", "Start service");
} else if (intent.getAction().equals("STOP_SERVICE") {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
stopForeground(true);
stopSelf();
Log.v(">>>", "Stop foreground service");
} else {
stopSelf();
Log.v(">>>", "Stop background service");
}
}
}
return START_STICKY;
}
/**
* Start foreground service for Android 8+
*/
@Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String channelId = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? createNotificationChannel(notificationManager) : "";
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId);
Notification notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Title")
.setPriority(PRIORITY_MIN)
.setCategory(NotificationCompat.CATEGORY_SERVICE)
.build();
startForeground(101, notification);
}
}
@RequiresApi(Build.VERSION_CODES.O)
private String createNotificationChannel(NotificationManager notificationManager) {
String channelId = "channel_id_01";
String channelName = "chanel_name";
NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
// omitted the LED color
channel.setImportance(NotificationManager.IMPORTANCE_NONE);
channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
notificationManager.createNotificationChannel(channel);
return channelId;
}
.......
}