蓝牙连接背景

时间:2017-08-24 08:35:35

标签: android bluetooth background android-bluetooth

我开发了一款使用蓝牙连接与其他设备通信的应用。 当应用程序进入后台时,蓝牙连接始终处于活动状态,直到我真正关闭应用程序(使用滑动)。 有没有办法,如果应用程序在后台,关闭蓝牙连接(蓝牙插座)后,例如,5分钟? 谢谢

修改

我创建了一个onPause方法:

@Override
public void onPause() {

    if(Utility.isAppIsInBackground(MainActivity.this)){

        runOnUiThread(new Runnable() {
            @Override
            public void run() {new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {

                    try {
                        bsocket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            }, 10000);
            }
        });

    }



    super.onPause();
}

应该在应用程序处于后台时10秒后关闭连接。

这是方法:

   public static boolean isAppIsInBackground(Context context) {
    boolean isInBackground = true;
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
        List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
            if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                for (String activeProcess : processInfo.pkgList) {
                    if (activeProcess.equals(context.getPackageName())) {
                        isInBackground = false;
                    }
                }
            }
        }
    } else {
        List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
        ComponentName componentInfo = taskInfo.get(0).topActivity;
        if (componentInfo.getPackageName().equals(context.getPackageName())) {
            isInBackground = false;
        }
    }

    return isInBackground;
}

但是计时器没有启动。它是正确的? 感谢

0 个答案:

没有答案