这里简单介绍两种实现心跳的方式。
第一种,简单粗暴线程实现
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(heartTime);
} catch (InterruptedException e) {
// e.printStackTrace();
}
//业务逻辑
}
}
}).start();
第二种,闹钟+广播
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (count != 0) {
heartReq();
} else {
postReceiver("监听服务启动,开启心跳");
}
count++;
postReceiver("心跳次数:"+count);
postReceiver("心跳间隔时间:"+(heartTime/1000) +"秒");
Global.debug("心跳次数====="+count+"======");
long triggerAtTime = SystemClock.elapsedRealtime() + heartTime;
Intent i = new Intent(this, HeartReceiver.class);
mPi = PendingIntent.getBroadcast(this, 0, i, 0);
// mManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, mPi);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, mPi);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
mManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, mPi);
} else {
mManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, mPi);
}
return START_STICKY;
}
广播:
public class HeartReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Global.debug("心跳广播接收=====");
Intent intent2 = new Intent(context, ListenService.class);
context.startService(intent2);
}
}
最后
以上就是动听花生最近收集整理的关于Android service心跳实现的两种方式的全部内容,更多相关Android内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复