简体   繁体   中英

Service stopped when app is swiped out from recent apps in Android

I am making a very simple app in which I want that a service should run infinitely just like Whatsapp service runs in background, even if the app is removed from Recent Apps by swiping out.
Below is my code.

AndroidManifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.net.gs.servicetesting" >

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <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=".MyService"
        android:process=":com">
        <intent-filter>
            <action
                android:name="com.net.gs.servicetesting.MyService" />
        </intent-filter>
    </service>
</application>
</manifest>

MyService.java:

public class MyService extends Service {
    private String TAG = "MyService";

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

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

    @Override
    public void onDestroy() {
        Log.d(TAG,"Service Destoryed");
        super.onDestroy();
    }
}

MainActivity.java:

public class MainActivity extends ActionBarActivity {

    String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Log.d(TAG, "Activity Strated");
        startService(new Intent(MyService.class.getName()));
    }
}

In your Service#onStartCommand method store the starting intent to a field variable, let's say mIntent .

Then implement the Service#onTaskRemoved method like this:

@Override
@TargetApi(14)
public void onTaskRemoved(Intent rootIntent) {
    startService(mIntent);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM