java 打开应用程序前的锁屏服务

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25562899/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 08:13:48  来源:igfitidea点击:

Service for Lock screen before opening app

javaandroidandroid-servicealarmmanagerandroid-pendingintent

提问by Rohit Tigga

I am trying to make an app in which there is a lock / password screen before you open selected apps to protect your apps.

我正在尝试制作一个应用程序,在您打开选定的应用程序以保护您的应用程序之前,其中有一个锁定/密码屏幕。

There are some on the market such as:

市场上有一些,例如:

https://play.google.com/store/apps/details?id=com.domobile.applock&hl=en

https://play.google.com/store/apps/details?id=com.domobile.applock&hl=en

Here is an open source one on GitHub. https://github.com/twinone/AppLocker

这是 GitHub 上的一个开源项目。https://github.com/twinone/AppLocker

I realized that even if the above apps are killed, or ram the is cleared, or the phone is restarted etc. The lock screen stills shows up for the selected application.

我意识到即使上述应用程序被杀死,或内存被清除,或手机重新启动等。锁定屏幕仍然显示所选应用程序。

Essentially I want to achieve the same thing that they did, but currently I am not achieving this currently with the service class I have written. I can lock the app, but when the app is killed I cannot. I have spent a great deal of time learning pending intents, alarm managers, broadcast receivers, and even studying example source code

基本上我想实现与他们所做的相同的事情,但目前我没有通过我编写的服务类实现这一点。我可以锁定应用程序,但是当应用程序被杀死时我不能。我花了大量时间学习待处理的意图、警报管理器、广播接收器,甚至研究示例源代码

https://github.com/twinone/AppLocker/blob/master/src/com/twinone/locker/lock/AppLockService.java

https://github.com/twinone/AppLocker/blob/master/src/com/twinone/locker/lock/AppLockService.java

but I am not successful in my implementation.

但我的实施并不成功。

Here is my service class:

这是我的服务类:

package com.ibc.android.demo.appslist.app;

import android.app.ActivityManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.util.Log;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
public class HeartBeat extends Service {



    private static final String TAG = HeartBeat.class.getSimpleName();
    public Timer TIMER;



    private static Set<AccessGranted> mAccessGrantedList = new HashSet<AccessGranted>();
    private Set<String> mLockedApps = new HashSet<String>();
    private long lastModified = 0;
    private BroadcastReceiver mScreenStateReceiver;
    private BroadcastReceiver mAccessGrantedReceiver;
    private File mLockedAppsFile;
    ArrayList<String> packagezList;
    SharedPreferences sharedPrefs;
    Map<String, ?> allEntries;
    SharedPreferences sharedPrefsapp;

    String prefix;





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


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


        startService(new Intent(this, HeartBeat.class));












        // Log.i("LocalService", "Received start id " + startId + ": " +
        // intent);
        // We want this service to continue running until it is explicitly
        // stopped, so return sticky.
        if (TIMER == null) {

            TIMER = new Timer(true);
            TIMER.scheduleAtFixedRate(new LockAppsTimerTask(), 1000, 250);

            mScreenStateReceiver = new BroadcastReceiver() {

                private boolean screenOff;

                @Override
                public void onReceive(Context context, Intent intent) {



                    if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
                        screenOff = true;
                    } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
                        screenOff = false;
                    }

                    if (screenOff) {
                        //Log.i(TAG, "Cancel Timer");
                        TIMER.cancel();
                    } else {
                       // Log.i(TAG, "Restart Timer");
                        TIMER = new Timer(true);
                        TIMER.scheduleAtFixedRate(new LockAppsTimerTask(), 1000, 250);
                    }
                }
            };

            IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
            filter.addAction(Intent.ACTION_SCREEN_OFF);
            registerReceiver(mScreenStateReceiver, filter);

            mAccessGrantedReceiver = new BroadcastReceiver() {

                @Override
                public void onReceive(Context context, Intent intent) {
                    String action = intent.getAction();
                    String packageName = intent.getStringExtra("packageName");
                    if (action.equals(Constants.ACTION_GRANT_ACCESS) && packageName != null) {
                        AccessGranted ag = new AccessGranted(packageName);
                        mAccessGrantedList.remove(ag);
                        mAccessGrantedList.add(ag);
                    }
                }
            };

            IntentFilter filter2 = new IntentFilter(Constants.ACTION_GRANT_ACCESS);
            registerReceiver(mAccessGrantedReceiver, filter2);
        }
        // this.stopSelf();



        //startforeground goes here



        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        startService(new Intent(this, HeartBeat.class));
    }




    private class LockAppsTimerTask extends TimerTask {




        @Override
        public void run() {


            sharedPrefs = getApplicationContext().getSharedPreferences(getApplicationContext().getPackageName(), Context.MODE_PRIVATE);
            sharedPrefsapp = getApplicationContext().getSharedPreferences("appdb", Context.MODE_PRIVATE);
            allEntries= null;
             allEntries = sharedPrefsapp.getAll();

            //prefix = "m";
            packagezList= null;


            packagezList = new ArrayList<String>();




            for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
                    //Log.e("right key: ", entry.getKey() + "right value: " + entry.getValue().toString()  );
                    packagezList.add(entry.getKey());





            }


/*        for (Map.Entry<String, ?> entry : allEntries.entrySet())
        {
            //Check if the package name starts with the prefix.
            if (entry.getKey().startsWith(prefix)) {
                //Add JUST the package name (trim off the prefix).
                packagezList.add(entry.getKey().substring(prefix.length()));
            packagezList.add(entry.getKey());

            }
        }*/

            for(Object object: packagezList){
                Log.e("YO!", (String) object);
            }








            ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);

            try {
                //List<RecentTaskInfo> recentTasks = activityManager.getRecentTasks(1, ActivityManager.RECENT_IGNORE_UNAVAILABLE);
                ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
                List<ActivityManager.RunningTaskInfo> RunningTask = mActivityManager
                        .getRunningTasks(1);
                ActivityManager.RunningTaskInfo ar = RunningTask.get(0);
                String activityOnTop = ar.topActivity.getPackageName();

                // Log.e("activity on Top", "" + activityOnTop);
                //   Log.e(" My package name", "" + getApplicationContext().getPackageName());








                //for (Object data : newArrayList) {

                for(Object object: packagezList){

// Provide the packagename(s) of apps here, you want to show password activity
                    if ((activityOnTop.contains((CharSequence) object)) &&
                            (!activityOnTop.contains(getApplicationContext().getPackageName()
                            ))) {  // you have to make this check even better


                        Intent i = new Intent(getApplicationContext(), LockScreenActivity.class);
                        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
                        i.putExtra( "", "");
                        startActivity(i);
                    }

                }


            } catch (Exception e) {
               // Log.e("Foreground App", e.getMessage(), e);
            }
        }



    }

} 

