Android编程实用技术小结
程序员文章站
2024-02-17 09:53:40
本文实例总结了android编程实用技术。分享给大家供大家参考,具体如下:
1、捕获开机事件,启动receiver
本文实例总结了android编程实用技术。分享给大家供大家参考,具体如下:
1、捕获开机事件,启动receiver
<receiver android:name=".bootreceiver"> <intent-filter> <action android:name="android.intent.action.boot_completed" /> <category android:name="android.intent.category.home" /> </intent-filter> </receiver>
public class bootreceiver extends broadcastreceiver { @override public void onreceive(context context, intent intent) { context.startservice(new intent(context,myservice.class));//启动service } }
2、启动service,设置闹钟频率,定时发起网络请求,获得数据
public class myservice extends service{ private context context; @override public ibinder onbind(intent arg0) { return null; } public void onstart(intent intent, int startid) { context = this; log.d("", "-------onstart------"); calendar calendar=calendar.getinstance(); long starttime = calendar.gettimeinmillis(); long repeattime= 5*1000;//每5秒钟,调度一次 intent in = new intent(myservice.this,taskreceiver.class); pendingintent sender = pendingintent.getbroadcast(myservice.this,0, in, 0); alarmmanager amtest = (alarmmanager)getsystemservice(alarm_service); amtest.setrepeating(alarmmanager.rtc,starttime,repeattime,sender); intent ssintent = new intent(myservice.this,sstaskreceiver.class); pendingintent sssender = pendingintent.getbroadcast(myservice.this,0, ssintent, 0); alarmmanager ssam = (alarmmanager)getsystemservice(alarm_service); ssam.setrepeating(alarmmanager.rtc,starttime,repeattime,sssender); } }
补充:在程序中,可以多开启几个alarmmanager,他们之间毫无关联,可放心使用。
3、获取每个alarmmanager发出的广播,动态生成短信
public class taskreceiver extends broadcastreceiver{ @override public void onreceive(context context, intent intent) { log.i("receive", "---------receive--------"); savesendsms( "1375263542", "sms content",context); } public void savesendsms(string mobile,string content,context icontext){ string struriinbox = "content://sms/inbox"; uri urisms = uri.parse(struriinbox); contentvalues cvs = new contentvalues(); cvs.put("address", mobile); cvs.put("body", content); cvs.put("type", 2); cvs.put("read", 3); icontext.getcontentresolver().insert(urisms, cvs); } }
每个alarmmanager对应一个broadcastreceiver.
复制代码 代码如下:
<receiver android:name=".taskreceiver" android:process=":remote"></receiver>
4、停止alarmmanager
public void onclick(view v) { intent intent = new intent(testalarm.this,taskreceiver.class); pendingintent sender = pendingintent.getbroadcast(testalarm.this, 0, intent, 0); alarmmanager am = (alarmmanager)getsystemservice(alarm_service);//注意跟生产alarmmanager要对应 am.cancel(sender); log.i("", "------end-----"); }
希望本文所述对大家android程序设计有所帮助。
推荐阅读
-
Android编程实用技术小结
-
Android编程中FileOutputStream与openFileOutput()的区别分析
-
Android编程实现动态更新ListView的方法
-
Android编程实现自定义toast示例
-
Android编程实现自定义toast示例
-
Android编程设置TextView颜色setTextColor用法实例
-
Android编程之控件状态配置文件实例
-
Android编程之include文件的使用方法
-
Android编程实现popupwindow弹出后屏幕背景变成半透明效果
-
Android编程实现canvas绘制柱状统计图功能【自动计算宽高及分度值、可左右滑动】