【发布时间】:2018-07-09 08:35:23
【问题描述】:
如果我也杀死应用程序实例,我想在后台运行我的应用程序。但是在我杀死我的应用程序后,该服务也停止工作。这是我的代码,请任何人帮助我解决我的问题。
我按照此链接在后台运行,但如果我删除实例,它就无法工作。如果实例也被删除,谁能告诉我如何运行后台服务?
这是我的 MainActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ctx = this;
setContentView(R.layout.activity_main);
Intent alarmIntent = new Intent(MainActivity.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, ALARM_REQUEST_CODE, alarmIntent, 0);
mSensorService = new SensorService(getCtx());
mServiceIntent = new Intent(getCtx(), mSensorService.getClass());
if (!isMyServiceRunning(mSensorService.getClass())) {
startService(mServiceIntent);
}
}
这是我的服务类
public class SensorService extends Service{
public int counter=0;
public SensorService(Context applicationContext) {
super();
Log.i("HERE", "here I am!");
}
public SensorService() {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
startTimer();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i("EXIT", "ondestroy!");
Intent broadcastIntent = new Intent("uk.ac.shef.oak.ActivityRecognition.RestartSensor");
sendBroadcast(broadcastIntent);
}
private Timer timer;
private TimerTask timerTask;
long oldTime=0;
public void startTimer() {
//set a new Timer
timer = new Timer();
//initialize the TimerTask's job
initializeTimerTask();
//schedule the timer, to wake up every 1 second
timer.schedule(timerTask, 1000, 1000); //
}
/**
* it sets the timer to print the counter every x seconds
*/
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
Log.i("in timer", "in timer ++++ "+ (counter++));
}
};
}
/**
* not needed
*/
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
【问题讨论】:
-
你检查过我对这个SO的回答了吗?
-
我试过了,但如果应用程序在前台,它正在运行@hasan_shaikh
-
在此处添加您的代码
-
@hasan_shaikh 我添加了我的代码 pease check 一次
标签: android background android-8.1-oreo