gpt4 book ai didi

android - 待定 Intent 获取服务

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:05:00 25 4
gpt4 key购买 nike

我在启动 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。提前致谢!

最佳答案

想通了!问题出在服务类中,我也改变了其他一些东西。但是,我认为主要问题是在我的服务类中的 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);
}

关于android - 待定 Intent 获取服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17959017/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com