1
我正在嘗試製作一個應用程序,允許用戶使用兩個TimePickers輸入兩次,手機將在這些時間之間設置爲無聲。我正在使用PendingIntent和AlarmManager在用戶選擇的時間觸發BroadcastReceiver。 目前,當用戶點擊保存按鈕時,立即開啓和關閉手機。然後我的「鬧鐘預定」烤麪包就會出現,我的「收到的廣播」會出現兩次,但在此之後它什麼也不做。待處理意圖立即觸發
這裏是我的主要活動代碼:
public class MainActivity extends AppCompatActivity {
AlarmManager alarm;
TimePicker timePickerStart;
TimePicker timePickerEnd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timePickerStart = (TimePicker)findViewById(R.id.timePickerStart);
timePickerStart.setIs24HourView(true);
timePickerEnd = (TimePicker)findViewById(R.id.timePickerEnd);
timePickerEnd.setIs24HourView(true);
}
//method is called when save button is clicked
public void setAlarm(View view) {
Calendar calendarStart;
Calendar calendarEnd;
calendarStart = Calendar.getInstance();
calendarEnd = Calendar.getInstance();
//Set calendars to the times in both TimePickers
calendarStart.set(Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH, timePickerStart.getCurrentHour(), timePickerStart.getCurrentMinute());
long startTimeMillis = calendarStart.getTimeInMillis();
calendarEnd.set(Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH, timePickerEnd.getCurrentHour(), timePickerEnd.getCurrentMinute());
long endTimeMillis = calendarEnd.getTimeInMillis();
//create an intent and set the class that will be triggered by the intent
Intent intent = new Intent(MainActivity.this, Receiver.class);
PendingIntent pIntent = null;
pIntent = PendingIntent.getBroadcast(this, 123, intent, PendingIntent.FLAG_UPDATE_CURRENT);
//create alarm manager
alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
//set alarms to go off at the time specified by the timePickers
alarm.set(AlarmManager.RTC_WAKEUP, calendarStart.getTimeInMillis(), pIntent);
alarm.set(AlarmManager.RTC_WAKEUP, calendarEnd.getTimeInMillis(), pIntent);
//Toast for feedback
Toast.makeText(this, "Alarm Scheduled", Toast.LENGTH_SHORT).show();
}
這裏是我的廣播接收器:
public class Receiver extends BroadcastReceiver {
AudioManager audioManager;
int modeNum;
@Override
public void onReceive(Context context, Intent intent) {
//toast for feedback
Toast.makeText(context, "Broadcast Received", Toast.LENGTH_SHORT).show();
audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
modeNum = audioManager.getRingerMode();
if (modeNum == 0) {
audioManager.setRingerMode(2);
} else {
audioManager.setRingerMode(0);
}
}
}
這是我的清單:
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".Receiver"></receiver>
</application>