应用程序关闭时服务停止

0 service android

我需要一个在后台运行的服务并计算两个位置之间的每分钟距离.我使用Thread来每分钟执行一个方法,然后我明白当应用程序关闭时,服务也会停止,因为应用程序和服务使用相同的线程.我怎样才能创建一个每1分钟调用一次的简单方法,即使应用程序关闭也是如此?

Mar*_*nen 12

可以Service通过修改清单在单独的进程中运行:

<service
    android:name="com.example.myapplication.MyBackgroundService"
    android:exported="false"
    android:process=":myBackgroundServiceProcess" >
</service>
Run Code Online (Sandbox Code Playgroud)

但这可能不会带来任何好处.而且大多数时候它甚至可能是一个坏主意.

当然主要的是如果Service关闭它然后重新启动.

ServiceonStartCommand()可以返回的START_STICKY标志:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    // Other code goes here...

    return START_STICKY;
}
Run Code Online (Sandbox Code Playgroud)

这个(和其他)选项在文档中进行了解释.基本上START_STICKY意味着"嘿Android!如果你因为内存不足而真的必须关闭我宝贵的服务,那么请尝试再次启动它."

虽然START_NOT_STICKY意思是"Nahh ......不要打扰.如果我真的需要我的服务运行,我会再次自己调用startService()."

这个(开始粘性)大部分时间都可能很好.您的服务将从头开始.您可以尝试,如果这适合您的用例.

然后有"前台服务"不太可能被Android关闭,因为它们被视为更像是可见的应用程序.事实上,它们会在通知抽屉中显示一个图标和(如果你这样做)一个状态文本.因此,用户可以看到它们,例如SportsTracker,Beddit和此类应用程序.

这包括修改你ServiceonStartCommand():

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    // Tapping the notification will open the specified Activity.
    Intent activityIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0,
            activityIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    // This always shows up in the notifications area when this Service is running.
    // TODO: String localization 
    Notification not = new Notification.Builder(this).
            setContentTitle(getText(R.string.app_name)).
            setContentInfo("Doing stuff in the background...").setSmallIcon(R.mipmap.ic_launcher).
            setContentIntent(pendingIntent).build();
    startForeground(1, not);

    // Other code goes here...

    return super.onStartCommand(intent, flags, startId);
}
Run Code Online (Sandbox Code Playgroud)

Service开始像往常一样,你可以走出前台模式具有:

myBackgroundService.stopForeground(true);
Run Code Online (Sandbox Code Playgroud)

布尔参数定义是否也应该关闭通知.

  • 第二种方法似乎是大多数应用程序执行此操作的方式。先生,我非常感谢您,您解决了数小时的谷歌搜索和文档搜索问题。 (2认同)