java - 应用程序崩溃后服务无法继续运行

标签 java android service

我的服务在应用程序启动时启动,但是当我从最近的应用程序中关闭应用程序时,它崩溃并停止绑定(bind)

我尝试在服务中使用线程,应用程序关闭后线程将继续,但它不起作用,我也在 onStartCommand 函数中返回 START_STICKY ,我无法理解问题是什么。


public class MyThread extends Thread {
        @Override
        public void run() {
            while (true)
            {
                try {
                    this.sleep(1000);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

@Override
    public int onStartCommand(final Intent intent,
                              final int flags,
                              final int startId) {
        MyThread mt = new  MyThread();
        mt.start();


        return START_STICKY;
    }


我希望在我关闭应用程序并将其从最近的应用程序中删除后,该服务能够继续。

最佳答案

您需要创建状态栏通知以使您的服务前台服务并保持运行。您可以在此页面上阅读更多信息 https://developer.android.com/guide/components/services

public class MyThread extends Thread {
    @Override
    public void run() {
        while (true)
        {
            try {
                this.sleep(1000);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

@Override
public int onStartCommand(final Intent intent,
final int flags,
final int startId) {
    MyThread mt = new  MyThread();
    mt.start();

    Intent notificationIntent = new Intent(this, ExampleActivity.class);
    PendingIntent pendingIntent =
    PendingIntent.getActivity(this, 0, notificationIntent, 0);

    Notification notification =
    new Notification.Builder(this, CHANNEL_DEFAULT_IMPORTANCE)
    .setContentTitle(getText(R.string.notification_title))
        .setContentText(getText(R.string.notification_message))
        .setSmallIcon(R.drawable.icon)
        .setContentIntent(pendingIntent)
        .setTicker(getText(R.string.ticker_text))
        .build();

    startForeground(ONGOING_NOTIFICATION_ID, notification);

    return START_STICKY;
}

关于java - 应用程序崩溃后服务无法继续运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56344125/

相关文章:

java - 在 Java 中创建有效的文件名

java - 何时使用 hibernate.connection.provider_class

android - DrawerLayout 中 View 的错误大小和点击行为

android - PreferenceActivity 类型的 addPreferencesFromResource(int) 方法已弃用

android - 如何在 Android 中单击按钮时启用 BroadcastReceiver?

java - 使用spring从服务层启动新线程的正确方法

c# - 如何从 .Net Core 3 创建 Windows 服务

Java SWT 图像调整大小不起作用

android - Phonegap 屏幕随着 AdMob 动画闪烁

java - JGit 在工作副本中检测重命名