Wednesday 14 August 2019

Run Kiosk-Like' Fashion Android Application.

Android can run tasks in an immersive, kiosk-like fashion called lock task mode. You might use lock task mode if you’re developing a kiosk application or a launcher to present a collection of apps. When the system runs in lock task mode, device users typically can’t see notifications, access non-white-listed apps, or return to the home screen (unless the home screen is white-listed).
Lock task mode and screen pinning are sometimes used interchangeably. Screen pinning appears similar but the person using the device can exit the mode whenever they want.

Let us see how it is done programmatically,

Refer the below link for complete sample code:-

Download Sample Code

Have a look on few code snippets,

//AdminReceiver.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.elitetechnologies.locktaskmode;
import android.app.admin.DeviceAdminReceiver;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.UserManager;
import android.widget.Toast;

public class AdminReceiver extends DeviceAdminReceiver {
    private static final String KIOSK_PACKAGE = "com.facebook.katana";
    private static final String CURRENT_PACKAGE = "com.elitetechnologies.locktaskmode";
    private static final String[] APP_PACKAGES = {KIOSK_PACKAGE,CURRENT_PACKAGE};

    @Override
    public void onProfileProvisioningComplete(Context context, Intent intent) {
        super.onProfileProvisioningComplete(context, intent);
        // Enable the profile
        DevicePolicyManager manager =
                (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
        ComponentName deviceAdmin = getWho(context);
        manager.setProfileName(deviceAdmin, context.getString(R.string.app_name));
        // Open the main screen
        Intent launch = new Intent(context, MainActivity.class);
        launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(launch);
    }

    @Override
    public void onEnabled(Context context, Intent intent) {
        super.onEnabled(context, intent);
        Toast.makeText(context, context.getString(R.string.device_admin_enabled), Toast.LENGTH_SHORT).show();

       /* DevicePolicyManager dpm = getManager(context);
        ComponentName deviceAdmin = getWho(context);
        dpm.setLockTaskPackages(deviceAdmin, APP_PACKAGES);*/
    }

    @Override
    public CharSequence onDisableRequested(Context context, Intent intent) {
        return context.getString(R.string.device_admin_warning);
    }

    @Override
    public void onDisabled(Context context, Intent intent) {
        Toast.makeText(context, context.getString(R.string.device_admin_disabled), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onLockTaskModeEntering(Context context, Intent intent, String pkg) {
        Toast.makeText(context, context.getString(R.string.kiosk_mode_enabled), Toast.LENGTH_SHORT).show();
        /*DevicePolicyManager dpm = getManager(context);
        ComponentName admin = getWho(context);
        dpm.addUserRestriction(admin, UserManager.DISALLOW_CREATE_WINDOWS);*/
    }

    @Override
    public void onLockTaskModeExiting(Context context, Intent intent) {
        Toast.makeText(context, context.getString(R.string.kiosk_mode_disabled), Toast.LENGTH_SHORT).show();
    }
}

//BackgroundService.java
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package com.elitetechnologies.locktaskmode;

import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.ActivityManager;
import android.app.Service;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.util.Log;


public class BackgroundService extends Service {
    private Context context;
    private static Timer timer = new Timer();

    public BackgroundService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        startService();
    }

    /**
     * This method is used to start service backgroundly.
     */
    private void startService() {
        timer.scheduleAtFixedRate(new mainTask(), 0, 500);
        context = this;
    }

    private class mainTask extends TimerTask {
        public void run() {
            handler.sendEmptyMessage(0);
        }
    }

    /**
     * This handler is used to check which is top activity.
     */
    private final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            getTopActivity(context);
//            boolean IsMyServiceRunning = isMyServiceRunning(context);
//            System.out.println("IsMyServiceRunning: " + IsMyServiceRunning);
        }
    };


