Android打开应用程序后台服务后停止并启动新服务

时间:2014-12-06 17:40:09

标签: android service

我创建了一个服务,它在手机启动时启动。但是,当我打开应用程序时,服务再次启动,旧的服务停止,但服务正常。但当我关闭应用程序时,此服务也会停止。如何使用在启动时启动的服务以及如果启动时启动的服务被系统杀死,如何重新运行该服务?

这是我的代码

的AndroidManifest.xml

<receiver android:name=".MyBroadcastReceiver" >
     <intent-filter>
         <action android:name="android.intent.action.BOOT_COMPLETED" />
     </intent-filter>
</receiver>

<service android:name=".AppMainService" />

MyBroadCastReceiver

public class MyBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent startServiceIntent = new Intent(context, AppMainService.class);
        context.startService(startServiceIntent);
    }
}

AppMainService

public class AppMainService extends IntentService {

    private Timer timer;
    private ReceiveMessagesTimerTask myTimerTask;
    public static AppPreferences _appPrefs;
    public static SQLiteDatabase qdb;
    public static Config config;
    public static Engine engine;

    /**
     * A constructor is required, and must call the super IntentService(String)
     * constructor with a name for the worker thread.
     */
    public AppMainService() {
        super("HelloIntentService");
    }
    public void onStart(Intent intent, Integer integer) {
        super.onStart(intent, integer);
    }
    public void onCreate() {
        super.onCreate();
        DB db = new DB(this);
        qdb = db.getReadableDatabase();

        _appPrefs = new AppPreferences(getApplicationContext());
        config = new Config();
        engine = new Engine();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, startId, startId);
        Log.i("sss", "Service sarted");
        return START_REDELIVER_INTENT;
    }
    /**
     * The IntentService calls this method from the default worker thread with
     * the intent that started the service. When this method returns, IntentService
     * stops the service, as appropriate.
     */
    @Override
    protected void onHandleIntent(Intent intent) {
        timer = new Timer();
        myTimerTask = new ReceiveMessagesTimerTask();
        timer.schedule(myTimerTask, 0, 10000);
    }

    class ReceiveMessagesTimerTask extends TimerTask {

        @Override
        public void run() {
            //Sending messages
            Log.i("Service", String.valueOf(System.currentTimeMillis())+_appPrefs.getToken());
        }
    }
}

并在我的活动中

protected void onCreate(Bundle savedInstanceState) {
        ...

        Intent intent = new Intent(this, AppMainService.class);
        startService(intent);
}

1 个答案:

答案 0 :(得分:0)

此行为是设计使然,因为您是IntentService的子类。一旦处理了所有意图,它就会自动关闭。如果您希望服务保持不变,请改为扩展Service并实施您自己的线程机制。