0
我创建了一项服务,该服务在电话启动时启动。但是,当我打开应用程序时,服务会再次启动并停止运行旧服务,但服务正常运行。但是当我关闭应用程序时,该服务也会停止。如何使用启动时启动的服务以及如果启动时启动的服务被系统杀死,如何重新运行该服务?Android打开应用程序后台服务后停止并启动新服务
这里是我的代码
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);
}