所有答案似乎正确,所以我将继续并在此处给出完整答案。
首先,最简单的方法是在手动杀死 应用程序时在 Android 中启动 广播,然后定义一个自定义 BroadcastReceiver 触发服务重启。
现在让我们进入代码。
在YourService.java中创建您的服务
请注意onCreate() 方法,在该方法中,对于高于Android Oreo 的构建版本,我们以不同的方式启动前台服务。这是因为最近引入了严格的通知政策,我们必须定义自己的通知渠道才能正确显示它们。
onDestroy() 方法中的this.sendBroadcast(broadcastIntent); 是异步发送动作名称为"restartservice" 的广播的语句。稍后我们将使用它作为重启服务的触发器。
这里我们定义了一个简单的 Timer 任务,它在 Log 中每 1 秒 打印一个计数器值,并在每次打印时自增。
public class YourService extends Service {
public int counter=0;
@Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O)
startMyOwnForeground();
else
startForeground(1, new Notification());
}
@RequiresApi(Build.VERSION_CODES.O)
private void startMyOwnForeground()
{
String NOTIFICATION_CHANNEL_ID = "example.permanence";
String channelName = "Background Service";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
Notification notification = notificationBuilder.setOngoing(true)
.setContentTitle("App is running in background")
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
startForeground(2, notification);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
startTimer();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
stoptimertask();
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("restartservice");
broadcastIntent.setClass(this, Restarter.class);
this.sendBroadcast(broadcastIntent);
}
private Timer timer;
private TimerTask timerTask;
public void startTimer() {
timer = new Timer();
timerTask = new TimerTask() {
public void run() {
Log.i("Count", "========= "+ (counter++));
}
};
timer.schedule(timerTask, 1000, 1000); //
}
public void stoptimertask() {
if (timer != null) {
timer.cancel();
timer = null;
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
创建一个广播接收器来响应您在Restarter.java中自定义的广播
您刚刚在YourService.java 中定义的动作名称为"restartservice" 的广播现在应该触发一个方法,该方法将重新启动您的服务。这是在 Android 中使用 BroadcastReceiver 完成的。
我们重写了 BroadcastReceiver 中内置的onRecieve() 方法来添加将重新启动服务的语句。 startService() 在 Android Oreo 8.1 及更高版本中将无法正常工作,因为一旦应用被终止,严格的后台政策将在重启后很快终止服务。因此,我们将startForegroundService() 用于更高版本并显示持续通知以保持服务运行。
public class Restarter extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i("Broadcast Listened", "Service tried to stop");
Toast.makeText(context, "Service restarted", Toast.LENGTH_SHORT).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(new Intent(context, YourService.class));
} else {
context.startService(new Intent(context, YourService.class));
}
}
}
定义您的 MainActivity.java 以在应用启动时调用服务。
这里我们定义了一个单独的isMyServiceRunning()方法来检查后台服务的当前状态。如果服务没有在运行,我们使用startService()启动它。
由于应用程序已经在前台运行,我们不需要将服务作为前台服务启动以防止自身被终止。
请注意,在onDestroy() 中,我们专门调用stopService(),以便调用我们的重写方法。如果不这样做,那么服务将在应用被终止后自动结束,而无需在 YourService.java
中调用我们修改后的
onDestroy() 方法
public class MainActivity extends AppCompatActivity {
Intent mServiceIntent;
private YourService mYourService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mYourService = new YourService();
mServiceIntent = new Intent(this, mYourService.getClass());
if (!isMyServiceRunning(mYourService.getClass())) {
startService(mServiceIntent);
}
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
Log.i ("Service status", "Running");
return true;
}
}
Log.i ("Service status", "Not running");
return false;
}
@Override
protected void onDestroy() {
//stopService(mServiceIntent);
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("restartservice");
broadcastIntent.setClass(this, Restarter.class);
this.sendBroadcast(broadcastIntent);
super.onDestroy();
}
}
最后在你的AndroidManifest.xml注册他们
以上三个类都需要分别在AndroidManifest.xml注册。
请注意,我们将带有动作名称的intent-filter定义为"restartservice",其中Restarter.java注册为receiver。
这确保了我们的自定义 BroadcastReciever 在系统遇到具有给定动作名称的广播时被调用。
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<receiver
android:name="Restarter"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="restartservice" />
</intent-filter>
</receiver>
<activity android:name="MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="YourService"
android:enabled="true" >
</service>
</application>
如果应用程序从任务管理器中终止,现在应该会再次重新启动您的服务。只要用户不在应用程序设置中Force Stop应用程序,此服务就会继续在后台运行。
更新:感谢Dr.jacky 指出这一点。上述方法仅在调用服务的onDestroy() 时才有效,在某些时候可能不是,这是我不知道的。谢谢。