我创建了一个服务,它在手机启动时启动。但是,当我打开应用程序时,服务再次启动,旧的服务停止,但服务正常。但当我关闭应用程序时,此服务也会停止。如何使用在启动时启动的服务以及如果启动时启动的服务被系统杀死,如何重新运行该服务?
这是我的代码
的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);
}
答案 0 :(得分:0)
此行为是设计使然,因为您是IntentService
的子类。一旦处理了所有意图,它就会自动关闭。如果您希望服务保持不变,请改为扩展Service
并实施您自己的线程机制。