我想在一天中的特定时间启动此服务,但它不会响应。出现这种情况的原因是什么?
String time = sharedPrefs.getString("change_time", "");
String[] parts = time.split(":");
int chosenHour = Integer.parseInt(parts[0]);
int chosenMinute = Integer.parseInt(parts[1]);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, chosenHour);
cal.set(Calendar.MINUTE, chosenMinute);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Intent i = new Intent(this, SmsService.class);
PendingIntent pIntent = PendingIntent.getService(this, 0, i, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 86400000, pIntent);
return super.onStartCommand(intent, flags, startId);
答案 0 :(得分:0)
你把代码放在哪里?是在Service
内(我看到super.onStartCommand(intent, flags, startId)
吗?如果是,您是否开始提供服务?
为了安排AlarmManager
,我建议将代码放在Application#onCreate()
。
答案 1 :(得分:0)
从MainActivity中调用此metod:
private void setNotifyAlarm() {
long _alarm;
Calendar now = Calendar.getInstance();
Calendar wakeupcall = Calendar.getInstance();
wakeupcall.setTimeInMillis(System.currentTimeMillis());
wakeupcall.set(Calendar.HOUR_OF_DAY, 15);
wakeupcall.set(Calendar.MINUTE, 30);
if (wakeupcall.getTimeInMillis() <= now.getTimeInMillis())
_alarm=wakeupcall.getTimeInMillis() + (AlarmManager.INTERVAL_DAY+1);
else
_alarm=wakeupcall.getTimeInMillis();
al = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
notif= new Intent(this,NotifyService.class);
fintent = PendingIntent.getService(this,0,notif,0);
al.setRepeating(AlarmManager.RTC_WAKEUP,_alarm,AlarmManager.INTERVAL_DAY, fintent);
}
此方法呼叫服务每天15:30。 现在在您的服务类中:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String time = sharedPrefs.getString("change_time", "");
String[] parts = time.split(":");
int chosenHour = Integer.parseInt(parts[0]);
int chosenMinute = Integer.parseInt(parts[1]);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, chosenHour);
cal.set(Calendar.MINUTE, chosenMinute);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Intent i = new Intent(this, SmsService.class);
PendingIntent pIntent = PendingIntent.getService(this, 0, i, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 86400000, pIntent);
return START_STICKY;
}
在您的清单文件中添加以下内容:
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
<service android:name=".NotifyService" android:exported="true" android:enabled="true"/>