Android编程实现闹钟的方法详解
程序员文章站
2023-12-17 20:08:52
本文实例讲述了android编程实现闹钟的方法。分享给大家供大家参考,具体如下:
在android中,有一个闹钟的类,alarmmanager类,我们可以通过其来对系统内...
本文实例讲述了android编程实现闹钟的方法。分享给大家供大家参考,具体如下:
在android中,有一个闹钟的类,alarmmanager
类,我们可以通过其来对系统内的通知进行操作!
本文用到了service
和broadcast
两个后台管理,在处理时,曾出现过很多问题,但经过半天的努力,终于解决了!
首先是main.xml文件:
<?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns: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:
package com.chiefcto.alarm; import java.text.format; import java.util.calendar; import android.app.activity; import android.app.alarmmanager; import android.app.pendingintent; import android.app.timepickerdialog; import android.content.intent; import android.os.bundle; import android.view.view; import android.view.view.onclicklistener; import android.widget.button; import android.widget.textview; import android.widget.timepicker; public class mainactivity extends activity { //properties private button msetbutton; private button mcancelbutton; private alermreceiver uireceiver; private textview mtextview; //就用了java的日历 private calendar calendar; /** called when the activity is first created. */ @override public void oncreate(bundle savedinstancestate) { 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(new onclicklistener() { @override public void onclick(view v) { // todo auto-generated method stub calendar.settimeinmillis(system.currenttimemillis()); int hour = calendar.get(calendar.hour_of_day); int minute = calendar.get(calendar.minute); new timepickerdialog(mainactivity.this, new timepickerdialog.ontimesetlistener() { @override public void ontimeset(timepicker view, int hourofday, int minute) { calendar.settimeinmillis(system.currenttimemillis()); //set(f, value) changes field f to value. calendar.set(calendar.hour_of_day, hourofday); calendar.set(calendar.minute, minute); calendar.set(calendar.second, 0); calendar.set(calendar.millisecond, 0); intent intent = new intent(mainactivity.this, alermreceiver.class); intent.putextra("music", true); pendingintent pendingintent = pendingintent.getbroadcast(mainactivity.this, 0, intent, 0); alarmmanager am; //获取系统进程 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); string tmps = "设置闹钟时间为:"+format(hourofday)+":"+format(minute); mtextview.settext(tmps); } },hour,minute,true).show(); } }); mcancelbutton.setonclicklistener(new onclicklistener() { @override public void onclick(view v) { intent intent = new intent(mainactivity.this, alermreceiver.class); intent.putextra("music", true); pendingintent pendingintent = pendingintent.getbroadcast(mainactivity.this, 0, intent, 0); alarmmanager am; //获取系统进程 am = (alarmmanager)getsystemservice(alarm_service); //cancel am.cancel(pendingintent); mtextview.settext("取消了!"); } }); } private string format(int x) { string s = ""+x; if(s.length() == 1) s = "0"+s; return s; } }
alarmservice.java
package com.chiefcto.alarm; import java.io.ioexception; import android.app.service; import android.content.context; import android.content.intent; import android.media.audiomanager; import android.media.mediaplayer; import android.media.ringtonemanager; import android.net.uri; import android.os.binder; import android.os.bundle; import android.os.ibinder; public class alarmservice extends service { // mediaplayer实例 private mediaplayer player; // ibinder实例 @override public ibinder onbind(intent intent) { playmusic(); return null; } @override public void oncreate() { // todo auto-generated method stub super.oncreate(); playmusic(); } @override public void ondestroy() { // todo auto-generated method stub super.ondestroy(); if (player != null) { player.stop(); player.release(); } } @override public void onstart(intent intent, int startid) { // todo auto-generated method stub super.onstart(intent, startid); if (intent != null) { bundle bundle = intent.getextras(); if (bundle != null) { if(bundle.getboolean("music")) playmusic(); else stopmusic(); } } } public void playmusic() { if(player == null) { uri uri = ringtonemanager.getdefaulturi(ringtonemanager.type_alarm); try { player = new mediaplayer(); player.setdatasource(this, uri); final audiomanager audiomanager = (audiomanager)this .getsystemservice(context.audio_service); if (audiomanager.getstreamvolume(audiomanager.stream_alarm) != 0) { player.setaudiostreamtype(audiomanager.stream_alarm); player.setlooping(true); player.prepare(); } } catch (illegalstateexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } } if(!player.isplaying()) { player.start(); } } public void stopmusic() { if (player != null) { player.stop(); try { // 在调用stop后如果需要再次通过start进行播放,需要之前调用prepare函数 player.prepare(); } catch (ioexception ex) { ex.printstacktrace(); } } } }
下面就是本文的关键性代码,了解activity到broadcast的机制,这小应用就很好实现了~
alermreceiver.java
package com.chiefcto.alarm; import java.io.ioexception; import java.util.calendar; import android.content.broadcastreceiver; import android.content.context; import android.content.intent; import android.media.audiomanager; import android.media.mediaplayer; import android.media.ringtonemanager; import android.net.uri; import android.os.bundle; import android.util.log; import android.widget.toast; public class alermreceiver extends broadcastreceiver { private mediaplayer mmediaplayer; context context; @override public void onreceive(context context, intent intent) { // todo auto-generated method stub calendar calendar = calendar.getinstance(); calendar.settimeinmillis(system.currenttimemillis()); int minute = calendar.get(calendar.minute); charsequence text = string.valueof(minute); toast.maketext(context, text, toast.length_long).show(); this.context = context; bundle bundle = intent.getextras(); intent serviceintent = new intent("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(); } private void playalarmring() { uri uri = ringtonemanager.getdefaulturi(ringtonemanager.type_alarm); try { mmediaplayer = new mediaplayer(); mmediaplayer.setdatasource(context, uri); final audiomanager audiomanager = (audiomanager) context .getsystemservice(context.audio_service); if (audiomanager.getstreamvolume(audiomanager.stream_alarm) != 0) { mmediaplayer.setaudiostreamtype(audiomanager.stream_alarm); mmediaplayer.setlooping(true); mmediaplayer.prepare(); } } catch (illegalstateexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } mmediaplayer.start(); } private void stopalarmring() { mmediaplayer.stop(); } }
要注意的是mainifest.xml:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.chiefcto.alarm" android:versioncode="1" android:versionname="1.0"> <uses-sdk android:minsdkversion="7" /> <application android:icon="@drawable/icon" android:label="@string/app_name"> <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> <service android:name=".alarmservice"> <intent-filter> <action android:name="chief_musicservice"/> <category android:name="android.intent.category.default"/> </intent-filter> </service> <receiver android:name=".alermreceiver" android:process=":remote"/> </application> <uses-permission android:name="android.permission.mout_unmount_filesystems"/> </manifest>
注:在模拟器中是运行不了的~
ps:关于androidmanifest.xml文件相关属性功能可参考本站在线工具:
android manifest功能与权限描述大全:
http://tools.jb51.net/table/androidmanifest
更多关于android相关内容感兴趣的读者可查看本站专题:《android开发入门与进阶教程》、《android调试技巧与常见问题解决方法汇总》、《android基本组件用法总结》、《android视图view技巧总结》、《android布局layout技巧总结》及《android控件用法总结》
希望本文所述对大家android程序设计有所帮助。