Blocking any other application via Service

0

Talk, I'm creating a business application and I need to block any other application that the user tries to open. I'm creating a service for this, but it's not working.

When run, it does not see the other applications when opened by the user.

I read some other posts here, but I could not figure it out.

Below is my service.

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);

        startService(new Intent(this, clsServico.class));
    }

My class:

import android.app.ActivityManager;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Build;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;


public class clsServico extends Service {

    private static final long INTERVAL = TimeUnit.SECONDS.toMillis(2); // em segundos
    private static final String TAG = clsServico.class.getSimpleName();
    private static final String APS_BG = "APS_BG";

    private Thread t = null;
    private Context ctx = null;
    private boolean running = false;

    @Override
    public void onDestroy() {
        running =false;
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        running = true;
        ctx = this;

        // checa periodicamente se tem algum outro app na tela
        t = new Thread(new Runnable() {
            @Override
            public void run() {
                do {
                    //checkAPS();

                    try {
                        if(Build.VERSION.SDK_INT >= 21)
                            listTasks();
                        else
                            listTasks_SDK21();

                    } catch (PackageManager.NameNotFoundException e) {

                    }

                    try {
                        Thread.sleep(INTERVAL);
                    } catch (InterruptedException e) {
                    }
                }while(running);
                stopSelf();
            }
        });

        t.start();
        return Service.START_NOT_STICKY;
    }

    public void listTasks() throws PackageManager.NameNotFoundException {
        if(Build.VERSION.SDK_INT >= 21) {
            ActivityManager mgr = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.AppTask> tasks = mgr.getAppTasks();
            String packagename;
            String label;
            for (ActivityManager.AppTask task : tasks) {
                packagename = task.getTaskInfo().baseIntent.getComponent().getPackageName();
                label = getPackageManager().getApplicationLabel(getPackageManager().getApplicationInfo(packagename, PackageManager.GET_META_DATA)).toString();
                //Log.i(TAG, packagename + ":" + label);
            }
        }
    }

    public void listTasks_SDK21() throws PackageManager.NameNotFoundException {
        ActivityManager mgr = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RecentTaskInfo> tasks = mgr.getRecentTasks(20, 0);
        String packagename;
        String label;
        for(ActivityManager.RecentTaskInfo task: tasks){
            packagename = task.baseIntent.getComponent().getPackageName();
            label = getPackageManager().getApplicationLabel(getPackageManager().getApplicationInfo(packagename, PackageManager.GET_META_DATA)).toString();
            Log.i(TAG,packagename + ":" + label);
        }
    }

    private void checkAPS() {
        /*
        if(apenasAPSAtivado(ctx)) {
            if(isInBackground()) {
                restoreApp(); // tras p frente
            }
        }
        */

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

        ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);


        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;
            }
            //Log.i("packageName","" + p.packageName);
        }

        List<ActivityManager.RunningTaskInfo> RunningTask = mActivityManager.getRunningTasks(1);
        ActivityManager.RunningTaskInfo run = RunningTask.get(0);
        Log.i("topActivity", run.topActivity.getClassName());




        Intent ints = new Intent(Intent.ACTION_MAIN, null);
        ints.addCategory(Intent.CATEGORY_LAUNCHER);

        List<ResolveInfo> intentlist = packageManager.queryIntentActivities(ints, PackageManager.PERMISSION_GRANTED);

        List<ActivityManager.RunningTaskInfo> processes = mActivityManager.getRunningTasks(Integer.MAX_VALUE);

        String pName = "";

        if (processes != null)
        {
            for (int i = 0; i < processes.size(); i++) {
                String packageName = processes.get(i).topActivity.getPackageName();
                ActivityManager.RunningTaskInfo temp = processes.get(i);
                try
                {
                    pName = (String) packageManager.getApplicationLabel(packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA));
                }
                catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }

                //Log.i("RunningTaskInfo",pName + " : " + temp.id);
                /*
                if (savedapp.equals(pName)) {
                    // finish(pm.);
                    int code = intentlist.get(i).activityInfo.hashCode();
                    finishActivity(code);

                    mActivityManager.killBackgroundProcesses(packageName);
                    mActivityManager.restartPackage(packageName);
                    android.os.Process.killProcess(temp.id);
                    finishActivity(temp.id);
                }
                */

            }

        }


        List<ActivityManager.RunningTaskInfo> rt = mActivityManager.getRunningTasks(1000);
        for(int i = 0; i < rt.size(); i++){
            ActivityManager.RunningTaskInfo ar = rt.get(i);
            String activityOnTop=ar.topActivity.getClassName();
            //Log.i("rt", activityOnTop);
        }
        //ActivityManager.RunningTaskInfo ar = rt.get(0);
        //String activityOnTop=ar.topActivity.getClassName();
        //Log.i("activityOnTop", activityOnTop);


        //ActivityManager am = (ActivityManager)ctx.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> pids = mActivityManager.getRunningAppProcesses();
        for(int i = 0; i < pids.size(); i++)
        {
            ActivityManager.RunningAppProcessInfo p = pids.get(i);
            if(!p.processName.equalsIgnoreCase("nog.aps3")){
                android.os.Process.killProcess(p.pid);
                try {
                    android.os.Process.killProcess(p.pid);
                    android.os.Process.sendSignal(p.pid, android.os.Process.SIGNAL_KILL);
                    mActivityManager.killBackgroundProcesses(p.processName);
                } catch (Exception e) {
                    e.printStackTrace();
                    //Log.i("try", e.toString());
                }
            }

            //Log.i("info.processName", p.processName);
            //isInBackground();
        }

    }

    private boolean isInBackground() {
        ActivityManager am = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);

        List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
        ComponentName componentInfo = taskInfo.get(0).topActivity;
        //Log.i("getPackageName", ctx.getApplicationContext().getPackageName() +" =? "+ componentInfo.getPackageName());

        return (!ctx.getApplicationContext().getPackageName().equals(componentInfo.getPackageName()));
    }

    private void restoreApp() {
        //restore other class
    }

    public boolean apenasAPSAtivado(final Context context) {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
        return sp.getBoolean(APS_BG, false);
    }

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

Can anyone help me with this, pls?

    
asked by anonymous 18.10.2016 / 14:16

1 answer

0

Unfortunately you will not be able to prevent other applications from running.

This happens because each APP runs in a separate JVM, that is, each one runs in its "box" and none has access to what the other is doing.

Interactions between JVMs (including system applications) are done through intentions, which means that each application will decide how it will handle this request.

Putting in general, your process and everything in it can only be terminated by two "entities": Your own application or the Android system itself.

Some applications, such as "Memory Cleaners" do some workaround (usually causing the system to shut down background applications to ensure the usability of the foreground), but this is not exactly guaranteed.

If your intention is to "cap" the user, allowing him to use the device only for your application, you can try Android for Work , I did not get to test it, but from what I saw in the API 20+ devices you can use two accounts (one personal and one business) and some applications would only be available in the business account (and no other staff ).

    
18.10.2016 / 21:46