【发布时间】:2017-03-31 14:04:43
【问题描述】:
我想在 Android 中创建一个永无止境的后台服务。为此,我使用 AlarmManager 和 Simple Service Alarmmanger 在一段时间后发送广播,在广播接收器中,我正在检查服务是否正在运行,如果正在运行,则什么也不做,再次启动它。
我的服务代码是
public class MyService extends Service {
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate ( );
Log.e ("My service ", "oncreate");
}
@Override
public void onTaskRemoved(Intent rootIntent) {
scheduleAlarm ();
super.onTaskRemoved (rootIntent);
}
// Setup a recurring alarm every half hour
public void scheduleAlarm() {
// Construct an intent that will execute the ServiceAlarmReceiver
Intent intent = new Intent("com.hmkcode.android.USER_ACTION");
// Create a PendingIntent to be triggered when the alarm goes off
final PendingIntent pIntent = PendingIntent.getBroadcast(this, ServiceReceiver.REQUEST_CODE,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
// Setup periodic alarm every 5 seconds
long firstMillis = System.currentTimeMillis()+5000; // alarm is set right away
AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
// First parameter is the type: ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTCWAKEUP
// Interval can be INTERVAL_FIFTEEN_MINUTES, INTERVAL_HALF_HOUR, INTERVAL_HOUR, INTERVAL_DAY
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis,
6000, pIntent);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e ("My Service:", " on Start Command");
return START_STICKY;
}
}
广播接收器
public class ServiceReceiver extends WakefulBroadcastReceiver {
public static final int REQUEST_CODE=12355;
public ServiceReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
// check service is running or not
if (isMyServiceRunning (MessageService.class,context)){
// don nothing
}
else {
// launch the service
if (isConnectedToInternet (context)) {
Intent serviceIntent = new Intent (context, MyService.class);
context.startService (serviceIntent);
}
}
Log.e ("hello","wer are in Receiver" );
// throw new UnsupportedOperationException ("Not yet implemented");
}
}
我的清单:
<receiver
android:name=".Services.ServiceReceiver"
android:enabled="true"
android:exported="true"
android:process=":remote">
<intent-filter>
<action android:name="com.hmkcode.android.USER_ACTION" />
</intent-filter>
</receiver>
<service
android:name=".Services.MyService"
android:enabled="true"
android:stopWithTask="false"
android:process=":remote"
>
</service>
当应用程序处于前台或后台时它运行良好,但 问题是当我从 Android 中最近的任务列表中刷出应用程序时,应用程序被杀死,因此服务和我的广播接收器永远无法重新开始?我正在重新安排我的Alarmmanger 中的onTaskRemoved 方法,但服务仍然没有重新开始。
也正如人们所说,从onStartCommand()返回START_STICKY 这样,即使由于资源限制而必须停止服务,系统也会重新启动服务。
在清单文件的<service> 标记中也使用了"stopWithTask"=false。它也没有任何影响。
【问题讨论】:
标签: android service broadcastreceiver