让android应用程序在后台运行

让android应用程序在后台运行,android,service,background,background-process,background-application,Android,Service,Background,Background Process,Background Application,我看到很多教程说,要做到这一点,我必须使用服务。在观看youtube视频后,得到以下信息: public class MyService extends Service { public MyService() { } @Override public int onStartCommand(Intent intent, int flags, int startId) { onTaskRemoved(intent); Toast

我看到很多教程说,要做到这一点,我必须使用服务。在观看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);
    }
}
我必须使用
startService(newintent(this,MyService.class)),在MainActivity中调用此服务

这很好用。即使我从最近的应用程序中关闭应用程序。但是当我从设置中强制停止应用程序时,服务就不再工作了


即使应用程序被强制杀死,是否有任何方法可以保持应用程序运行?

您现在可以注册应用程序以从google play services(通常是firebase)获得推送通知。您可以通过服务器上的firebase Amin ask向应用程序发送推送通知来启动服务


注意:由于android pie,您运行服务的方式发生了变化。因此,在做任何事情之前,先通过android pie服务文档

注册你的应用程序,从google play services(通常是firebase)获得推送通知。您可以通过服务器上的firebase Amin ask向应用程序发送推送通知来启动服务


注意:由于android pie,您运行服务的方式发生了变化。因此,在做任何事情之前,当用户强制停止并运行应用程序时,先通过android pie services文档

,他说他不想让它再运行了。这也将停止应用程序中的任何服务。除非用户再次手动启动应用程序,否则无法重新启动应用程序。这是设计的。当用户强制停止应用程序时,你应该看看文档,他说他不想让它再运行了。这也将停止应用程序中的任何服务。除非用户再次手动启动应用程序,否则无法重新启动应用程序。这是故意的。你应该看看文件