0

我想在两秒钟后重复运行下面给出的一段代码,我多次搜索解决方案并找到了这个。

下面给出的代码只能工作一段时间,因为 Timer 会在一段时间后被系统销毁。我还尝试了警报管理器,它会在 2 秒后启动服务,但即使服务不包含任何代码也会消耗太多内存。

请(它已经连续 3 天在谷歌上搜索解决方案),建议一些其他方法来每隔 2 秒在后台重复运行那一堆代码,而不会被系统破坏。

   Timer timer  =  new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {

            ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningAppProcessInfo> runningAppProcessInfo = am.getRunningAppProcesses();
            final ActivityManager.RunningAppProcessInfo appProcess =runningAppProcessInfo.get(0) ;


                currentAppName = appProcess.processName.toString();


                Handler handler = new Handler(Looper.getMainLooper());

                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        if(temp.equalsIgnoreCase(currentAppName))
                        {

                        }
                        else
                        {  Toast.makeText(MyService.this.getApplicationContext(),appProcess.processName.toString(),Toast.LENGTH_SHORT).show();
                            temp=""+currentAppName;

                         }

                    }
                });
            for(int i=0;i<LockedApps.LockedAppsList.size();i++) {

                if (appProcess.processName.toString().contains(LockedApps.preflist.get(i))) {
                    if (flag == 0) {

                        Intent x = new Intent(getApplicationContext(), LockActivity.class);
                        x.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(x);

                    }

                }
            }
4

1 回答 1

1

您分别使用了 Timer 和 AlarmManager。你为什么不试试 Timer 和 AlarmManager 的组合,我的意思是说每 30 秒或 60 秒重复一次警报来触发服务,这反过来会启动计时器。

于 2016-03-26T18:30:35.277 回答