如何保存或阻止我的后台服务从强制停止或清除用户的任务

时间:2017-03-29 10:17:52

标签: java android eclipse android-studio service

你好朋友我正在创建一个Android应用程序锁定应用程序,用户可以锁定应用程序,我正在使用一个后台运行的后台服务。我的服务在所有设备上都运行良好,但在一些新设备中,如OPPO,Redme Mi和联想移动,有一个先进的功能,如用户可以从清洁工清理所有正在运行的任务,因为这个先进的功能,当用户清理所有任务我的服务也停止和应用程序锁定将无法工作,因此用户需要进入应用程序和手动启动服务是否有任何解决方案来保护我的服务。 app lock之一就有这种解决方案 https://play.google.com/store/apps/details?id=com.domobile.applock 这个应用程序服务是在干净的任务后启动我也想为我的应用程序做同样的我尝试了很多解决方案但没有得到任何结果我的服务代码如下所示

public class MyAppLockService extends Service {
public static int BuildV = 0;
public static final int NOTIFICATION_ID = 11259186;
private static boolean flag;
public static boolean isLauncher;
public static boolean isRunning;
public static ArrayList<String> locked_list;
public static String pack;
public static Thread th;
String currentHomePackage;
private boolean isRefreshedList;
boolean mAllowDestroy;
BroadcastReceiver mReciever;
private boolean mShowNotification;
UsageStatsManager mUsageStatsManager;
ActivityManager manager;
PowerManager pmanager;
SharedPreferences prefs;
public boolean run;
Timer f6t;
TimerTask tt;

class C02221 extends BroadcastReceiver {
    C02221() {
    }

    public void onReceive(Context context, Intent intent) {

        if (intent.getAction().equals(Utils.ACTION_UPDATE)) {
            MyAppLockService.this.refreshList();
        } else if (intent.getAction().equals(Utils.ACTION_STOP_SELF)) {
            MyAppLockService.this.doStopSelf();
        } else if (intent.getAction().equals(Utils.ACTION_REMOVE_APP)) {
            MyAppLockService.this.removeAppFromLockedList(intent
                    .getStringExtra("packName"));
        }
    }
}

@SuppressLint("NewApi")

class C02232 extends TimerTask {
    C02232() {
    }

    @SuppressLint("NewApi")
    public void run() {
        if (Utils.isScreenOn(MyAppLockService.this.pmanager)) {
            MyAppLockService.this.isRefreshedList = false;
            String current = "";
            try {
                current = Utils.getProcess(
                        MyAppLockService.this.mUsageStatsManager,
                        MyAppLockService.this.getApplicationContext());
            } catch (Exception e) {
                current = "";
            }
            if (current != null) {
                if (MyAppLockService.flag
                        && current
                                .equals(MyAppLockService.this.currentHomePackage)) {
                    if (MyAppLockService.this.prefs.getBoolean(
                            "immediately", true)) {
                        MyAppLockService.locked_list = new DBHelper(
                                MyAppLockService.this
                                        .getApplicationContext())
                                .getApsHasStateTrue();
                    }
                    MyAppLockService.flag = false;
                }
                if (!current
                        .equals(MyAppLockService.this.currentHomePackage)
                        && MyAppLockService.locked_list.contains(current)) {
                    Intent it;
                    if (MyAppLockService.BuildV >= 23) {
                        long endTime = System.currentTimeMillis();
                        UsageEvents usageEvents = MyAppLockService.this.mUsageStatsManager
                                .queryEvents(endTime - 10000, endTime);
                        Event event = new Event();
                        while (usageEvents.hasNextEvent()) {
                            usageEvents.getNextEvent(event);
                        }
                        if (current.equals(event.getPackageName())
                                && event.getEventType() == 1) {
                            MyAppLockService.pack = current;
                            if (MyAppLockService.this.prefs.getBoolean(
                                    "isPattern", false)) {
                                MyAppLockService.this
                                        .confirmPattern(current);
                            } else {
                                it = new Intent(
                                        MyAppLockService.this
                                                .getApplicationContext(),
                                        AppLockActivity.class);
                                it.setFlags(DriveFile.MODE_READ_ONLY);
                                MyAppLockService.this
                                        .getApplicationContext()
                                        .startActivity(it);
                            }
                            MyAppLockService.flag = true;
                            return;
                        }
                        return;
                    }
                    MyAppLockService.pack = current;
                    if (MyAppLockService.this.prefs.getBoolean("isPattern",
                            false)) {
                        MyAppLockService.this.confirmPattern(current);
                    } else {
                        it = new Intent(
                                MyAppLockService.this
                                        .getApplicationContext(),
                                AppLockActivity.class);
                        it.setFlags(DriveFile.MODE_READ_ONLY);
                        MyAppLockService.this.getApplicationContext()
                                .startActivity(it);
                    }
                    MyAppLockService.flag = true;
                }
            }
        } else if (!MyAppLockService.this.isRefreshedList) {
            MyAppLockService.this.refreshList();
        }
    }
}

public MyAppLockService() {
    this.run = true;
}

static {
    BuildV = VERSION.SDK_INT;
}

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

public void onCreate() {




    this.prefs = PreferenceManager
            .getDefaultSharedPreferences(getApplicationContext());
    this.manager = (ActivityManager) getApplicationContext()
            .getSystemService("activity");
    this.pmanager = (PowerManager) getApplicationContext()
            .getSystemService("power");
    if (BuildV >= 21) {
        this.mUsageStatsManager = (UsageStatsManager) getApplicationContext()
                .getSystemService("usagestats");
    }
    startNotification();
    Intent intent = new Intent("android.intent.action.MAIN");
    intent.addCategory("android.intent.category.HOME");
    this.currentHomePackage = getPackageManager().resolveActivity(intent,
            Cast.MAX_MESSAGE_LENGTH).activityInfo.packageName;
    this.mReciever = new C02221();
    IntentFilter filter = new IntentFilter(Utils.ACTION_UPDATE);
    filter.addAction(Utils.ACTION_STOP_SELF);
    filter.addAction(Utils.ACTION_REMOVE_APP);
    registerReceiver(this.mReciever, filter);
    refreshList();
    this.tt = new C02232();
    this.f6t = new Timer();
    this.f6t.schedule(this.tt, 500, 500);
    super.onCreate();
    Calendar cal = Calendar.getInstance();
    Intent intent12 = new Intent(getBaseContext(),MyAppLockService.class);
    PendingIntent pintent = PendingIntent.getService(getBaseContext(), 0, intent12, 0);
    AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),5, pintent);
}

