2 liuxiaoddd liuxiaoddd 于 2014.05.22 17:55 提问

android开的简单闹钟,模仿教程,出现问题求助

MainActivity.java如下
public class MainActivity extends ActionBarActivity {
private Button bt=null;
private AlarmManager am=null;
Calendar cal=Calendar.getInstance();
final int DIALOD_TIME=0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    am=(AlarmManager)getSystemService(ALARM_SERVICE);
    bt=(Button)findViewById(R.id.bt);
    bt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showDialog(DIALOD_TIME);
        }
    });
}

@Override
protected Dialog onCreateDialog(int id) {
    // TODO Auto-generated method stub
    Dialog dialog=null;
    switch(id){
    case DIALOD_TIME:
        dialog=new TimePickerDialog(this,new OnTimeSetListener() {

            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                Calendar c=Calendar.getInstance();
                //设置Calendar对象
                c.setTimeInMillis(System.currentTimeMillis());
                //设置时分秒毫秒
                c.set(Calendar.HOUR_OF_DAY,hourOfDay);
                c.set(Calendar.MINUTE,minute);
                c.set(Calendar.SECOND,0);
                c.set(Calendar.MILLISECOND,0);

                Intent intent=new Intent(MainActivity.this,AlarmReceiver.class);
                PendingIntent pi=PendingIntent.getBroadcast(MainActivity.this,0, intent, 0);
                am.set(AlarmManager.RTC_WAKEUP,c.getTimeInMillis(), pi);
                Toast.makeText(MainActivity.this,"闹钟设置成功",Toast.LENGTH_SHORT).show();
            }
        } , Calendar.HOUR_OF_DAY, Calendar.MINUTE,true);
        break;
    }
    return dialog;
}

}

主要在这两句,
Intent intent=new Intent(MainActivity.this,AlarmReceiver.class);
PendingIntent pi=PendingIntent.getBroadcast(MainActivity.this,0, intent, 0);
am.set(AlarmManager.RTC_WAKEUP,c.getTimeInMillis(), pi);
不知道为什么有时候闹钟会好,现在彻底不行了。。

AlarmReceiver.java如下
public class AlarmReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    Intent i=new Intent(context,AlarmActivity.class);
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(i);
    MediaPlayer mp = new MediaPlayer();
    try {
        mp.setDataSource(context, RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE));
    } catch (IllegalArgumentException | SecurityException
            | IllegalStateException | IOException e) {
        e.printStackTrace();
    }
    try {
        mp.prepare();
    } catch (IllegalStateException | IOException e) {
        e.printStackTrace();
    }
    mp.start();
}   

}
求高手解答,菜鸟一枚。。

Csdn user default icon
上传中...
上传图片
插入图片