【发布时间】:2020-01-22 22:20:17
【问题描述】:
我看到很多教程说要做到这一点,我必须使用服务。看了一个 youtube 视频后,得到了这个:
public class MyService extends Service {
public MyService() {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
onTaskRemoved(intent);
Toast.makeText(this, "Service", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onTaskRemoved(Intent rootIntent) {
Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
restartServiceIntent.setPackage(getPackageName());
startService(restartServiceIntent);
super.onTaskRemoved(rootIntent);
}
}
我必须在 MainActivity 中使用 startService(new Intent(this, MyService.class));
这工作正常。即使我从最近的应用程序中关闭应用程序。但是当我强制停止设置中的应用程序时,该服务不再工作。
有什么方法可以让应用在被强杀的情况下保持运行?
【问题讨论】:
-
当用户强制停止应用程序时,他是在说他不想让它再运行了。这也将停止应用程序中的任何服务。除非用户再次手动启动应用程序,否则无法重新启动应用程序。这是设计使然。
标签: android service background background-process background-application