android 读取手机所有短信息

xiaoxiao2021-02-28  34

import android.app.Activity; import android.content.AsyncQueryHandler; import android.content.ContentResolver; import android.database.Cursor; import android.net.Uri; import com.feilu.flashloan.callback.OnSmsInboxListener; import com.feilu.flashloan.ui.usercenter.bean.SmsInboxBean; import com.google.gson.Gson; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * Created by fengpeihao on 2017/8/15. * 读取手机短信工具类 */ public class SmsInboxUtils { private static SmsInboxUtils mContactUtils; private OnSmsInboxListener mListener; public static SmsInboxUtils with() { if (mContactUtils == null) { synchronized (ContactUtils.class) { mContactUtils = new SmsInboxUtils(); } } return mContactUtils; } public void getSms(Activity activity, OnSmsInboxListener listener) { mListener = listener; MyAsyncQueryhandler asyncQueryhandler = new MyAsyncQueryhandler(activity.getContentResolver()); /** * content://sms/           所有短信 * content://sms/inbox        收件箱 * content://sms/sent        已发送 * content://sms/draft        草稿 * content://sms/outbox        发件箱 * content://sms/failed        发送失败 * content://sms/queued        待发送列表 */ Uri uri = Uri.parse("content://sms/"); String[] projection = new String[]{"address", "person", "body", "date", "type"};//"_id", "address", "person","date", "type"1是接收到的,2是已发出 asyncQueryhandler.startQuery(0, null, uri, projection, null, null, "date desc"); } private String getDate(String date) { Date callDate = new Date(Long.parseLong(date)); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return sdf.format(callDate); } private class MyAsyncQueryhandler extends AsyncQueryHandler { public MyAsyncQueryhandler(ContentResolver cr) { super(cr); } @Override protected void onQueryComplete(int token, Object cookie, Cursor cursor) { if (cursor != null && cursor.getCount() > 0) { List<SmsInboxBean> list = new ArrayList<>(); while (cursor.moveToNext()) { String number = cursor.getString(cursor.getColumnIndex("address"));//手机号 String name = cursor.getString(cursor.getColumnIndex("person"));//联系人姓名列表 String body = cursor.getString(cursor.getColumnIndex("body"));//内容 String date = getDate(cursor.getString(cursor.getColumnIndex("date")));//时间 String type = cursor.getString(cursor.getColumnIndex("type"));//1是接收到的,2是已发出 SmsInboxBean smsInboxBean = new SmsInboxBean(date, name, number, body, type); list.add(smsInboxBean); } Gson gson = new Gson(); mListener.onSuccess(gson.toJson(list)); } else { if (mListener != null) mListener.onFailed(); } super.onQueryComplete(token, cookie, cursor); } } } public interface OnSmsInboxListener { void onSuccess(String json); void onFailed(); }注:需要权限 <uses-permission android:name="android.permission.READ_SMS"/>6.0以上需要动态请求权限
转载请注明原文地址: https://www.6miu.com/read-45942.html

最新回复(0)