【问题标题】:Keep an android app running in background让安卓应用在后台运行
【发布时间】: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


【解决方案1】:

您现在可以注册您的应用以从通常为 firebase 的 google play 服务获取推送通知。您可以通过从服务器上的 firebase Amin ask 向您的应用发送推送通知来启动您的服务。

注意:由于 android pie 运行服务的方式发生了变化。因此,在做任何事情之前,请先阅读 android pie services docs

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-07
    • 2019-10-10
    • 2016-06-09
    • 1970-01-01
    • 2016-11-06
    • 1970-01-01
    • 2015-01-04
    相关资源
    最近更新 更多