我想在android中制作一个闹钟,我用BroadcastReceiver编写了这个,但是我有一些问题... 我想在指定的时间开始闹钟,例如,我想每3:50开始闹钟... 但是当我运行应用程序时,警报也开始...
下面是我的代码:
任何人都可以帮助我
有我的广播接收器:
public class MyBroadcastReceiver extends BroadcastReceiver {
public static MediaPlayer mediaPlayer;
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("com.tester.alarmmanager")) {
Toast.makeText(context, "Its time!!!", Toast.LENGTH_SHORT).show();
mediaPlayer = MediaPlayer.create(context, R.raw.entezar);
mediaPlayer.start();
}
}
}
在MainActivity中:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StartAlarm(03,50);
}
public void StartAlarm(int hour, int min){
Intent intent = new Intent(this, MyBroadcastReceiver.class);
intent.setAction("com.tester.alarmmanager");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(),23433,intent,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
Log.v("time picker",calendar.getTime()+"");
calendar.set(Calendar.HOUR_OF_DAY,hour);
calendar.set(Calendar.MINUTE,min);
calendar.set(Calendar.SECOND,00);
if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.KITKAT){
alarmManager.setExact(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),pendingIntent);
Toast.makeText(MainActivity.this, "Alarm>kitkat", Toast.LENGTH_SHORT).show();
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT){
alarmManager.set(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),pendingIntent);
Toast.makeText(MainActivity.this, "Alarm<kitkat", Toast.LENGTH_SHORT).show();
}
}
在清单中:
<receiver android:name=".Utility.MyBroadcastReceiver">
<intent-filter>
<action android:name="com.tester.alarmmanager"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</receiver>
答案 0 :(得分:0)
在calendar.getInstance()
之后添加
calendar.setTimeInMillis(System.currentTimeMillis())