Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make app lock app in android?

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.

like image 410
Vishnu Avatar asked Mar 28 '16 12:03

Vishnu


People also ask

How do I Lock apps on Android?

Launch the Settings app. Navigate to the Security option and click on it. Find the Lock screen setting and set a type of secure unlock (Knock Code, pattern, PIN, or password) . Tap on the Screen pin and the Pin to activate it.

Does Android have an AppLock?

AppLock – FingerprintAppLock – Fingerprint (yes, that's the app's name on the Play Store) is another very popular app locker on Android and deservedly so, because it packs in a ton of great features. There's support for fingerprint scanner, PIN, and you can set different passwords for different apps.

How do you Lock an app with a password?

First, go to the Settings app and open the General section. Next, please scroll down and navigate the Restrictions tab and open it; here, Enable Restrictions. Next, you will need to enter a new passcode and confirm it. Once the restrictions are enabled with a unique passcode, you are presented with various options.


2 Answers

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!

like image 134
The Bat Avatar answered Oct 19 '22 05:10

The Bat


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.

like image 45
sarpedon montecarlo Avatar answered Oct 19 '22 05:10

sarpedon montecarlo