public int onStartCommand(Intent intent, int flags, int startId) {
    return super.onStartCommand(intent, START_STICKY_COMPATIBILITY, startId);

}

public void onDestroy() {
    try {
        this.f6t.cancel();
        this.tt.cancel();
    } catch (Exception e) {
        e.printStackTrace();
    }

        Intent intent1 = new Intent("com.android.techtrainner");
        intent1.putExtra("yourvalue", "torestore");
        sendBroadcast(intent1);


}



public void refreshList() {
    locked_list = new DBHelper(getApplicationContext())
            .getApsHasStateTrue();
    if (locked_list.size() == 0) {
        doStopSelf();
    }
    this.isRefreshedList = true;
}

@SuppressLint({ "InlinedApi" })
private void startForegroundWithNotification() {
    PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this,
            Calculator_Activity.class), 0);
    String title = getString(R.string.app_name);
    String content = getString(R.string.app_name);
    Builder nb = new Builder(this);
    nb.setSmallIcon(R.drawable.ic_transparent);
    nb.setContentTitle(title);
    nb.setContentText(content);
    nb.setWhen(System.currentTimeMillis());
    nb.setContentIntent(pi);
    nb.setOngoing(true);
    nb.setPriority(0);
    startForeground(NOTIFICATION_ID, nb.build());
}

private void startNotification() {
    startForegroundWithNotification();
    if (!this.mShowNotification) {
        HelperService.removeNotification(this);
    }
}

private void doStopSelf() {
    this.mAllowDestroy = true;
    unregisterReceiver(this.mReciever);
    stopForeground(true);
    stopSelf();
}

private void confirmPattern(String st) {

    Intent pIntent = new Intent(getApplicationContext(),
            ResetActivity.class);
    pIntent.putExtra("isFromReset", true);
    PendingIntent pi = PendingIntent.getActivity(getApplicationContext(),
            12345, pIntent, DriveFile.MODE_READ_ONLY);

    Intent intent = new Intent(LockPatternActivity.ACTION_COMPARE_PATTERN, null,
            getApplicationContext(), LockPatternActivity.class);
    intent.putExtra("packName", st);
    intent.putExtra("isStealthMode", this.prefs.getBoolean(
            AlpSettings.Display.METADATA_STEALTH_MODE, false));
    intent.putExtra("isFromLock", true);
    intent.setFlags(DriveFile.MODE_READ_ONLY);
    intent.addFlags(Cast.MAX_MESSAGE_LENGTH);

    intent.putExtra(LockPatternActivity.EXTRA_PENDING_INTENT_FORGOT_PATTERN, pi);

    startActivity(intent);

}

private void removeAppFromLockedList(String packName) {
    locked_list.remove(packName);
}

如果有任何解决方案,那么请提前帮助我

2 个答案:

答案 0 :(得分:0)

当服务停止时重新启动服务,即系统将在已停止的服务上调用onDestroy()。

答案 1 :(得分:0)

  1. 在服务类中设置一个变量来检查服务是否正在运行。

  2. 让boolRuningService是一个变量

  3. Intent intent = new Intent(DashboardScreen.this,ServiceClass.class);      PendingIntent pintent = PendingIntent.getService(DashboardScreen.this,0,intent,0);

                        if(!ServiceClass.boolRuningService){
                               AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
                            alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30*1000, pintent);
                        }