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

时间:2019-05-28 14:09:26

标签: java android service

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

我尝试在服务中使用线程,并且该线程将在应用程序关闭后继续运行,但无法正常工作,我还返回了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;
    }

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

2 个答案:

答案 0 :(得分:0)

您需要创建状态栏通知以使服务前台服务保持运行。您可以在此页面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;
}

答案 1 :(得分:0)

MyThread mt = new  MyThread();
    mt.start();

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

    Notification notification =
            null;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
        notification = new Notification.Builder(this)
                .setContentTitle("checkT")
                .setContentText("checkCT")
                .setSmallIcon(R.drawable.applogo)
                .setContentIntent(pendingIntent)
                .setTicker("sticker")
                .build();
    }

    startForeground(ONGOING_NOTIFICATION_ID, notification);

感谢您的帮助。 我确实喜欢这个,但仍然无法使用