1

我正在尝试为 Android 应用程序创建一个简单的应用程序锁。所以我创建了这样的应用程序锁定服务

package com.company.applock;

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

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

import com.company.applock.LockscreenActivity;


public class LockService extends Service {
    private static boolean isLock = false;
    private Timer timer;


    // Static Getters and setters
    public static boolean isLock() {
        return isLock;
    }

    public static void setLock(boolean lock) {
        isLock = lock;
    }

    // Public static method to start service
    public static void start(Context context) {
        Intent intent = new Intent(context, LockService.class);
        context.startService(intent);
    }

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

    @Override
    public void onCreate() {
        timer = new Timer("LockService");
        timer.schedule(checkLockTask, 500L, 500L);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (null != intent) { }
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        timer.cancel(); timer = null;
    }

    // Custom methods
    private boolean isForegroundLocked() {
        ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);

        Log.d("topActivity", taskInfo.get(0).topActivity.getClassName());

        return taskInfo.get(0).topActivity.getClassName().equals("com.company.applock.LockscreenActivity");
    }

    private void showLockActivity() {
        Intent intent = new Intent(getApplicationContext(), LockscreenActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);

        Log.d("showLockActivity", "success");
    }

    private TimerTask checkLockTask = new TimerTask() {
        @Override
        public void run() {
            // TODO: Fix foreground bug
            if (isLock) {
                Log.d("isLock", "true");
                if (isForegroundLocked()) {
                    Log.d("isForegroundLocked", "true");
                } else {
                    Log.d("isForegroundLocked", "false");
                    showLockActivity();
                }
            } else {
                Log.d("isLock", "false");
                // TODO: Close lock screen
            }
        }
    };
}

如您所见,这是非常简单的一个。问题是;

  1. 当我按下主页按钮并进入启动器时,它会在几秒钟后锁定(通常是 4 或 5 秒)
  2. 如果我从最近的任务中删除我的主要活动(这不是锁屏活动),服务就会停止(当我按下主页按钮时它不会停止)。

所以,任何知道这些问题的解决方案的人,请帮助我。我是安卓新手。

谢谢你。

4

0 回答 0