package com.sunvote.xpadapp.server; import android.app.ActivityManager; import android.app.KeyguardManager; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.Handler; import android.os.IBinder; import android.text.TextUtils; import com.jaredrummler.android.processes.AndroidProcesses; import com.sunvote.util.LogUtil; import com.sunvote.xpadapp.MainActivity; import java.util.List; public class MoniService extends Service { private Handler handler; public MoniService() { } @Override public IBinder onBind(Intent intent) { throw new UnsupportedOperationException("Not yet implemented"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { if (handler == null) { handler = new Handler(); } if (handler != null) { handler.removeCallbacks(checkTask); handler.post(checkTask); } return super.onStartCommand(intent, flags, startId); } @Override public void onCreate() { super.onCreate(); handler = new Handler(); } private Runnable checkTask = new Runnable() { @Override public void run() { boolean ret = !isBackground(MoniService.this);//AndroidProcesses.isMyProcessInTheForeground(); LogUtil.i("MoniService", "checkResult:" + ret); if (!ret) { Intent intent = new Intent(MoniService.this, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } if (handler != null) { handler.removeCallbacks(checkTask); handler.postDelayed(checkTask, 500); } } }; @Override public void onDestroy() { super.onDestroy(); handler.removeCallbacks(checkTask); } public static boolean isBackground(Context context) { ActivityManager activityManager = (ActivityManager) context .getSystemService(Context.ACTIVITY_SERVICE); List appProcesses = activityManager .getRunningAppProcesses(); for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) { if (TextUtils.equals(appProcess.processName, context.getPackageName())) { return appProcess.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND; } } return false; } }