我应该如何使用alarmmanager每天和中午12点运行服务

时间:2012-01-25 14:48:48

标签: android notifications broadcastreceiver alarmmanager

我正在尝试每天晚上7点开通一项新服务,这会在启动时通知我,但我无法解决这个问题,也无法理解原因。任何人都可以帮我谢谢谢谢这里是代码


这是我在DaysCounterActivity类中编写的代码

    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, 19);
    calendar.set(Calendar.MINUTE, 05);
    calendar.set(Calendar.SECOND, 00);


    Intent intent = new Intent(this, MyReciever.class);
    PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0);


    AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24*60*60*1000 , pintent);

这里是MyReviever类onRevcieve方法

    public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub

    Intent serviceIntent = new Intent();
    serviceIntent.setAction("com.saaram.MyService");
    context.startService(serviceIntent);
}

1 个答案:

答案 0 :(得分:3)

您的问题是pintent正在尝试运行服务,但MyReceiver是广播接收器。如果您将MyReceiver更改为服务,则会有效。

public class MyReceiver extends Service {


    public int onStartCommand(Intent intent, int flags, int startId) {
        //Anything you put here is run at the time you set the alarm to
        }

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
        }

    }

在你的清单中,你只需要声明它:

<service android:name=".MyReceiver"></service>