欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android编程实用技术小结

程序员文章站 2023-12-20 19:11:52
本文实例总结了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程序设计有所帮助。

上一篇:

下一篇: