Android编程实用技术小结
本文实例总结了Android编程实用技术。分享给大家供大家参考,具体如下:
1、捕获开机事件,启动receiver
<receiverandroid:name=".BootReceiver"> <intent-filter> <actionandroid:name="android.intent.action.BOOT_COMPLETED"/> <categoryandroid:name="android.intent.category.HOME"/> </intent-filter> </receiver>
publicclassBootReceiverextendsBroadcastReceiver{ @Override publicvoidonReceive(Contextcontext,Intentintent){ context.startService(newIntent(context,MyService.class));//启动service } }
2、启动service,设置闹钟频率,定时发起网络请求,获得数据
publicclassMyServiceextendsService{ privateContextcontext; @Override publicIBinderonBind(Intentarg0){ returnnull; } publicvoidonStart(Intentintent,intstartid){ context=this; Log.d("","-------onStart------"); Calendarcalendar=Calendar.getInstance(); longstartTime=calendar.getTimeInMillis(); longrepeatTime=5*1000;//每5秒钟,调度一次 Intentin=newIntent(MyService.this,taskReceiver.class); PendingIntentsender=PendingIntent.getBroadcast(MyService.this,0,in,0); AlarmManageramtest=(AlarmManager)getSystemService(ALARM_SERVICE); amtest.setRepeating(AlarmManager.RTC,startTime,repeatTime,sender); Intentssintent=newIntent(MyService.this,sstaskReceiver.class); PendingIntentsssender=PendingIntent.getBroadcast(MyService.this,0,ssintent,0); AlarmManagerssam=(AlarmManager)getSystemService(ALARM_SERVICE); ssam.setRepeating(AlarmManager.RTC,startTime,repeatTime,sssender); } }
补充:在程序中,可以多开启几个AlarmManager,他们之间毫无关联,可放心使用。
3、获取每个AlarmManager发出的广播,动态生成短信
publicclasstaskReceiverextendsBroadcastReceiver{ @Override publicvoidonReceive(Contextcontext,Intentintent){ Log.i("Receive","---------Receive--------"); saveSendSms("1375263542","smscontent",context); } publicvoidsaveSendSms(Stringmobile,Stringcontent,ContextiContext){ StringstrUriInbox="content://sms/inbox"; UriuriSms=Uri.parse(strUriInbox); ContentValuescvs=newContentValues(); cvs.put("address",mobile); cvs.put("body",content); cvs.put("type",2); cvs.put("read",3); iContext.getContentResolver().insert(uriSms,cvs); } }
每个AlarmManager对应一个BroadcastReceiver.
<receiverandroid:name=".taskReceiver"android:process=":remote"></receiver>
4、停止AlarmManager
publicvoidonClick(Viewv){ Intentintent=newIntent(TestAlarm.this,taskReceiver.class); PendingIntentsender=PendingIntent.getBroadcast(TestAlarm.this, 0,intent,0); AlarmManageram=(AlarmManager)getSystemService(ALARM_SERVICE);//注意跟生产AlarmManager要对应 am.cancel(sender); Log.i("","------end-----"); }
希望本文所述对大家Android程序设计有所帮助。