Android系列之指令短讯

这几天自己写了个手机防盗追踪软件,过程中遇到了些问题,在网友的帮助下得以解决
在这里总结一下;
软件中有这样一块功能:接收短信息,判断是否是指令短息,如果是则执行相应的操作(事先定义好的),
测试的时候发现系统也能接收指令短息并显示,并且短信铃声会响起(这不是预期的效果
预期的效果是系统可以正常接收非指令短息,遇到指令短息时不接受)
接收和发送短息的代码我就不提了;
解决方法:
在Manifest.xml中配置广播的优先级高于系统,
代码如下

 

  
    
1 < receiver android:name ="SmsReceiver" android:enabled ="true" >
2 < intent-filter android:priority ="100" >
3 < actionandroid:name ="android.provider.Telephony.SMS_RECEIVED" ></ action >
4   </ intent-filter >
5   </ receiver >

然后在指令短息执行完毕后终止广播,这样一来系统就接收不到指令短信啦
代码如下:

  
    
1 package com.xiaoqin.Test.mess.abo;
2
3 import android.content.BroadcastReceiver;
4 import android.content.Context;
5 import android.content.Intent;
6 import android.database.Cursor;
7 import android.net.Uri;
8 import android.os.Bundle;
9 import android.telephony.SmsManager;
10 import android.telephony.SmsMessage;
11 import android.util.Log;
12 import android.widget.Toast;
13
14 public class SmsReceiver extends BroadcastReceiver {
15
16 private static final String strRes = " android.provider.Telephony.SMS_RECEIVED " ;
17
18 @Override
19 public void onReceive(Context context, Intent intent) {
20 Log.d( " info " , " Now is Listening..... " );
21
22 /*
23 * 判断是否是SMS_RECEIVED事件被触发
24 */
25
26 if (intent.getAction().equals(strRes)) {
27 Bundle bundle = intent.getExtras();
28 if (bundle != null ) {
29 Object[] pdus = (Object[]) bundle.get( " pdus " );
30 SmsMessage[] msg = new SmsMessage[pdus.length];
31 for ( int i = 0 ; i < pdus.length; i ++ ) {
32 msg[i] = SmsMessage.createFromPdu(( byte []) pdus[i]);
33 }
34 for (SmsMessage currMsg : msg) {
35 String codeStr = currMsg.getDisplayMessageBody().substring(
36 0 , 3 );
37 String code1 = currMsg.getDisplayMessageBody().substring( 3 ,
38 4 );
39 if (codeStr.equals( " 000 " )) {
40 if (code1.equals( " 1 " )) {
41 Toast toast = Toast.makeText(context,
42 " 正在启动GPS防盗追踪... " , Toast.LENGTH_LONG);
43
44 toast.show();
45 abortBroadcast();
46 } else if (code1.equals( " 2 " )) {
47 Toast toast = Toast.makeText(context,
48 " 正在获取通讯录信息... " , Toast.LENGTH_LONG);
49 toast.show();
50 abortBroadcast();
51 } else if (code1.equals( " 3 " )) {
52 Toast toast = Toast.makeText(context,
53 " 正在监听短信 ... " , Toast.LENGTH_LONG);
54 toast.show();
55 abortBroadcast();
56 } else {
57 Toast toast = Toast.makeText(context,
58 " 不进行任何操作 ... " , Toast.LENGTH_LONG);
59 toast.show();
60 abortBroadcast();
61 }
62 }
63 }
64 }
65 }
66
67 }
68 }

 

你可能感兴趣的:(android)