编程语言
首页 > 编程语言> > 以编程方式阻止Android应用程序

以编程方式阻止Android应用程序

作者:互联网

我试图开发这样一个应用程序,在某种意义上我想用我想要的密码锁定我的设备中的所有应用程序.但我没有找到解决方案的任何代码.所以我自己开发了一个,不幸的是它没有成功.我找到了许多锁定Android设备的解决方案,但没有找到一个锁定应用程序.如果你建议一个解决方案,将很高兴.

解决方法:

我使用后台服务来检查哪个应用程序在前台(这意味着用户正在使用该应用程序).然后我检查是否需要锁定应用程序.

要查找所有已安装应用程序的列表(不包括系统应用程序):

PackageManager packageManager = getPackageManager();
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);

List<ResolveInfo> appList = packageManager.queryIntentActivities(mainIntent, 0);
Collections.sort(appList, new ResolveInfo.DisplayNameComparator(packageManager));
List<PackageInfo> packs = packageManager.getInstalledPackages(0);
for (int i = 0; i < packs.size(); i++) {
    PackageInfo p = packs.get(i);
    ApplicationInfo a = p.applicationInfo;
    // skip system apps if they shall not be included
    if ((a.flags & ApplicationInfo.FLAG_SYSTEM) == 1) {
        continue;
    }
    appList.add(p.packageName);
}

要查找当前的前台应用程序:

ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> RunningTask = mActivityManager.getRunningTasks(1);
ActivityManager.RunningTaskInfo ar = RunningTask.get(0);
activityOnTop=ar.topActivity.getClassName();

这里的class-name提供了应用程序的包名.我建议您使用包名来标识任何应用程序,以便我们知道包名称始终是唯一的.

现在,锁定应用程序的功能:

要查找哪个应用程序在前台运行并想要锁定它,我们只需要启动另一个具有EditText for password和OK和Cancel按钮的活动.

Intent lockIntent = new Intent(mContext, LockScreen.class);
lockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(lockIntent);

单击“确定”,如果密码正确,则只需完成LockScreen活动.如果密码不正确,则只需使用下面的代码即可关闭应用程序并显示设备的主屏幕:

Intent startHomescreen = new Intent(Intent.ACTION_MAIN);
startHomescreen.addCategory(Intent.CATEGORY_HOME);
startHomescreen.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(startHomescreen);

取消按钮也使用相同的代码.

标签:android,password-protection
来源: https://codeday.me/bug/20190928/1825994.html