1

我让我的广播接收器设置重复警报,以启动服务。不幸的是,这不会导致服务被重复调用(基于 logcat)。我也尝试过不同的时间间隔值。有人可以帮忙吗?(我正在通过 Eclipse 在 Android 3.2 Motorola xoom 上进行测试)

下面是广播接收器的代码。

    alarm = (AlarmManager) arg0.getSystemService(Context.ALARM_SERVICE);
    Intent intentUploadService = new Intent (arg0, com.vikramdhunta.UploaderService.class);

    Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 3);

    PendingIntent pi = PendingIntent.getBroadcast(arg0, 0, intentUploadService , 0);
    alarm.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 5, pi);

下面是服务类的代码

    public UploaderService()
    {
        super("UploaderService");
        mycounterid = globalcounter++;
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        synchronized(this)
        {
            try
            {
                for (int i = 1;i < 5;i++)
                {
// doesn't do much right now.. but this should appear in logcat
                    Log.i(TAG,"OK " + globalcounter++ + " uploading..." + System.currentTimeMillis());

                }
            }
            catch(Exception e)
            {

            }
        }   
    }
     @Override
        public void onCreate() {
            super.onCreate();
            Log.d("TAG", "Service created.");
        }


        @Override
        public IBinder onBind(Intent arg0) {
            return null;
        }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) 
    {
        Log.i(TAG, "Starting upload service..." + mycounterid);
        return super.onStartCommand(intent,flags,startId);
    }
4

1 回答 1

2

好的 看起来我得到了这个。需要进行两项更改 -
1 - 我在需要执行 getService 时错误地使用了 PendingIntent.getBroadcast(见鬼,谁知道!)
2 - 在 getService 中,我应该在最后提供 PendingIntent.FLAG_UPDATE_CURRENT 而不是 0。FLAG_ONE_SHOT不工作。我想因为间隔只有 5 秒,所以这是正确的方法。

现在我得到了每 5 秒调用一次的正确服务/功能。欢呼!

于 2012-10-07T10:02:03.077 回答