    public boolean isMyServiceRunning(Context context) {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (BackgroundService.class.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }


    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public void getTopActivity(Context context) {
        try {
            UsageStatsManager usageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
            long milliSecs = 60 * 1000;
            Date date = new Date();
            List<UsageStats> queryUsageStats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, date.getTime() - milliSecs, date.getTime());
            long recentTime = 0;
            String packageName = "";
            for (int i = 0; i < queryUsageStats.size(); i++) {
                UsageStats stats = queryUsageStats.get(i);
                if (stats.getLastTimeStamp() > recentTime) {
                    recentTime = stats.getLastTimeStamp();
                    packageName = stats.getPackageName();
                }
            }
            System.out.println("packageName: "+packageName);

            SharedPreferences prefs = getSharedPreferences(getPackageName(), MODE_PRIVATE);
                int password = prefs.getInt("password", 0); //0 is the default value.



            if(!packageName.equalsIgnoreCase("")
                    && !packageName.equalsIgnoreCase(getPackageName())
                    && !"com.facebook.katana".equalsIgnoreCase(packageName)
                    && !packageName.contains("com.google")
                    && password!=1234){
            Intent intent = new Intent(context, LockScreenActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
                    Intent.FLAG_ACTIVITY_CLEAR_TASK |
                    Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

//LockScreenActivity.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package com.elitetechnologies.locktaskmode;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.PersistableBundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class LockScreenActivity extends AppCompatActivity {
    private TextView tv_lockmsg;
    private EditText et_lockpassword;
    private Button btn_lockok;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lockscreen);
        tv_lockmsg = (TextView) findViewById(R.id.tv_lockmsg);
        et_lockpassword=(EditText)findViewById(R.id.et_lockpassword);
        btn_lockok=(Button)findViewById(R.id.btn_lockok);

        new CountDownTimer(15000, 1000) {

            public void onTick(long millisUntilFinished) {
                tv_lockmsg.setText("You are locked out of the app: \n " + millisUntilFinished / 1000+"secs \nremaining");
            }

            public void onFinish() {
                finish();
                Intent i = getPackageManager().getLaunchIntentForPackage("com.facebook.katana");
                startActivity(i);
            }

        }.start();

        btn_lockok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    SharedPreferences.Editor editor = getSharedPreferences(getPackageName(), MODE_PRIVATE).edit();
                    editor.putInt("password", Integer.parseInt(et_lockpassword.getText().toString()));
                    editor.apply();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

//MainActivity.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import android.app.Activity;
import android.app.ActivityOptions;
import android.app.AppOpsManager;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.os.UserHandle;
import android.provider.Settings;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
import java.io.IOException;

public class MainActivity extends Activity {

    public ImageButton ib_startkioske;

    private View mDecorView;
    private DevicePolicyManager mDpm;
    private boolean mIsKioskEnabled = false;
    // Whitelist two apps.
    private static final String KIOSK_PACKAGE = "com.facebook.katana";
    private static final String CURRENT_PACKAGE = "com.elitetechnologies.locktaskmode";
    private static final String[] APP_PACKAGES = {KIOSK_PACKAGE, CURRENT_PACKAGE};
    private ComponentName deviceAdmin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ib_startkioske = (ImageButton) findViewById(R.id.ib_startkioske);
        ib_startkioske.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // enableKioskMode(!mIsKioskEnabled);
//                if (mDpm.isLockTaskPermitted(getPackageName())) {
                //startLockTask();
                    startService(new Intent(MainActivity.this, BackgroundService.class));
                try {
                    SharedPreferences.Editor editor = getSharedPreferences(getPackageName(), MODE_PRIVATE).edit();
                    editor.putInt("password", 0);
                    editor.apply();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                finish();
                Intent i = getPackageManager().getLaunchIntentForPackage("com.facebook.katana");
                startActivity(i);
//                }
            }
        });


        boolean usage_granted = false;
        AppOpsManager appOps = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE);
        int mode = appOps.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, android.os.Process.myUid(), getPackageName());
        if (mode == AppOpsManager.MODE_DEFAULT) {
            usage_granted = (checkCallingOrSelfPermission(android.Manifest.permission.PACKAGE_USAGE_STATS) == PackageManager.PERMISSION_GRANTED);
        } else {
            usage_granted = (mode == AppOpsManager.MODE_ALLOWED);
        }

        if (usage_granted == false) {
            Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
            startActivity(intent);
        }
        Intent it = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
        it.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, new ComponentName(this, AdminReceiver.class));
        startActivityForResult(it, 0);
    }

}