2014-10-09 78 views
1

我需要知道何时Android设备闲置了一段时间,当我的应用程序当前处于后台时(并且如果它闲置,请将我的应用程序前面)。只有两个办法我能想到的要做到这一点是:Android服务:当设备空闲X分钟时检测

  1. 不知怎的,检测用户交互的应用程序之外,如果还没有几分钟的X个任意输入,带给我的应用程序前。

    或:

  2. 当设备进入睡眠模式,带给我的应用程序的前面。

我不知道如何这些,但2似乎是对我来说最可行的选择。这是什么代码?

+0

在我看到过类似的讨论之前,这里:http://stackoverflow.com/questions/4075180/application-idle-time – Scalarr 2014-10-09 21:26:17

+0

@Scalar这是检测空闲时间_inside_应用程序。 – uyuyuy99 2014-10-09 21:48:02

+0

当设备进入睡眠模式时,*无*(至少以普通软件的方式)正在运行。 – 2014-10-09 21:54:40

回答

0

我是能够通过使用被放置在所有视图顶部“透明的”视图,它检查用户完成1.触摸

步骤用于实现所需要的效果:

1)创建一个服务这在其onCreate方法创建透明视图,其附加到观点堆栈
2)onStartCommand调用initTimer()方法
3)上的服务
4实施View.OnTouchListener)覆盖onTouch方法
5) onTouch甚至t)收到 - 呼叫initTimer()
6)onDestroy的服务 - 从视图堆栈中删除透明视图
7)当你的主要活动的onPause被调用时启动服务
8)当应用程序停止服务打开

下面是代码:

private Handler mHandler; 
private Runnable mRunnable; 
private final int mTimerDelay = 60000;//inactivity delay in milliseconds 
private LinearLayout mTouchLayout;//the transparent view 

@Override 
public IBinder onBind(Intent intent) { 
    return null; 
} 

@Override 
public void onCreate() { 
    super.onCreate(); 

    mTouchLayout = new LinearLayout(this); 

    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 
      LinearLayout.LayoutParams.MATCH_PARENT); 
    mTouchLayout.setLayoutParams(lp); 

    // set on touch listener 
    mTouchLayout.setOnTouchListener(this); 

    // fetch window manager object 
    WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE); 
    // set layout parameter of window manager 

    WindowManager.LayoutParams mParams = new WindowManager.LayoutParams(
      WindowManager.LayoutParams.WRAP_CONTENT, 
      WindowManager.LayoutParams.WRAP_CONTENT, 
      WindowManager.LayoutParams.TYPE_SYSTEM_ERROR, 
      WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | 
        WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH | 
        WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT 
    ); 

    mParams.gravity = Gravity.LEFT | Gravity.TOP; 
    windowManager.addView(mTouchLayout, mParams); 
} 

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    initTimer(); 

    return START_NOT_STICKY; 
} 

@Override 
public boolean onTouch(View view, MotionEvent motionEvent) { 
    Log.d("IdleDetectorService", "Touch detected. Resetting timer"); 
    initTimer(); 
    return false; 
} 

@Override 
public void onDestroy() { 
    super.onDestroy(); 
    mHandler.removeCallbacks(mRunnable); 
    WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE); 
    if (windowManager != null && mTouchLayout != null) { 
     windowManager.removeView(mTouchLayout); 
    } 
} 

/** 
* (Re)sets the timer to send the inactivity broadcast 
*/ 
private void initTimer() { 
    // Start timer and timer task 
    if (mRunnable == null) { 

     mRunnable = new Runnable() { 
      @Override 
      public void run() { 
       Log.d("IdleDetectorService", "Inactivity detected. Sending broadcast to start the app"); 

       try { 
        boolean isInForeground = new ForegroundCheckTask().execute(getApplicationContext()).get(); 

        if (!isInForeground) { 
         Intent launchIntent = getApplication() 
           .getPackageManager() 
           .getLaunchIntentForPackage("<your-package-name>"); 
         if (launchIntent != null) { 
          LogUtil.d("IdleDetectorService", "App started"); 
          getApplication().startActivity(launchIntent); 
         } 
        } 

        stopSelf(); 
       } catch (Exception e) { 
       } 
      } 
     }; 
    } 

    if (mHandler == null) { 
     mHandler = new Handler(); 
    } 

    mHandler.removeCallbacks(mRunnable); 
    mHandler.postDelayed(mRunnable, mTimerDelay); 
} 

private class ForegroundCheckTask extends AsyncTask<Context, Void, Boolean> { 

    @Override 
    protected Boolean doInBackground(Context... params) { 
     final Context context = params[0]; 
     return isAppOnForeground(context); 
    } 

    private boolean isAppOnForeground(Context context) { 
     ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); 
     List<ActivityManager.RunningAppProcessInfo> appProcesses = null; 

     if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) { 
      appProcesses = activityManager.getRunningAppProcesses(); 
     } else { 
      //for devices with Android 5+ use alternative methods 
      appProcesses = AndroidProcesses.getRunningAppProcessInfo(getApplication()); 
     } 

     if (appProcesses == null) { 
      return false; 
     } 

     final String packageName = context.getPackageName(); 

     for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) { 
      if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && 
        appProcess.processName.equals(packageName)) { 
       return true; 
      } 
     } 

     return false; 
    } 
} 

请注意,你应该在你的AndroidManifest.xml文件中添加额外的权限: 机器人:名字= “android.permission.SYSTEM_ALERT_WINDOW”