使用broadcastreceiver监听短信

来源:互联网 发布:tl494引脚功能和数据 编辑:程序博客网 时间:2024/04/28 07:58

最近接的一个小项目,监听短信,如果短信中包含某字符串(比如“#回复码”),则自动回复内容。

功能很简单,就涉及到两块知识点:broadcastreceiver的静态动态注册短信类的使用

项目的完成参考的此篇博客:http://blog.csdn.net/mad1989/article/details/22426415

先说说broadcastreceiver的注册问题:

1、静态注册:

        <receiver android:name="jianghuai.automessage.MsgReceiver" >            <intent-filter android:priority="999" >                <action android:name="android.provider.Telephony.SMS_RECEIVED" />            </intent-filter>        </receiver>

静态注册很简单,在AndroidManifest.xml配置文件中添加receiver标签,并设置其filter为

"android.provider.Telephony.SMS_RECEIVED"

剩下的就是写一个Receiver类,并重写onReceive方法。


2、动态注册:

动态注册就是在activity中动态对receiver进行注册。

//动态注册broadcastreceivermsgReceiver = new MsgReceiver();IntentFilter filter = new IntentFilter();filter.addAction("android.provider.Telephony.SMS_RECEIVED");MainActivity.this.registerReceiver(msgReceiver, filter);
如上面的示例代码,一个IntentFilter类和一个写好的Receiver类,通过filter.addAction将需要监听的内容添加进来,并调用registerReceiver来进行注册。

动态注册还需要注意在activity中还需要动态注销,如下

@Overrideprotected void onDestroy() {super.onDestroy();MainActivity.this.unregisterReceiver(msgReceiver);}

在activity中的onDestroy方法中,调用unregisterReceiver方法来注销receiver。


短信类的使用:SmsMessage类

java.lang.Object   ↳android.telephony.SmsMessage

常用的几个方法:

getOriginatingAddress() 获得发来短信的号码

getDisplayMessageBody 获得短信内容

getTimestampMillis 获得短信时间


另外这个小项目中,用到了SharedPreferences类来对数据进行持久化。

将数据存入SharedPreferences。

sharedPreferences = getSharedPreferences("autoMsg",Context.MODE_PRIVATE);Editor editor = sharedPreferences.edit();
editor.putString("custom_submsg", submsg);editor.putString("custom_reply", auto_reply);editor.commit();

从SharedPreferences取出数据:

sharedPreferences = context.getSharedPreferences("autoMsg",Context.MODE_PRIVATE);submsg = sharedPreferences.getString("custom_submsg", "");



最后贴下完整的代码:

MainActivity

package jianghuai.automessage;import android.app.Activity;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;import android.content.SharedPreferences;import android.content.SharedPreferences.Editor;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast;public class MainActivity extends Activity {//自定义拦截内容private String submsg;//自定义短信内容private String auto_reply;//自定义拦截内容和自定义短信内容的输入框private EditText edit_submsg, edit_auto_reply;private Button button;//显示自定义拦截内容和自定义回复短信内容的TextViewprivate TextView tv_submsg, tv_auto_reply;SharedPreferences sharedPreferences;private MsgReceiver msgReceiver;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);/*//动态注册broadcastreceivermsgReceiver = new MsgReceiver();IntentFilter filter = new IntentFilter();filter.addAction("android.provider.Telephony.SMS_RECEIVED");MainActivity.this.registerReceiver(msgReceiver, filter);*/edit_submsg = (EditText) findViewById(R.id.edit_submsg);button = (Button) findViewById(R.id.submit);tv_submsg = (TextView) findViewById(R.id.tv_submsg);edit_auto_reply = (EditText) findViewById(R.id.edit_auto_reply);tv_auto_reply = (TextView) findViewById(R.id.tv_auto_reply);/* * 将自动拦截内容和自动回复内容存储在autoMsg文件中, * 键值为custom_submsg和custom_reply */sharedPreferences = getSharedPreferences("autoMsg",Context.MODE_PRIVATE);final Editor editor = sharedPreferences.edit();tv_submsg.setText("当前自定义拦截内容为:"+ sharedPreferences.getString("custom_submsg", ""));tv_auto_reply.setText("当前自定义回复内容为:"+ sharedPreferences.getString("custom_reply", ""));// 提交输入框中的短信拦截内容和自动回复内容button.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// 获得自定义拦截短信内容submsg = edit_submsg.getText().toString();// 获得自定义回复短信内容auto_reply = edit_auto_reply.getText().toString();//将键值对保存在文件中,并提交editor.putString("custom_submsg", submsg);editor.putString("custom_reply", auto_reply);editor.commit();tv_submsg.setText("当前自定义拦截内容为:"+ sharedPreferences.getString("custom_submsg", ""));tv_auto_reply.setText("当前自定义回复内容为:"+ sharedPreferences.getString("custom_reply", ""));Toast.makeText(getApplicationContext(), "自定义拦截内容,回复内容提交成功",Toast.LENGTH_SHORT).show();}});}@Overrideprotected void onDestroy() {super.onDestroy();//MainActivity.this.unregisterReceiver(msgReceiver);}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {// Handle action bar item clicks here. The action bar will// automatically handle clicks on the Home/Up button, so long// as you specify a parent activity in AndroidManifest.xml.int id = item.getItemId();if (id == R.id.action_settings) {return true;}return super.onOptionsItemSelected(item);}}


MsgReceiver.java
package jianghuai.automessage;import java.text.SimpleDateFormat;import java.util.Date;import java.util.regex.Matcher;import java.util.regex.Pattern;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.content.SharedPreferences;import android.os.Bundle;import android.telephony.SmsManager;import android.telephony.SmsMessage;public class MsgReceiver extends BroadcastReceiver {// 收到的短信内容private String recvmsg;// 拦截的内容private String submsg;// 自动回复内容private String auto_reply;SharedPreferences sharedPreferences;public static final String DEFAULT_SUBMSG = "#回复码";public static final String DEFAULT_REPLY = "上门维修";// 正则表达式public static final String regex = "\\[[A-Z]+\\]";@Overridepublic void onReceive(Context context, Intent intent) {Bundle bundle = intent.getExtras();SmsMessage msg = null;if (null != bundle) {Object[] smsObj = (Object[]) bundle.get("pdus");for (Object object : smsObj) {msg = SmsMessage.createFromPdu((byte[]) object);Date date = new Date(msg.getTimestampMillis());// 时间SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String receiveTime = format.format(date);System.out.println("number:" + msg.getOriginatingAddress()+ "   body:" + msg.getDisplayMessageBody() + "  time:"+ msg.getTimestampMillis());recvmsg = msg.getDisplayMessageBody();// 拿到sharedPreferences,并获得其中的拦截内容edit_detailsharedPreferences = context.getSharedPreferences("autoMsg",Context.MODE_PRIVATE);submsg = sharedPreferences.getString("custom_submsg", "");// 获得自定义回复内容auto_reply = sharedPreferences.getString("custom_reply", "");// 如果没有输入拦截内容,则使用默认的拦截条件if (submsg.equals("")) {// 没有输入内容,使用默认的“#回复码”if (recvmsg.contains(DEFAULT_SUBMSG)) {SmsManager smsManager = SmsManager.getDefault();if (auto_reply.equals("")) {smsManager.sendTextMessage(msg.getOriginatingAddress(), null, "JD"+ pickString(recvmsg) + "#"+ DEFAULT_REPLY, null, null);} else {smsManager.sendTextMessage(msg.getOriginatingAddress(), null, "JD"+ pickString(recvmsg) + "#"+ auto_reply, null, null);}}} else {// submsg的过滤条件不为空,当短信检测到时,自动回复if (recvmsg.contains(submsg)) {SmsManager smsManager = SmsManager.getDefault();if (auto_reply.equals("")) {smsManager.sendTextMessage(msg.getOriginatingAddress(), null,DEFAULT_REPLY, null, null);} else {smsManager.sendTextMessage(msg.getOriginatingAddress(), null,auto_reply, null, null);}}}}}}/* * 提取验证码 传入短信内容msg.getDisplayMessageBody() */public String pickString(String str) {String result = "";Pattern pattern = Pattern.compile(regex);Matcher m = pattern.matcher(str);if (m.find()) {result = (String) m.group().subSequence(1, 4);}return result;}}

Activity的布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="jianghuai.automessage.MainActivity"    android:orientation="vertical" >        <TextView         android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="系统默认:包含 #回复码 内容的短信为自动回复短信,如果使用默认拦截和默认回复,请保证下面输入框为空后提交"        />    <EditText         android:id="@+id/edit_submsg"        android:layout_width="match_parent"        android:layout_height="80dp"        android:hint="在此编辑短信拦截内容"        />        <TextView        android:id="@+id/tv_submsg"         android:layout_width="match_parent"        android:layout_height="wrap_content"        />        <View         android:layout_width="match_parent"        android:layout_height="4dp"        android:layout_marginTop="20dp"        android:background="#000000"        android:layout_marginBottom="10dp"        />        <EditText        android:id="@+id/edit_auto_reply"         android:layout_width="match_parent"        android:layout_height="80dp"        android:hint="请输入自动回复内容"        />        <TextView        android:id="@+id/tv_auto_reply"         android:layout_width="match_parent"        android:layout_height="wrap_content"        />        <Button         android:id="@+id/submit"        android:layout_width="wrap_content"        android:layout_height="40dp"        android:text="提交自定义内容"        android:layout_gravity="right"        />        <TextView         android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="TIPS:输入框不填,提交后,短信拦截内容和自动回复会使用系统默认(#回复码,JD***#上门维修),否则使用自定义内容。"        /></LinearLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="jianghuai.automessage"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="14"        android:targetSdkVersion="14" />    <uses-permission android:name="android.permission.RECEIVE_SMS" >    </uses-permission>    <uses-permission android:name="android.permission.READ_SMS" >    </uses-permission>    <uses-permission android:name="android.permission.SEND_SMS" >    </uses-permission>    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name=".MainActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <receiver android:name="jianghuai.automessage.MsgReceiver" >            <intent-filter android:priority="999" >                <action android:name="android.provider.Telephony.SMS_RECEIVED" />            </intent-filter>        </receiver>    </application></manifest>


github地址:https://github.com/lovekun/AutoMessage


0 0
原创粉丝点击