0
所以我正在做這個項目,在確定的時間,手機會自動進入靜音模式(沒有聲音),有人在這裏建議我使用WakefulBroadcastReciever。我試着在這裏尋找一些關於它是如何工作的舊主題,並試圖在我的代碼中實現它,但無論我做什麼,它都不會在確定的時間開始。有人能幫我嗎?下面是代碼,其中hourStart和minuteStart由先前用戶確定:不能觸發WakefulBroadcastReciever
public void alarm(){
Calendar cur_cal = new GregorianCalendar();
cur_cal.setTimeInMillis(System.currentTimeMillis());//set the current time and date for this calendar
Calendar cal = new GregorianCalendar();
cal.add(Calendar.DAY_OF_YEAR, cur_cal.get(Calendar.DAY_OF_YEAR));
cal.set(Calendar.HOUR_OF_DAY, hourStart);
cal.set(Calendar.MINUTE, minuteStart);
Log.d("calendartimeValue", String.valueOf(cal.getTimeInMillis()));
cal.set(Calendar.SECOND, cur_cal.get(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, cur_cal.get(Calendar.MILLISECOND));
cal.set(Calendar.DATE, cur_cal.get(Calendar.DATE));
cal.set(Calendar.MONTH, cur_cal.get(Calendar.MONTH));
Intent intent = new Intent(this, SoundWakefulReceiver.class);
intent.setAction("SOUND_ACTION");
PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pintent);
}
public class SoundWakefulReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, SoundService.class);
Log.d("receiver", "receiver here !!");
startWakefulService(context, service);
}
}
public class SoundService extends IntentService {
public SoundService(String name) {
super(name);
}
@Override
protected void onHandleIntent(Intent intent) {
AudioManager amanager;
Log.d("service","service started!!");
amanager = (AudioManager)getSystemService(AUDIO_SERVICE);
amanager.setStreamMute(AudioManager.STREAM_SYSTEM, true);
SoundWakefulReceiver.completeWakefulIntent(intent);
}
}
P.S:我已經宣佈對清單中的「SOUND_ACTION」,並啓用了用戶有權修改的聲音。
謝謝你
WAKE_LOCK
許可!我不知道。我在Android編程方面有點新鮮。但是,即使使用權限= /,它仍然不起作用。如果我將WakefulBroadcast更改爲廣播並在alarm()函數上發送廣播,它可以正常工作,但這樣我就無法預先確定發送廣播的時間。 – Filipe您使用PendingIntent.getService似乎有點奇怪,但提供了一個旨在用於接收者的意圖。當警報被觸發時,系統會根據您的接收機意圖調用startService。我想你想要PendingIntent.getBroadcast? – JHH
耶,你說得對。我之前使用過getBroadcast,但由於它不工作,我試圖將其更改爲getService,以查看它是否會以這種方式工作,但隨後我將其更改回getBroadcast並在權限中進行了修改,但仍然無效。 – Filipe