当我从任务管理器

时间:2015-10-25 18:39:31

标签: java android android-service

我正在为Android开发应用程序。我在Android中遇到了一些问题。我想让服务在后台运行并播放音频流。但不幸的是,当任务从活动管理器中滑出时,服务会重新启动。这对我来说非常不方便,我希望这项服务继续有效,无需重启。

的AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.rkoptev.backgroundservice">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".TweetViewActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name=".TweetCollectorService"
            android:process=":remote">
            <intent-filter>
                <action android:name="com.rkoptev.backgroundservice.TweetCollectorService"/>
            </intent-filter>
        </service>
    </application>

</manifest>

TweetCollectorService.java

public class TweetCollectorService extends Service {

    private static final String TAG = TweetCollectorService.class.getSimpleName();

    private Timer timer;

    private TimerTask updateTask = new TimerTask() {
        @Override
        public void run() {
            Log.i(TAG, "Timer task doing work");
        }
    };

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

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "Service creating");

        timer = new Timer("TweetCollectorTimer");
        timer.schedule(updateTask, 1000);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "Service destroying");

        timer.cancel();
        timer = null;
    }
}

TweetViewActivity.java

public class TweetViewActivity extends Activity {

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

        startService(new Intent(TweetCollectorService.class.getName()));
    }
}

有没有办法阻止服务重启? 谢谢!

2 个答案:

答案 0 :(得分:0)

尝试将其添加到服务的onCreate方法的底部:

Notification note = new Notification.Builder(this)
    .setContentTitle("Notification title")
    .setContentText("Notification message")
    .setSmallIcon(R.mipmap.ic_launcher)
    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher)).build();
startForeground(1, note);

这将告诉Android系统您不希望该服务被杀死。

您还可以尝试从服务的Service.START_STICKY方法返回onStartCommand(),如下所述:https://stackoverflow.com/a/24427569/2441655

答案 1 :(得分:-1)

向外滑动相当于在应用上导致Force Stop。由于该服务仅是应用程序的一部分,因此它也将被停止。

作为替代方案,您可以:

noHistory="true"

<activity>标记