Android服务:检测设备空闲X分钟

时间:2014-10-09 21:17:56

标签: java android idle-timer

我需要知道当我的应用程序当前处于后台时,检测到Android设备何时处于空闲状态一段时间(如果它处于空闲状态,请将我的应用程序带到前面)。我能想到的唯一两种方法是:

  1. 以某种方式检测应用程序之外的用户互动,如果没有任何X分钟的输入,请将我的应用程序带到前面。

  2. 当设备进入睡眠模式时,请将我的应用程序放在前面。

  3. 我无法弄清楚如何处理其中任何一个,但对我来说2似乎是最可行的选择。这个代码是什么?

1 个答案:

答案 0 :(得分:0)

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

实现所需效果的步骤:

1)创建一个服务,在其onCreate方法中创建透明视图并将其附加到视图堆栈
2)onStartCommand调用initTimer()方法
3)在服务上实现View.OnTouchListener 4)覆盖onTouch方法
5)收到onTouch事件 - 调用initTimer()
6)onDestroy服务 - 从视图堆栈中删除透明视图
7)当onMause主要活动被称为
时启动服务 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”