赞
踩
有时遇到这样的需求 需要开机自启项目 且时刻保持存活状态
可以利用Service和Broadcast 相互连接 保证通讯 使APP时刻保持 存活状态
如何实现呢?
首先在项目定义一个服务 AlarmService extends Service
public class AlarmService extends Service { private final String TAG = AlarmService.class.getSimpleName(); //定义的时间为1分钟 private static final int ONE_MINUTE = 60 * 1000; private static final int PENDING_REQUEST = 0; @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.e(TAG, "AlarmService:onStartCommand"); if (!SilentUtils.isForeground(getApplication().getBaseContext(), getApplication().getBaseContext().getPackageName())) { Log.e(TAG, "启动app"); SilentUtils.launchApp(getApplication().getBaseContext(), getApplication().getBaseContext().getPackageName()); } AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); //从开机到现在的毫秒书(手机睡眠(sleep)的时间也包括在内 long triggerAtTime = SystemClock.elapsedRealtime() + ONE_MINUTE; Intent AlarmIntent = new Intent(this, AlarmReceive.class); PendingIntent pIntent = PendingIntent.getBroadcast(this, PENDING_REQUEST, AlarmIntent, PENDING_REQUEST); alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pIntent); return super.onStartCommand(intent, flags, startId); } @Nullable @Override public IBinder onBind(Intent intent) { throw new UnsupportedOperationException("Not yet implemented"); } }
这里收到请求后 再返回 AlarmService 然后由 AlarmService 再次执行60*1000
public class AlarmReceive extends BroadcastReceiver {
private final String TAG = AlarmReceive.class.getSimpleName();
@Override
public void onReceive(Context context, Intent intent) {
Log.e(TAG,"AlarmReceive:onReceive");
Intent serviceIntent = new Intent(context, AlarmService.class);
context.startService(serviceIntent);
}
}
通过日志我们看出 每1分钟 AlarmService 和BroadcastReceiver就会送一次请求
通过AlarmService 和BroadcastReceiver 互动 可以达到我要的效果
不要忘记注册
在manifest
<service
android:name=".ipad.service.AlarmService"
android:enabled="true"
android:exported="true" />
<receiver android:name=".ipad.receive.AlarmReceive" />
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。