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



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

这是我的代码

安卓清单.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);
}

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

最新更新