繁体   English   中英

从Android中的最新应用中刷出应用后,服务停止

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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