请尝试使用前台服务:
在启动服务的方法中:
Intent startIntent = new Intent(MainActivity.this, ForegroundService.class)
startIntent.setAction(Constants.ACTION.STARTFOREGROUND_ACTION)
startService(startIntent)
现在在
onStartCommand()
中:
if (intent.getAction().equals(Constants.ACTION.STARTFOREGROUND_ACTION)) {
Log.i(LOG_TAG, "Received Start Foreground Intent ");
Toast.makeText(this, "Service Started!", Toast.LENGTH_SHORT).show();
阅读更多 简单的前台服务
或者您可以尝试像这样的代码:
从 onStartCommand()
需要返回 START_STICKY
在您的服务中覆盖 onDestroy()
方法:
@Override
public void onDestroy() {
super.onDestroy();
Log.i("EXIT", "ondestroy!");
Intent broadcastIntent = new Intent();
broadcastIntent.putExtra("broadcast.Message", "alarm, need to restart service");
sendBroadcast(broadcastIntent);
}
现在需要实现广播接收器:
public class RestarterBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i(SensorRestarterBroadcastReceiver.class.getSimpleName(), "Service Stops! Oooooooooooooppppssssss!!!!");
context.startService(new Intent(context, YourService.class));
}
}