Как я могу сделать надежный AppLock в Android? - PullRequest
0 голосов
/ 10 апреля 2020

Я уже некоторое время пытаюсь заставить приложение блокировки приложений работать, но мне не удается заставить его работать надежно.

Вот вам пример моего сервиса. Комментируемая часть и сервис как таковые имеют ту же проблему: они иногда не читают верхнюю активность. Например, я пытался заблокировать Youtube, но когда я go перехожу на Youtube, иногда пакет переднего плана, который появляется в журналах, имеет вид com.google.android.apps.nexuslauncher.NexusLauncherActivity, так что, как будто нет изменений с Launcher на Youtube.

Закомментированная функция и некомментированная Thread + Runnable - две версии, которые я пробовал, они не предназначены для совместной работы, просто у меня есть обе возможности пробовать обе стороны.

Эта служба должен иметь список со всеми заблокированными приложениями, и всякий раз, когда он обнаруживает, что приоритетное действие является одним из перечисленных в списке, откройте действие, говорящее «Это приложение заблокировано», и закройте заблокированное приложение. Не удалось сделать это надежно, и нигде не смог найти ничего полезного. Я пробовал примеры здесь и ничего тоже. Пробовал последний пример на этом веб-сайте StackOverflow, и по какой-то причине служба даже не запускается.

package com.example.adictic.service;

import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;

import androidx.annotation.Nullable;

import com.example.adictic.R;
import com.example.adictic.activity.BlockActivity;
import com.example.adictic.activity.MainActivity;

import java.util.ArrayList;
import java.util.List;

public class RunService extends Service {

    List<String> blockedApps = new ArrayList();
    Context mContext;

    ActivityManager mActivityManager;
    List<ActivityManager.RunningTaskInfo> RunningTask;
    ActivityManager.RunningTaskInfo ar;
    String activityOnTop;
    Intent lockIntent;

    private Runnable appLock = new Runnable() {
        @Override
        public void run() {
            while(true){
                mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);

                RunningTask = mActivityManager.getRunningTasks(1);
                ar = RunningTask.get(0);
                activityOnTop=ar.topActivity.getClassName();

                System.out.println(activityOnTop);

                if(blockedApps.contains(activityOnTop) || activityOnTop.equals("com.google.android.youtube")){
                    mContext = getApplicationContext();
                    lockIntent = new Intent(mContext, BlockActivity.class);
                    lockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    mContext.startActivity(lockIntent);
                }
            }
        }
    };

    Thread t = new Thread(appLock);

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

    @Override
    public void onCreate(){
        if(!t.isAlive()) t.start();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId){
        super.onStartCommand(intent, flags, startId);

        if(!t.isAlive()) t.start();

        startForeground();

        return START_STICKY;
    }

//    private void getForegroundTask() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
//        String currentApp = "NULL";
//        if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
//            UsageStatsManager usm = (UsageStatsManager) this.getSystemService(Context.USAGE_STATS_SERVICE);
//            long time = System.currentTimeMillis();
//            List<UsageStats> appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY,  time - 1000*1000, time);
//            if (appList != null && appList.size() > 0) {
//                SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
//                for (UsageStats usageStats : appList) {
//                    mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
//                }
//                if (!mySortedMap.isEmpty()) {
//                    currentApp = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
//                }
//            }
//        } else {
//            ActivityManager am = (ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);
//            List<ActivityManager.RunningAppProcessInfo> tasks = am.getRunningAppProcesses();
//            currentApp = tasks.get(0).processName;
//        }
//
//        System.out.println("CURRENT APP: " + currentApp);
//
//        if(currentApp.equals("com.google.android.youtube")){
//            ActivityManager am = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
//            Method forceStopPackage;
//            forceStopPackage =am.getClass().getDeclaredMethod("forceStopPackage",String.class);
//            forceStopPackage.setAccessible(true);
//            forceStopPackage.invoke(am,currentApp);
//
//            Intent dialogIntent = new Intent(this, BlockActivity.class);
//            dialogIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
//            startActivity(dialogIntent);
//        }
//    }

    private void startForeground(){

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Intent notificationIntent = new Intent(this, MainActivity.class);
            PendingIntent pendingIntent =
                    PendingIntent.getActivity(this, 0, notificationIntent, 0);

            NotificationChannel nch = createNotificationChannel();

            Notification notification =
                    new Notification.Builder(this, nch.getId())
                            .setContentTitle(getString(R.string.app_name))
                            .setContentText("Service is running background")
                            .setSmallIcon(R.drawable.ic_launcher_foreground)
                            .setContentIntent(pendingIntent)
                            .setTicker("Ticker")
                            .build();

            startForeground(1, notification);
        }
    }

    private NotificationChannel createNotificationChannel() {
        // Create the NotificationChannel, but only on API 26+ because
        // the NotificationChannel class is new and not in the support library
        NotificationChannel channel = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = "Back";
            String description = "";
            int importance = NotificationManager.IMPORTANCE_LOW;
            channel = new NotificationChannel("AdicTIC", name, importance);
            channel.setSound(null, null);
            channel.setDescription(description);
            // Register the channel with the system; you can't change the importance
            // or other notification behaviors after this
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
        return channel;
    }
}

Есть идеи, как это сделать?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...