繁体   English   中英

使用Alarm Manager启动服务

[英]Starting service using Alarm Manager

我正在尝试使用Alarm Manager启动服务。 我尝试了一切,但它还没有开始。 我从一个活动的按钮监听器调用下面提到的代码。

    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);

PendingIntent.getBroadcast更改为PendingIntent.getService以使用PendingIntent启动服务:

PendingIntent pending = PendingIntent.getService(getApplicationContext(),
                                     0,
                                     i,
                                   PendingIntent.FLAG_CANCEL_CURRENT);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM