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

Android读取系统短信(短信窃听器)

程序员文章站 2022-05-31 11:46:19
...

1、清单文件AndroidManifest.xml需要获取短信的权限

Android读取系统短信(短信窃听器)

2、MainActivity.java中通过内容解析器(ContentResolver)读取系统短信

package com.t20.sms;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.database.Cursor;
import android.view.View;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}
	/**
	 * 获取系统短信
	 * @param v
	 */
	public void sms(View v){
		//获取内容解析器(ContentResolver)
		ContentResolver resolver= getContentResolver();
		//定义一个URI(Uniform Resource Identifier 统一资源标示符)
		//查全部短信
		Uri uri=Uri.parse("content://sms/");
		Cursor cursor=resolver.query(uri, null, null, null, null);
		//输出集合内容
		AlertDialog.Builder dialog=new AlertDialog.Builder(MainActivity.this);
		dialog.setTitle("短信列表:");
		StringBuilder sb=new StringBuilder();
		int i=0;		
		while (cursor.moveToNext()) {
			String address=cursor.getString(cursor.getColumnIndex("address"));
			String body=cursor.getString(cursor.getColumnIndex("body"));
			String dateString=cursor.getString(cursor.getColumnIndex("date"));
			Long dateLong=Long.parseLong(dateString);
			SimpleDateFormat sdf=new SimpleDateFormat("yyy-MM-dd hh:mm:ss");
			Date date=new Date(dateLong);
			String dateShow=sdf.format(date);
			if(i!=0){
				sb.append("\n");
			}
			sb.append("号码:"+address+" 内容:"+body+" 时间:"+dateShow);			
			i++;
		}
		cursor.close();
		dialog.setMessage(sb);
		dialog.show();
	}

}