【问题标题】:Service stops when main app si closed关闭主应用程序时服务停止
【发布时间】:2017-03-25 19:53:44
【问题描述】:

当我关闭主应用服务停止广播意图。错在哪里?我找不到任何方法让它继续运行。

广播接收器:

public class CustomReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    Toast.makeText(context, "Custom Broadcast recevied", Toast.LENGTH_SHORT).show();
}}

服务(AAA.java):

public class AAA extends Service {
final class MyThreadClass implements Runnable {
    int service_id;
    MyThreadClass(int service_id) {
        this.service_id = service_id;
    }

    @Override
    public void run() {
        synchronized (this) {
            try {
                while (true) {
                    Thread.sleep(3000);

                    Intent i = new Intent();
                    i.setAction("cz.johnyapps.custombroadcast");
                    sendBroadcast(i);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Thread thread = new Thread(new MyThreadClass(startId));
    thread.start();

    return START_STICKY;
}

@Override
public void onDestroy() {
    super.onDestroy();
}}

清单:

<service android:name="cz.johnyapps.notificationservice.AAA"
        android:exported="true"
        android:process=":ServiceProcess"/>

主要活动:startService(new Intent(this, AAA.class));

【问题讨论】:

    标签: android service android-studio-2.3


    【解决方案1】:

    在Service内部使用startForeground方法来防止这种行为

    【讨论】:

    • 当显示通知时它会起作用。但我需要它而不通知
    • 你必须使用前台进程来确保你的进程不会被杀死。
    • @HonzaJohnyPejsar 顺便说一下,你可以试试 Start_sticky flag
    • START_STICKY 不起作用,在我发布的代码中使用。
    • @HonzaJohnyPejsar,好的。唯一的解决方案是使用前台进程。因此,在常见情况下无法避免这种情况。
    【解决方案2】:

    据我所知,一种方法是即使在关闭应用程序后也让服务运行。

    您必须在您的应用中发出通知,这将绑定 为它服务。如果应用程序关闭,将附加通知 这会将服务绑定到它。

    示例:Android 手机默认的媒体声音播放应用,如果您关闭该应用,通知栏上会显示通知,该通知维护服务以保持服务中的音乐播放。

    【讨论】:

    • 我需要它,恕不另行通知
    • 那么您必须添加一个线程,该线程将一直运行以使该服务处于活动状态。
    • 我该怎么做?
    • 我想我已经通过 Thread thread = new Thread(new MyThreadClass(startId));
    • 它是否按照您的意愿运行服务..?
    猜你喜欢
    • 1970-01-01
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    • 2023-03-02
    • 2015-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多