用ContentObserver监听发出的短信的信息日志
效果
代码
package com.javen.devicemange.CrazyOne.content; import android.Manifest; import android.database.ContentObserver; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.Toast; import com.javen.devicemange.R; import java.text.SimpleDateFormat; /** * Created by Administrator on 2017/2/17 0017. * 用ContentObserver监听发出的短信的信息日志 * 需要申请的权限 * <uses-permission android:name="android.permission.READ_SMS"/> */ public class MonitorSms extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.monitorsms); //申请读取短信的权限 requestPermission(); //注册监听器,监听Uri为content://sms的数据改变 getContentResolver().registerContentObserver(Uri.parse("content://sms"), true, new SmsObserver(new Handler())); } private void requestPermission() { String[] needPermissions = { Manifest.permission.READ_SMS, }; ActivityCompat.requestPermissions(this, needPermissions, 1); } //提供自定义的ContentObserver监听器类 private final class SmsObserver extends ContentObserver { /** * Creates a content observer. * * @param handler The handler to run {@link #onChange} on, or null if none. */ public SmsObserver(Handler handler) { super(handler); } @Override public void onChange(boolean selfChange) { super.onChange(selfChange); //查询发送箱("content://sms/outbox")中的短信(处于正在发送状态的短信放在发送箱) Cursor cursor = getContentResolver().query(Uri.parse("content://sms/outbox"), null, null, null, null); //遍历查询得到的结果集,即可获取用户正在发送的短信 while (cursor.moveToNext()) { StringBuilder stringBuilder = new StringBuilder(); //获取短信的发送地址,如:10086 stringBuilder.append("address=").append(cursor.getString(cursor.getColumnIndex("address"))); //标题 stringBuilder.append(";subject=").append(cursor.getString(cursor.getColumnIndex("subject"))); //内容 stringBuilder.append(";body=").append(cursor.getString(cursor.getColumnIndex("body"))); //发送时间 String dateNumber = cursor.getString(cursor.getColumnIndex("date")); //把毫秒值的时间值(1487314423408)转换成(2017-02-17 15:02:22) Long time = Long.valueOf(dateNumber); Log.d("GsonUtils", "time=" + time); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String date = sdf.format(time); Log.d("GsonUtils", "date=" + date); stringBuilder.append(";date=").append(date); Log.d("GsonUtils", "stringBuilder=" + stringBuilder.toString()); //打印发送的短信提示信息 Toast.makeText(MonitorSms.this, "stringBuilder=" + stringBuilder.toString(), Toast.LENGTH_LONG).show(); } } } }
布局xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> </LinearLayout>
。。。