How to make app lock app in android?

﹥>﹥吖頭↗ 提交于 2019-12-20 08:12:22

问题


I have to develop an app locker for Android where the user can block apps and other users can not access these apps without an access key.

I have installed an app but I don't know how to lock this app.

Please suggest me something.


回答1:


This is not how stack overflow works. You can not ask a complete solution without even trying anything.

For the most basic version of your app, you need to perform three functions.

  1. Get a list of all the installed apps on device and show them in a ListView with check box. If the user checks any app, add the app to a different list say BlockedAppsList(which will be the list of apps which user wants to block). You can get all the apps installed using the following code:

    final PackageManager pm = getPackageManager();
    //get a list of installed apps.
    List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);
    
    for (ApplicationInfo packageInfo : packages) {
    Log.d(TAG, "Installed package :" + packageInfo.packageName);
    Log.d(TAG, "Source dir : " + packageInfo.sourceDir);
    Log.d(TAG, "Launch Activity :" + pm.getLaunchIntentForPackage(packageInfo.packageName)); 
    }
    
  2. Check the which is the current opened app. You can check by using this code:

    ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
    List l = am.getRecentTasks(1, ActivityManager.RECENT_WITH_EXCLUDED);
    Iterator i = l.iterator();
    PackageManager pm = this.getPackageManager();
    while (i.hasNext()) {
    ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo)(i.next());
    try {
    CharSequence c = pm.getApplicationLabel(pm.getApplicationInfo(
    info.processName, PackageManager.GET_META_DATA));
    Log.w("LABEL", c.toString());
    } catch (Exception e) {
    // Name Not FOund Exception
        }
       }
    
  3. Now check if the current app is present in the BlockedAppsList, if it is there, you can show any screen with a block message.

good luck!




回答2:


Assuming that you store the package names of locked apps in a table called:

locks

and you want to call an activity named

PasswordActivity

when ever the users launch a locked app, you can implement a polling mechanism like below:

public class CheckAppLaunchThread extends Thread {

private Context context;
private Handler handler;
private ActivityManager actMan;
private int timer = 100;
public static final String TAG = "App Thread";
public static String lastUnlocked;

// private String lastUnlocked;

public CheckAppLaunchThread(Handler mainHandler, Context context) {
    this.context = context;
    this.handler = mainHandler;
    actMan = (ActivityManager) context
            .getSystemService(Context.ACTIVITY_SERVICE);
    this.setPriority(MAX_PRIORITY);
}

@Override
public void run() {
    context.startService(new Intent(context, AppLockService.class));
    Looper.prepare();
    String prevTasks;
    String recentTasks = "";

    prevTasks = recentTasks;
    Log.d("Thread", "Inside Thread");
    while (true) {
        try {
            String topPackageName = "";
            if(Build.VERSION.SDK_INT >= 21) {
                UsageStatsManager mUsageStatsManager = (UsageStatsManager) context.getSystemService("usagestats");                       
                long time = System.currentTimeMillis(); 
                // We get usage stats for the last 10 seconds
                List<UsageStats> stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000*5, time);                                    
                if(stats != null) {
                    SortedMap<Long,UsageStats> mySortedMap = new TreeMap<Long,UsageStats>();
                    for (UsageStats usageStats : stats) {
                        mySortedMap.put(usageStats.getLastTimeUsed(),usageStats);
                    }                    
                    if(mySortedMap != null && !mySortedMap.isEmpty()) {
                        topPackageName =  mySortedMap.get(mySortedMap.lastKey()).getPackageName();                                   
                    }                                       
                }
            }
            else {
                topPackageName = actMan.getRunningAppProcesses().get(0).processName;
            }
            recentTasks = topPackageName;
            Thread.sleep(timer);
            if (recentTasks.length()==0 || recentTasks.equals(
                    prevTasks)) {
            } else {
                if (isAppLocked(recentTasks)) {
                    Log.d(TAG, "Locked " + recentTasks);
                    handler.post(new RequestPassword(context, recentTasks));
                }
            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        prevTasks = recentTasks;

    }

}

class ToastRunnable implements Runnable {

    String message;

    public ToastRunnable(String text) {
        message = text;
    }

    @Override
    public void run() {
        Toast.makeText(context, message, Toast.LENGTH_SHORT).show();

    }
}

class RequestPassword implements Runnable {

    private Context mContext;
    private String pkgName;

    public RequestPassword(Context mContext, String pkgName) {
        this.mContext = mContext;
        this.pkgName = pkgName;
    }

    @Override
    public void run() {

        Intent passwordAct = new Intent(context, PasswordActivity.class);
        passwordAct.putExtra("PACKAGE_NAME", pkgName);
        passwordAct.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_SINGLE_TOP);
        this.mContext.startActivity(passwordAct);

    }

}

private boolean isAppLocked(String packageName) {
    if (packageName.equals(PasswordActivity.lastUnlocked)) {
        return false;
    }
    PasswordActivity.lastUnlocked = null;
    DatabaseHelper dbHelper = new DatabaseHelper(context);
    SQLiteDatabase db = dbHelper.getReadableDatabase();
    Cursor cursor = db.rawQuery("SELECT * FROM locks WHERE package_name=\'"
            + packageName + "\'", null);
    boolean isLocked = false;
    if (cursor.moveToNext()) {
        isLocked = true;
    }

    cursor.close();
    db.close();
    dbHelper.close();
    return isLocked;
}

}

Now you must call the above code from your service like this:

@Override
public void onCreate() {
    handler = new Handler(getMainLooper());
    context = getApplicationContext();
    launchChecker = new CheckAppLaunchThread(handler, context);
    super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    while (true) {
        if (!launchChecker.isAlive())
            launchChecker.start();
        return START_STICKY;

    }
}

Warning: Since Oreo, google has restricted background services and you must figure out a way to always keep your service alive. (that is not the scope of this question) for a clue on this, consider scheduling a JobService and a broadcast receiver that would reschedule your service when ever the android kills it.



来源:https://stackoverflow.com/questions/36261909/how-to-make-app-lock-app-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!