Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restart the service when application closed?

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>

`

like image 812
dev_mg99 Avatar asked Nov 01 '22 10:11

dev_mg99


1 Answers

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.

like image 183
MysticMagicϡ Avatar answered Nov 14 '22 14:11

MysticMagicϡ