packagecom.example.scangundemo_as;importandroid.app.ActivityManager;importandroid.app.Service;importandroid.content.ComponentName;importandroid.content.Context;importandroid.content.Intent;importandroid.content.pm.ApplicationInfo;importandroid.content.res.Resources;importandroid.os.IBinder;importandroid.support.annotation.Nullable;importandroid.text.TextUtils;importandroid.util.Log;importjava.util.List;importjava.util.logging.Logger;public class APPService extendsService {private static final String packageName = "com.example.scangundemo_as";private static final String className = "MainActivity";
@Overridepublic voidonCreate() {super.onCreate();
Log.i("Service","-------create-------");
}
@Overridepublic voidonDestroy() {super.onDestroy();
Log.i("Service","-------onDestroy-------");
}
@Overridepublic int onStartCommand(Intent intent, int flags, intstartId) {
Log.i("Service","-----service onStartCommand...");newThread(){
@Overridepublic voidrun() {super.run();while(true){try{
Thread.sleep(5000);
}catch(InterruptedException e) {
e.printStackTrace();
}//一直运行
boolean isRunningForeground = isRunningForeground(APPService.this);//Log.i("Service","-----service isRunningForeground="+isRunningForeground);
if(!isRunningForeground){
Log.i("Service","-----start activity-----");
startActivityTool(APPService.this);
}
}
}
}.start();return super.onStartCommand(intent, flags, startId);
}
@Nullable
@OverridepublicIBinder onBind(Intent intent) {return null;
}public static booleanisRunningForeground (Context context) {
ActivityManager am=(ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
ComponentName cn= am.getRunningTasks(1).get(0).topActivity;
String currentPackageName=cn.getPackageName();if(!TextUtils.isEmpty(currentPackageName) &¤tPackageName.equals(context.getPackageName())) {return true;
}return false;
}public static voidstartActivityTool(Context context){
Intent intent= newIntent();
intent.setClass(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK );
context.startActivity(intent);
}
}