Here is my LockScreen activity class (the screen that is displayed when the selected app is open) :

这是我的 LockScreen 活动类(打开所选应用程序时显示的屏幕):

package com.ibc.android.demo.appslist.app;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;

import com.spicycurryman.getdisciplined10.app.R;

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

public class LockScreenActivity extends Activity {
    private static final String TAG = LockScreenActivity.class.getSimpleName();
    Map<String, ?> allEntries;
    SharedPreferences sharedPrefsapp;
    ArrayList<String> packagezList;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setup);

    }
    @Override
    public void onBackPressed() {



        // Grab a list of all running processes and their PIDs.
        ActivityManager am = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> pids = am.getRunningAppProcesses();

        // Now loop through the list of PIDs and find Instagram's PID.
        sharedPrefsapp = getApplicationContext().getSharedPreferences("appdb", Context.MODE_PRIVATE);
        allEntries= null;
        allEntries = sharedPrefsapp.getAll();

        //prefix = "m";
        packagezList= null;


        packagezList = new ArrayList<String>();




        for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
            //Log.e("right key: ", entry.getKey() + "right value: " + entry.getValue().toString()  );
            packagezList.add(entry.getKey());
        }


        // Killing any process for blocked applications when the back button is pressed while the lock screen is displayed

        for(Object object: packagezList){
            am.killBackgroundProcesses((String) object);
            Log.d("Killed Background Process!: ", (String) object);


        }



        // Now that we've got the PID, kill the Instagram process.


        // Now that we've got the PID, kill the Instagram process.

        ActivityManager  am1 = (ActivityManager) getApplicationContext().getSystemService(ACTIVITY_SERVICE);


        // Display confirmation here, finish() activity.
        Intent startMain = new Intent(Intent.ACTION_MAIN);
        startMain.addCategory(Intent.CATEGORY_HOME);
        startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(startMain);


        startService(new Intent(this, HeartBeat.class));


  /*      Intent iHeartBeatService = new Intent(this, HeartBeat.class);
        PendingIntent piHeartBeatService = PendingIntent.getService(this, 0, iHeartBeatService, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarmManager.cancel(piHeartBeatService);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 300000, piHeartBeatService);*/

        finish();
        super.onBackPressed();
    }

}

Right now I am able to lock the apps, but when the app is killed or phone is restarted I cannot. The app lock apps on the Google Play Store can successfully still lock apps with a pin when all apps are force stopped or when the phone is restarted, ram cleared, etc.

现在我可以锁定应用程序,但是当应用程序被杀死或手机重新启动时,我不能。当所有应用程序被强制停止或手机重新启动、内存清除等时,Google Play 商店中的应用程序锁定应用程序仍然可以成功地使用 PIN 锁定应用程序。

How can I achieve this like those have?

我怎样才能像那些人那样做到这一点?

回答by Rohit Tigga

I think u should try this ...

我想你应该试试这个...

     package com.ankit.vkapplock;

 import android.content.BroadcastReceiver;
 import android.content.Context;
 import android.content.Intent;
 import android.util.Log;

 public class StartupServiceReceiver extends BroadcastReceiver {
 @Override
 public void onReceive(Context context, Intent intent) {

    if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){

        context.startService(new Intent(context, HeartBeat.class  ));

}

Dont forget to add permisson for boot_completion action.

不要忘记为 boot_completion 操作添加权限。

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>