【实例简介】
【实例截图】
【核心代码】
package com.sunfusheng.daemon.sample;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Looper;
import android.util.Log;
import com.blankj.utilcode.util.AppUtils;
import com.sunfusheng.daemon.AbsHeartBeatService;
/**
* @author sunfusheng on 2018/8/3.
*/
public class HeartBeatService extends AbsHeartBeatService {
private static final String TAG = "---> HeartBeatService";
private static final android.os.Handler mainThreadHandler = new android.os.Handler(Looper.getMainLooper());
@Override
public void onStartService() {
Log.d(TAG, "onStartService()");
}
@Override
public void onStopService() {
Log.e(TAG, "onStopService()");
}
@Override
public long getDelayExecutedMillis() {
return 0;
}
@Override
public long getHeartBeatMillis() {
return 30 * 1000;
}
@Override
public void onHeartBeat() {
String packetName=AppUtils.getAppPackageName();
Log.d(TAG, "onHeartBeat()" packetName);
if(!AppUtils.isAppRunning(packetName)){
//方案一
AppUtils.relaunchApp();
//方案二
// Intent sayHelloIntent=new Intent(this,MainActivity.class);
// sayHelloIntent.setAction(Intent.ACTION_VIEW);
// sayHelloIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
// sayHelloIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
// getApplicationContext().startActivity(sayHelloIntent);
//
//方案三
// Intent intent = new Intent("android.intent.action.MAIN");
// intent.setComponent(new ComponentName(getApplicationContext().getPackageName(), MainActivity.class.getName()));
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// getApplicationContext().startActivity(intent);
Log.d(TAG, packetName " launchApp Sucess!!!!!!");
}else{
Log.d(TAG, packetName " is running");
if(!AppUtils.isAppForeground()){
Intent sayHelloIntent=new Intent(this,MainActivity.class);
sayHelloIntent.setAction(Intent.ACTION_VIEW);
sayHelloIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
sayHelloIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
getApplicationContext().startActivity(sayHelloIntent);
Log.d(TAG, packetName " is FLAG_ACTIVITY_SINGLE_TOP!!!");
}
}
}
}