当应用程序从Android中的最新应用程序中删除时,服务停止

时间:2015-03-26 00:18:25

标签: java android performance android-intent android-service

我正在创建一个非常简单的应用程序,我希望服务应该无限运行,就像Whatsapp服务在后台运行一样,即使应用程序通过刷出从最近的应用程序中删除。 以下是我的代码。

的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()));
    }
}

1 个答案:

答案 0 :(得分:0)

Service#onStartCommand方法存储中,字段变量的起始意图,假设为mIntent

然后实现Service#onTaskRemoved方法,如下所示:

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