Android编程实现闹钟的方法详解
本文实例讲述了Android编程实现闹钟的方法。分享给大家供大家参考,具体如下:
在Android中,有一个闹钟的类,AlarmManager类,我们可以通过其来对系统内的通知进行操作!
本文用到了Service和Broadcast两个后台管理,在处理时,曾出现过很多问题,但经过半天的努力,终于解决了!
首先是Main.xml文件:
<?xmlversion="1.0"encoding="utf-8"?> <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:id="@+id/mText" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <Button android:id="@+id/setTimeButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/setTimeButton" /> <Button android:id="@+id/cancelButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/cancelButton" /> </LinearLayout>
MainActivity.Java:
packagecom.chiefcto.Alarm; importjava.text.Format; importjava.util.Calendar; importandroid.app.Activity; importandroid.app.AlarmManager; importandroid.app.PendingIntent; importandroid.app.TimePickerDialog; importandroid.content.Intent; importandroid.os.Bundle; importandroid.view.View; importandroid.view.View.OnClickListener; importandroid.widget.Button; importandroid.widget.TextView; importandroid.widget.TimePicker; publicclassMainActivityextendsActivity{ //Properties privateButtonmsetButton; privateButtonmcancelButton; privateAlermReceiveruIReceiver; privateTextViewmTextView; //就用了Java的日历 privateCalendarcalendar; /**Calledwhentheactivityisfirstcreated.*/ @Override publicvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); calendar=Calendar.getInstance(); mTextView=(TextView)this.findViewById(R.id.mText); msetButton=(Button)this.findViewById(R.id.setTimeButton); mcancelButton=(Button)findViewById(R.id.cancelButton); msetButton.setOnClickListener(newOnClickListener(){ @Override publicvoidonClick(Viewv){ //TODOAuto-generatedmethodstub calendar.setTimeInMillis(System.currentTimeMillis()); inthour=calendar.get(Calendar.HOUR_OF_DAY); intminute=calendar.get(Calendar.MINUTE); newTimePickerDialog(MainActivity.this,newTimePickerDialog.OnTimeSetListener(){ @Override publicvoidonTimeSet(TimePickerview,inthourOfDay,intminute){ calendar.setTimeInMillis(System.currentTimeMillis()); //set(f,value)changesfieldftovalue. calendar.set(Calendar.HOUR_OF_DAY,hourOfDay); calendar.set(Calendar.MINUTE,minute); calendar.set(Calendar.SECOND,0); calendar.set(Calendar.MILLISECOND,0); Intentintent=newIntent(MainActivity.this,AlermReceiver.class); intent.putExtra("music",true); PendingIntentpendingIntent=PendingIntent.getBroadcast(MainActivity.this,0,intent,0); AlarmManageram; //获取系统进程 am=(AlarmManager)getSystemService(ALARM_SERVICE); am.set(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),pendingIntent); //设置周期!! am.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis()+(10*1000),(24*60*60*1000),pendingIntent); Stringtmps="设置闹钟时间为:"+format(hourOfDay)+":"+format(minute); mTextView.setText(tmps); } },hour,minute,true).show(); } }); mcancelButton.setOnClickListener(newOnClickListener(){ @Override publicvoidonClick(Viewv){ Intentintent=newIntent(MainActivity.this,AlermReceiver.class); intent.putExtra("music",true); PendingIntentpendingIntent=PendingIntent.getBroadcast(MainActivity.this,0,intent,0); AlarmManageram; //获取系统进程 am=(AlarmManager)getSystemService(ALARM_SERVICE); //cancel am.cancel(pendingIntent); mTextView.setText("取消了!"); } }); } privateStringformat(intx){ Strings=""+x; if(s.length()==1) s="0"+s; returns; } }
AlarmService.java
packagecom.chiefcto.Alarm; importjava.io.IOException; importandroid.app.Service; importandroid.content.Context; importandroid.content.Intent; importandroid.media.AudioManager; importandroid.media.MediaPlayer; importandroid.media.RingtoneManager; importandroid.net.Uri; importandroid.os.Binder; importandroid.os.Bundle; importandroid.os.IBinder; publicclassAlarmServiceextendsService{ //MediaPlayer实例 privateMediaPlayerplayer; //IBinder实例 @Override publicIBinderonBind(Intentintent){ playMusic(); returnnull; } @Override publicvoidonCreate(){ //TODOAuto-generatedmethodstub super.onCreate(); playMusic(); } @Override publicvoidonDestroy(){ //TODOAuto-generatedmethodstub super.onDestroy(); if(player!=null){ player.stop(); player.release(); } } @Override publicvoidonStart(Intentintent,intstartId){ //TODOAuto-generatedmethodstub super.onStart(intent,startId); if(intent!=null){ Bundlebundle=intent.getExtras(); if(bundle!=null){ if(bundle.getBoolean("music")) playMusic(); else stopMusic(); } } } publicvoidplayMusic(){ if(player==null){ Uriuri=RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM); try{ player=newMediaPlayer(); player.setDataSource(this,uri); finalAudioManageraudioManager=(AudioManager)this .getSystemService(Context.AUDIO_SERVICE); if(audioManager.getStreamVolume(AudioManager.STREAM_ALARM)!=0){ player.setAudioStreamType(AudioManager.STREAM_ALARM); player.setLooping(true); player.prepare(); } }catch(IllegalStateExceptione){ e.printStackTrace(); }catch(IOExceptione){ e.printStackTrace(); } } if(!player.isPlaying()){ player.start(); } } publicvoidstopMusic(){ if(player!=null){ player.stop(); try{ //在调用stop后如果需要再次通过start进行播放,需要之前调用prepare函数 player.prepare(); }catch(IOExceptionex){ ex.printStackTrace(); } } } }
下面就是本文的关键性代码,了解Activity到Broadcast的机制,这小应用就很好实现了~
AlermReceiver.java
packagecom.chiefcto.Alarm; importjava.io.IOException; importjava.util.Calendar; importandroid.content.BroadcastReceiver; importandroid.content.Context; importandroid.content.Intent; importandroid.media.AudioManager; importandroid.media.MediaPlayer; importandroid.media.RingtoneManager; importandroid.net.Uri; importandroid.os.Bundle; importandroid.util.Log; importandroid.widget.Toast; publicclassAlermReceiverextendsBroadcastReceiver{ privateMediaPlayermMediaPlayer; Contextcontext; @Override publicvoidonReceive(Contextcontext,Intentintent){ //TODOAuto-generatedmethodstub Calendarcalendar=Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); intminute=calendar.get(Calendar.MINUTE); CharSequencetext=String.valueOf(minute); Toast.makeText(context,text,Toast.LENGTH_LONG).show(); this.context=context; Bundlebundle=intent.getExtras(); IntentserviceIntent=newIntent("chief_musicService"); serviceIntent.putExtras(bundle); if(bundle!=null){ Log.i("CTO",String.valueOf(bundle.getBoolean("music"))); if(bundle.getBoolean("music")) context.startService(serviceIntent); else context.stopService(serviceIntent); } //在这里是播放不了的!! //playAlarmRing(); } privatevoidplayAlarmRing(){ Uriuri=RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM); try{ mMediaPlayer=newMediaPlayer(); mMediaPlayer.setDataSource(context,uri); finalAudioManageraudioManager=(AudioManager)context .getSystemService(Context.AUDIO_SERVICE); if(audioManager.getStreamVolume(AudioManager.STREAM_ALARM)!=0){ mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM); mMediaPlayer.setLooping(true); mMediaPlayer.prepare(); } }catch(IllegalStateExceptione){ e.printStackTrace(); }catch(IOExceptione){ e.printStackTrace(); } mMediaPlayer.start(); } privatevoidStopAlarmRing(){ mMediaPlayer.stop(); } }
要注意的是Mainifest.xml:
<?xmlversion="1.0"encoding="utf-8"?> <manifestxmlns:android="http://schemas.android.com/apk/res/android" package="com.chiefcto.Alarm" android:versionCode="1" android:versionName="1.0"> <uses-sdkandroid:minSdkVersion="7"/> <applicationandroid:icon="@drawable/icon"android:label="@string/app_name"> <activityandroid:name=".MainActivity" android:label="@string/app_name"> <intent-filter> <actionandroid:name="android.intent.action.MAIN"/> <categoryandroid:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> <serviceandroid:name=".AlarmService"> <intent-filter> <actionandroid:name="chief_musicService"/> <categoryandroid:name="android.intent.category.DEFAULT"/> </intent-filter> </service> <receiverandroid:name=".AlermReceiver"android:process=":remote"/> </application> <uses-permissionandroid:name="android.permission.MOUT_UNMOUNT_FILESYSTEMS"/> </manifest>
注:在模拟器中是运行不了的~
PS:关于AndroidManifest.xml文件相关属性功能可参考本站在线工具:
AndroidManifest功能与权限描述大全:
http://tools.jb51.net/table/AndroidManifest
希望本文所述对大家Android程序设计有所帮助。