Android编程实用技术小结

时间:2021-08-05 01:59:52

本文实例总结了Android编程实用技术。分享给大家供大家参考,具体如下:

1、捕获开机事件,启动receiver

?
1
2
3
4
5
6
<receiver android:name=".BootReceiver">
 <intent-filter>
 <action android:name="android.intent.action.BOOT_COMPLETED" />
 <category android:name="android.intent.category.HOME" />
 </intent-filter>
</receiver>
?
1
2
3
4
5
6
public class BootReceiver extends BroadcastReceiver {
 @Override
 public void onReceive(Context context, Intent intent) {
 context.startService(new Intent(context,MyService.class));//启动service
 }
}

2、启动service,设置闹钟频率,定时发起网络请求,获得数据

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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发出的广播,动态生成短信

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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

?
1
2
3
4
5
6
7
8
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程序设计有所帮助。