3

我正在尝试使用警报管理器启动服务。我已经尝试了一切,但它只是没有开始。我从活动的按钮侦听器调用下面提到的代码。

    private void setAlarmManager(String interval) throws NumberFormatException, IOException
    {
        AlarmManager service = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        Intent i = new Intent(getApplicationContext(), MyService.class);

        PendingIntent pending = PendingIntent.getBroadcast(getApplicationContext(),
                                                           0,
                                                           i,
                                                           PendingIntent.FLAG_CANCEL_CURRENT);
        Calendar cal = Calendar.getInstance();

        cal.add(Calendar.MINUTE, Integer.valueOf(interval));
        service.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
                                    (Integer.valueOf(interval) * 60000), pending);
    }

我的清单看起来像:

<service android:enabled="true" android:name="com.pack.android.service.MyService"
            />

我正在尝试按照用户指定的时间(以分钟为单位)启动服务。但是我的服务永远不会被调用。

如果我使用以下代码调用该服务,它可以工作。我的项目目标版本是 16。

getApplicationContext().startService(i);
4

1 回答 1

4

更改PendingIntent.getBroadcastPendingIntent.getService使用PendingIntentas 启动服务:

PendingIntent pending = PendingIntent.getService(getApplicationContext(),
                                     0,
                                     i,
                                   PendingIntent.FLAG_CANCEL_CURRENT);
于 2013-01-26T12:18:49.290 回答