4

我在pendingIntent开火时遇到问题。我已经使用 logcat 等进行了一些故障排除,最后我几乎可以肯定我的问题实际上是在我的pendingIntent方法中。我设置的时间是正确的,并且该方法被调用,但在预定时间没有任何反应。这是我用来创建pendingIntent

public void scheduleAlarm(){
    Log.d("Alarm scheduler","Alarm is being scheduled");
    Intent changeVol = new Intent();
    changeVol.setClass(this, VolumeService.class);
    PendingIntent sender = PendingIntent.getService(this, 0, changeVol, 0);
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP, time, sender);
    //Toast.makeText(this, "Volume Adjusted!", Toast.LENGTH_LONG).show();
}

这是服务类:

public class VolumeService extends Service{

@Override
public void onCreate() {
    super.onCreate();
    Log.d("Service", "Service has been called.");
    Toast.makeText(getApplicationContext(), "Service Called!", Toast.LENGTH_LONG).show();
}

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

}

课堂上的日志scheduleAlarm()正在按我的计划工作,但没有任何反应,所以我认为它是我的pendingIntent. 提前致谢!

4

1 回答 1

8

弄清楚了!问题出在 Service 类中,我也改变了一些其他的东西。但是,我认为主要问题是在我的服务类中onCreate我试图运行我的代码的方法。但这需要在onStartCommand方法中完成

public class VolumeService extends Service{

@Override
public void onCreate() {
    super.onCreate();

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(getApplicationContext(), "Service started", Toast.LENGTH_LONG).show();
    return START_NOT_STICKY;
 }


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

}

并在启动服务的类中进行了一些更改,如下所示:

    public void scheduleAlarm(){
    Log.d("Alarm scheduler","Alarm is being scheduled");
    Intent intent = new Intent(AlarmSettings.this, VolumeService.class);
    PendingIntent pintent = PendingIntent.getService(AlarmSettings.this, 0, intent, 0);
    AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarm.set(AlarmManager.RTC_WAKEUP, time, pintent);
}
于 2013-07-31T20:50:02.837 回答