【问题标题】:Service stopped when app is swiped out from recent apps in Android从 Android 中最近的应用程序中刷出应用程序时服务停止
【发布时间】:2015-05-29 21:48:09
【问题描述】:

我正在制作一个非常简单的应用程序,我希望服务应该无限运行,就像 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()));
    }
}

【问题讨论】:

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


    【解决方案1】:

    在您的 Service#onStartCommand 方法中,将起始意图存储到字段变量中,例如 mIntent

    然后像这样实现Service#onTaskRemoved方法:

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

    【讨论】:

    • 感谢您的回复,但仍然无法正常工作。当我关闭所有最近的应用程序时,包括这个服务都停止了。
    • 在清单中,添加您的服务 android:stopWithTask="false" 属性。
    • 请将其作为答案发布。
    • 但是我的服务类扩展了 IntentService。现在我该如何实现呢?
    猜你喜欢
    • 1970-01-01
    • 2019-12-05
    • 1970-01-01
    • 1970-01-01
    • 2018-11-10
    • 1970-01-01
    • 2013-01-28
    • 1970-01-01
    • 2022-07-07
    相关资源
    最近更新 更多