使用AlarmManager每20秒运行一次Android服务不会在从应用程序列表中删除该应用程序时重新启动 [英] Running an Android Service after every 20 sec using AlarmManager doesn't restart on killing the app from the app list

查看:90
本文介绍了使用AlarmManager每20秒运行一次Android服务不会在从应用程序列表中删除该应用程序时重新启动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试运行一个Android服务,该服务每20秒在后台运行一次,并将用户的经纬度数据发送到服务器以进行跟踪.当我启动我的应用程序时,它第一次起作用.现在,如果我单击主页"按钮,它将仍在后台运行.但是,现在,如果我使用主页按钮从应用程序列表中杀死了我的应用程序.然后使用启动器图标重新启动我的应用程序.现在该服务无法启动.我使用警报管理器每20秒触发一次服务.但是在重新启动时,设置了我的警报,但未在广播接收器上注册,因此未调用我的服务.下面是我的代码:- MyFragment.java的onCreateView(),我在其中设置我的闹钟":-

I am trying to run an Android Service which runs in background every 20 sec and send user's lat-long data to server for tracking. It works for the first time when I launch my application. Now If I click the Home Button, It still runs in the background. But, now if I kill my application from the app list using the home button. And restart my App with the launcher icon. Now the Service doesn't start. I am using Alarm Manager to trigger my service after every 20 sec. But on Restart my Alarm is set but doesn't registers on Broadcast Receiver, as a Result My Service is not called. Below is my code:- MyFragment.java's onCreateView() where I am setting My Alarm:-

Intent alarm = new Intent(mContext, AlarmReceiver.class);
    boolean alarmRunning = (PendingIntent.getBroadcast(mContext, 0, alarm, PendingIntent.FLAG_NO_CREATE) != null);
    if (alarmRunning == false) {
        Log.e("In OnCreateView DDFrag", "AlarmRunning == False");
        PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, alarm, 0);
        AlarmManager alarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 20000, pendingIntent);
    } else{
        Log.e("In OnCreateView DDFrag", "AlarmRunning == True");
    }

AlarmReceiver.class :-

    public class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent background = new Intent(context, MyService.class);
        Log.e("AlarmReceiver", "Broadcasr Receiver started");
        context.startService(background);
    }
}

MyService.class :-

    public class MyService extends Service {

    public boolean isServiceRunning;

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

    @Override
    public void onCreate() {
        this.isServiceRunning = false;
    }



    @Override
    public void onDestroy() {
        this.isServiceRunning = false;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if(!this.isServiceRunning) {
            sendDataToServer();
            this.isServiceRunning = true;
        }
        return START_STICKY;
    }


    private void sendDataToServer() {
        // Performing my operation in this method..
    // On Success of the method performed I am calling the below method and setting the below variables:
    stopSelf();
        this.isServiceRunning = false;
    }
}

我还要在 manifest.xml文件中将我的服务和接收方定义为:-

Also I am defining my service and receiver in the manifest.xml file as:-

<service android:name="com.mypackagename.services.MyService" />

    <receiver android:name="com.mypackagename.services.AlarmReceiver" />

请帮助我解决问题,或指出我在做什么.作为第一次.由于未设置我的警报管理器,因此设置了该属性,并且在大约20秒钟后调用了该服务.但是,如果我终止我的应用程序并再次启动它,则将设置我的闹钟",使其不再启动或再次设置.现在我的AlarmReceiver类从没有收到Alarm BroadcastReceiver.

Please help me to resolve the issue, or point me what i am doing wroung. As For the first time. as my Alarm manager is not set, it sets and the service is called after 20 sec appropiatley. But if I kill my application and start it again, then My Alarm is set so it doesn't start or set again. and now my AlarmReceiver class never receives the Alarm BroadcastReceiver.

推荐答案

以下是一些内容:

请删除设置警报的"alarmRunning"代码.一直都在做.如果已设置警报,则再次设置只会取消旧警报并设置新警报.这不是问题.

Please remove the "alarmRunning" code where you set the alarms. Just do it all the time. If the alarm is already set, setting it again will just cancel the old one and set a new one. This isn't a problem.

您不能依靠 PendingIntent 的存在来确定是否在警报管理器中设置了警报.这很可能是在终止并重新启动您的应用后没有任何警报的原因.

You cannot rely on the existence of a PendingIntent to determine whether or not an alarm is set in the alarm manager. This is most likely the reason why you get no alarms after killing and restarting your app.

此外,您不能使用 setRepeating()每20秒可靠地安排一次警报.Android具有严格的电源管理规则,并且不会在大多数设备上可靠地触发少于2分钟的重复警报.您可能会看到此警报在2或3或5分钟而不是20秒后响起,具体取决于电源管理设置,电池电量,设备的繁忙程度,是否处于睡眠状态等等.

Also, you cannot reliably schedule an alarm every 20 seconds using setRepeating(). Android has strict power management rules and will not reliably trigger a repeating alarm that is less than 2 minutes on most devices. You might see this alarm going off after 2 or 3 or 5 minutes instead of 20 seconds, depending on the power management settings, battery level, busyness of the device, whether it is sleeping, etc.

如果您真的希望每20秒运行一次,则应该设置一个警报,当该警报消失时,对其进行处理,然后将下一个警报设置为现在的20秒.

If you really want something running every 20 seconds then you should set a single alarm and when that alarm goes off, process it and set the next alarm for 20 seconds from now.

这篇关于使用AlarmManager每20秒运行一次Android服务不会在从应用程序列表中删除该应用程序时重新启动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