即使用户强制关闭它,如何自动重启服务?

Vip*_*l J 38 service android alarm

我想要一个服务在我的应用程序中一直运行.因此,即使用户强行关闭,我也想重新启动它.肯定有一种方法可以做到像facebook这样的应用程序正在这样做.(它没有使用推送通知,即使互联网关闭,facebook也会重启其服务).

任何帮助,将不胜感激.谢谢!

Meh*_*sar 65

首先,对用户的意愿强有力地运行服务是非常糟糕的模式.

无论如何,您可以使用BroadcastReceiver处理从onDestroy()您的服务发送的广播来重新启动它.

StickyService.java

public class StickyService extends Service
{
    private static final String TAG = "StickyService";


    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "onStartCommand");
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        sendBroadcast(new Intent("YouWillNeverKillMe"));
    }

}
Run Code Online (Sandbox Code Playgroud)

RestartServiceReceiver.java

public class RestartServiceReceiver extends BroadcastReceiver
{

    private static final String TAG = "RestartServiceReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.e(TAG, "onReceive");
    context.startService(new Intent(context.getApplicationContext(), StickyService.class));

    }

}
Run Code Online (Sandbox Code Playgroud)

声明清单文件中的组件:

    <service android:name=".StickyService" >
    </service>

    <receiver android:name=".RestartServiceReceiver" >
        <intent-filter>
            <action android:name="YouWillNeverKillMe" >
            </action>
        </intent-filter>
    </receiver>
Run Code Online (Sandbox Code Playgroud)

启动StickyService的组件(即Application,Activity,Fragment):

startService(new Intent(this, StickyService.class));
Run Code Online (Sandbox Code Playgroud)

要么

sendBroadcast(new Intent("YouWillNeverKillMe"));
Run Code Online (Sandbox Code Playgroud)

  • 据我所知,如果用户强制停止应用程序,BroadcastReceivers将不再工作 (17认同)
  • 用户强制关闭应用程序时不工作.**onDestroy**未被调用. (15认同)
  • @sjkm不是那个电池杀手吗? (2认同)
  • "首先,强行服务于用户的意愿是非常糟糕的模式." - >那就是Google所做的一切...... (2认同)
  • 在某些手机(如 Mi 和 Vivo)中,我们必须更改设置,并从设置应用程序中授予应用程序在后台运行的特殊权限。即使您创建了在应用程序关闭时自动重启的服务,该服务也不会运行,除非您在手机的设置应用程序中设置权限。 (2认同)

Gov*_*ind 12

您必须创建一个sticky service覆盖onTaskRemoved方法,您可以在其中设置警报服务以再次触发代码.

public class BackgroundService extends Service {

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        //create an intent that you want to start again.
        Intent intent = new Intent(getApplicationContext(), BackgroundService.class);
        PendingIntent pendingIntent = PendingIntent.getService(this, 1, intent, PendingIntent.FLAG_ONE_SHOT);
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime() + 5000, pendingIntent);
        super.onTaskRemoved(rootIntent);
    }
}
Run Code Online (Sandbox Code Playgroud)

另外在像小米,Huwaei这样的设备中,一旦从最近的应用程序中移除应用程序,该应用程序就会被强制关闭.这是因为制造商具有可提高内存/电池性能的任务管理器功能.

您可以查看此链接以获取更多信息:https://stackoverflow.com/a/41360159/2798289


Zoh*_*han 5

根据 Android 文档

Starting from Android 3.1, the system's package manager keeps track of applications 
that are in a stopped state and provides a means of controlling their launch from 
background processes and other applications.

Note that an application's stopped state is not the same as an Activity's stopped
state. The system manages those two stopped states separately.
FLAG_INCLUDE_STOPPED_PACKAGES — Include intent filters of stopped applications in the
list of potential targets to resolve against.

FLAG_EXCLUDE_STOPPED_PACKAGES — Exclude intent filters of stopped applications from the
list of potential targets.

When neither or both of these flags is defined in an intent, the default behavior is to
include filters of stopped applications in the list of potential targets. 

Note that the system adds FLAG_EXCLUDE_STOPPED_PACKAGES to all broadcast intents.
It does this to prevent broadcasts from background services from inadvertently or
unnecessarily launching components of stopped applications. A background service 
or application can override this behavior by adding the FLAG_INCLUDE_STOPPED_PACKAGES
flag to broadcast intents that should be allowed to activate stopped applications.
Run Code Online (Sandbox Code Playgroud)

在强制停止应用程序时,Android 只会终止进程 ID。没有警告,对服务/活动进行回调。根据 Android 文档,当应用程序被终止时,它可能会调用 onPause()。

当我在我的应用程序中尝试时,甚至没有调用 onPause() 。我认为唯一的方法是使用FLAG_INCLUDE_STOPPED_PACKAGES意图标记并从另一个应用程序发送它


Bij*_*esh 2

在服务的 startCommand 方法上返回 START_STICKY。一般来说,它告诉操作系统在服务被杀死时启动该服务。

  • 当 android 终止服务时,这有效,而不是当我们强制关闭它时。 (4认同)