How to restart the service when application closed?

南笙酒味 提交于 2021-02-07 14:14:09

问题


I am using the service for sending notifications every 30 sec. When my application is in background mode it is working fine. Every notification receives properly. But when I kill/close my application the service stops and I am not receiving any notification.

Anybody have an idea on how to run the service when application is closed or killed?

here is my manifest file`
``

<uses-sdk
    android:minSdkVersion="11"
    android:targetSdkVersion="21" />

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.GET_TASKS" />
<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <service
        android:name=".MainService"
        android:enabled="true"
        android:exported="false"
         >
    </service>
    <service android:name=".NewService" >
    </service>

    <activity
        android:name=".MainActivity2"
        android:label="@string/title_activity_main_activity2" >
    </activity>
</application>

`


回答1:


If you want to continue your service even after killing application from Recent app's list, set stopWithTask as false in manifest:

<service
    android:enabled="true"
    android:name=".MyService"
    android:exported="false"
    android:stopWithTask="false" />

And your Service should be sticky.

@Override
public final int onStartCommand(Intent intent, int flags, int startId) {
    Log.i(TAG, "onStarCommand(): Received id " + startId + ": " + intent);
    return START_STICKY; // run until explicitly stopped.
}

Refer this question for all details.

And if you want to perform some additional action when application gets removed from recent list, you can override method onTaskRemoved

Hope this helps.



来源:https://stackoverflow.com/questions/28474664/how-to-restart-the-service-when-application-closed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!