即使应用已关闭,我的任务是运行服务。
我的服务类:
public class MyService extends Service {
public int onStartCommand(Intent intent, int flags, int startId) {
AudioManager am;
am= (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
if(am.getRingerMode() == AudioManager.RINGER_MODE_NORMAL)
am.setRingerMode(AudioManager.RINGER_MODE_SILENT);
else
am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
Minute minute = new Minute();
Calendar cal = Calendar.getInstance();
AlarmManager alarms ;
Intent activate = new Intent(this, MyService.class);
PendingIntent alarmIntent = PendingIntent.getService(this, 0, activate, 0);
alarms = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
cal.set(Calendar.HOUR_OF_DAY, 00);
cal.set(Calendar.MINUTE, minute.minute);
cal.set(Calendar.SECOND, 00);
alarms.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), alarmIntent);
Toast.makeText(this, "checkOnStart", Toast.LENGTH_LONG).show();
return Service.START_STICKY;
}
}
在我的活动中:
Intent activate = new Intent(this, MyService.class);
startService(activate);
但是当我杀死应用程序关闭服务时,我该怎么办才能在应用程序被杀后继续运行服务?
答案 0 :(得分:0)
可以通过在服务被杀死时调用服务来实现。但我无法确定它,因为我从未尝试过它。
这篇文章可能是一个帮助: Creating an never ending background service in android
在Android Service need to run always(Never pause or stop)
上阅读类似的问题和答案- 已编辑 -
这里接近文章的完整实现:
清单文件:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="oak.shef.ac.uk.testrunningservicesbackgroundrelaunched">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="oak.shef.ac.uk.testrunningservicesbackgroundrelaunched.SensorService"
android:enabled="true" >
</service>
<receiver
android:name="oak.shef.ac.uk.testrunningservicesbackgroundrelaunched.SensorRestarterBroadcastReceiver"
android:enabled="true"
android:exported="true"
android:label="RestartServiceWhenStopped">
<intent-filter>
<action android:name="uk.ac.shef.oak.ActivityRecognition.RestartSensor"/>
</intent-filter>
</receiver>
</application>
</manifest>
MainActivity
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
Intent mServiceIntent;
private SensorService mSensorService;
Context ctx;
public Context getCtx() {
return ctx;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ctx = this;
setContentView(R.layout.activity_main);
mSensorService = new SensorService(getCtx());
mServiceIntent = new Intent(getCtx(), mSensorService.getClass());
if (!isMyServiceRunning(mSensorService.getClass())) {
startService(mServiceIntent);
}
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
Log.i ("isMyServiceRunning?", true+"");
return true;
}
}
Log.i ("isMyServiceRunning?", false+"");
return false;
}
@Override
protected void onDestroy() {
stopService(mServiceIntent);
Log.i("MAINACT", "onDestroy!");
super.onDestroy();
}
}
服务
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import java.util.Timer;
import java.util.TimerTask;
/**
* Created by fabio on 30/01/2016.
*/
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);
stoptimertask();
}
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
*/
public void stoptimertask() {
//stop the timer, if it's not already null
if (timer != null) {
timer.cancel();
timer = null;
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
服务重启器
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class SensorRestarterBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i(SensorRestarterBroadcastReceiver.class.getSimpleName(), "Service Stops! Oooooooooooooppppssssss!!!!");
context.startService(new Intent(context, SensorService.class));;
}
}
该服务向BroadcastReceiver发送一条消息,该消息将在服务停止后重启服务(这是一次异步调用,因此它不会受到服务死亡的影响。
完整的源代码是here