如何在Android中以编程方式从设备读取SMS消息?

我想从设备中检索SMS消息并显示它们?

使用内容parsing器( “content:// sms / inbox” )来阅读收件箱中的短信。

// public static final String INBOX = "content://sms/inbox"; // public static final String SENT = "content://sms/sent"; // public static final String DRAFT = "content://sms/draft"; Cursor cursor = getContentResolver().query(Uri.parse("content://sms/inbox"), null, null, null, null); if (cursor.moveToFirst()) { // must check the result to prevent exception do { String msgData = ""; for(int idx=0;idx<cursor.getColumnCount();idx++) { msgData += " " + cursor.getColumnName(idx) + ":" + cursor.getString(idx); } // use msgData } while (cursor.moveToNext()); } else { // empty box, no SMS } 

请添加READ_SMS权限。

我希望它有助于:)

这是一个微不足道的过程。 您可以在源代码SMSPopup中看到一个很好的例子

检查以下方法:

 SmsMmsMessage getSmsDetails(Context context, long ignoreThreadId, boolean unreadOnly) long findMessageId(Context context, long threadId, long _timestamp, int messageType void setMessageRead(Context context, long messageId, int messageType) void deleteMessage(Context context, long messageId, long threadId, int messageType) 

这是阅读的方法:

 SmsMmsMessage getSmsDetails(Context context, long ignoreThreadId, boolean unreadOnly) { String SMS_READ_COLUMN = "read"; String WHERE_CONDITION = unreadOnly ? SMS_READ_COLUMN + " = 0" : null; String SORT_ORDER = "date DESC"; int count = 0; // Log.v(WHERE_CONDITION); if (ignoreThreadId > 0) { // Log.v("Ignoring sms threadId = " + ignoreThreadId); WHERE_CONDITION += " AND thread_id != " + ignoreThreadId; } Cursor cursor = context.getContentResolver().query( SMS_INBOX_CONTENT_URI, new String[] { "_id", "thread_id", "address", "person", "date", "body" }, WHERE_CONDITION, null, SORT_ORDER); if (cursor != null) { try { count = cursor.getCount(); if (count > 0) { cursor.moveToFirst(); // String[] columns = cursor.getColumnNames(); // for (int i=0; i<columns.length; i++) { // Log.v("columns " + i + ": " + columns[i] + ": " + cursor.getString(i)); // } long messageId = cursor.getLong(0); long threadId = cursor.getLong(1); String address = cursor.getString(2); long contactId = cursor.getLong(3); String contactId_string = String.valueOf(contactId); long timestamp = cursor.getLong(4); String body = cursor.getString(5); if (!unreadOnly) { count = 0; } SmsMmsMessage smsMessage = new SmsMmsMessage(context, address, contactId_string, body, timestamp, threadId, count, messageId, SmsMmsMessage.MESSAGE_TYPE_SMS); return smsMessage; } } finally { cursor.close(); } } return null; } 
 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { final String myPackageName = getPackageName(); if (!Telephony.Sms.getDefaultSmsPackage(this).equals(myPackageName)) { Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT); intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, myPackageName); startActivityForResult(intent, 1); }else { List<Sms> lst = getAllSms(); } }else { List<Sms> lst = getAllSms(); } 

将应用设置为默认的短信应用

  @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 1) { if (resultCode == RESULT_OK) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { final String myPackageName = getPackageName(); if (Telephony.Sms.getDefaultSmsPackage(mActivity).equals(myPackageName)) { List<Sms> lst = getAllSms(); } } } } } 

function获取短信

 public List<Sms> getAllSms() { List<Sms> lstSms = new ArrayList<Sms>(); Sms objSms = new Sms(); Uri message = Uri.parse("content://sms/"); ContentResolver cr = mActivity.getContentResolver(); Cursor c = cr.query(message, null, null, null, null); mActivity.startManagingCursor(c); int totalSMS = c.getCount(); if (c.moveToFirst()) { for (int i = 0; i < totalSMS; i++) { objSms = new Sms(); objSms.setId(c.getString(c.getColumnIndexOrThrow("_id"))); objSms.setAddress(c.getString(c .getColumnIndexOrThrow("address"))); objSms.setMsg(c.getString(c.getColumnIndexOrThrow("body"))); objSms.setReadState(c.getString(c.getColumnIndex("read"))); objSms.setTime(c.getString(c.getColumnIndexOrThrow("date"))); if (c.getString(c.getColumnIndexOrThrow("type")).contains("1")) { objSms.setFolderName("inbox"); } else { objSms.setFolderName("sent"); } lstSms.add(objSms); c.moveToNext(); } } // else { // throw new RuntimeException("You have no SMS"); // } c.close(); return lstSms; } 

短信类如下:

 public class Sms{ private String _id; private String _address; private String _msg; private String _readState; //"0" for have not read sms and "1" for have read sms private String _time; private String _folderName; public String getId(){ return _id; } public String getAddress(){ return _address; } public String getMsg(){ return _msg; } public String getReadState(){ return _readState; } public String getTime(){ return _time; } public String getFolderName(){ return _folderName; } public void setId(String id){ _id = id; } public void setAddress(String address){ _address = address; } public void setMsg(String msg){ _msg = msg; } public void setReadState(String readState){ _readState = readState; } public void setTime(String time){ _time = time; } public void setFolderName(String folderName){ _folderName = folderName; } } 

不要忘记在您的AndroidManifest.xml中定义权限

 <uses-permission android:name="android.permission.READ_SMS" /> 

这篇文章有点旧了,但这里是另一个简单的解决scheme,用于在Android中获取与SMS内容提供者相关的数据:

使用这个lib: https : //github.com/EverythingMe/easy-content-providers

  • 获取所有SMS

     TelephonyProvider telephonyProvider = new TelephonyProvider(context); List<Sms> smses = telephonyProvider.getSms(Filter.ALL).getList(); 

    每个短信都有所有的领域,所以你可以得到你需要的任何信息:
    地址,正文,receivedDate,types(INBOX,SENT,DRAFT,..),threadId,…

  • 凝胶所有MMS

     List<Mms> mmses = telephonyProvider.getMms(Filter.ALL).getList(); 
  • 凝胶全部Thread

     List<Thread> threads = telephonyProvider.getThreads().getList(); 
  • 凝胶所有Conversation

     List<Conversation> conversations = telephonyProvider.getConversations().getList(); 

它适用于ListCursor并有一个示例应用程序,看看它的外观和工作。

实际上,对所有Android内容提供商都有支持,例如: 联系人,通话logging,日历,…所有选项的完整文档: https : //github.com/EverythingMe/easy-content-providers/wiki/Android-供应商

希望它也帮助:)

从API 19开始,您可以使用Telephony Class; 由于硬核值不会检索每个设备中的消息,因为内容提供者Uri从设备和制造商变化。

 public void getAllSms(Context context) { ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(Telephony.Sms.CONTENT_URI, null, null, null, null); int totalSMS = 0; if (c != null) { totalSMS = c.getCount(); if (c.moveToFirst()) { for (int j = 0; j < totalSMS; j++) { String smsDate = c.getString(c.getColumnIndexOrThrow(Telephony.Sms.DATE)); String number = c.getString(c.getColumnIndexOrThrow(Telephony.Sms.ADDRESS)); String body = c.getString(c.getColumnIndexOrThrow(Telephony.Sms.BODY)); Date dateFormat= new Date(Long.valueOf(smsDate)); String type; switch (Integer.parseInt(c.getString(c.getColumnIndexOrThrow(Telephony.Sms.TYPE)))) { case Telephony.Sms.MESSAGE_TYPE_INBOX: type = "inbox"; break; case Telephony.Sms.MESSAGE_TYPE_SENT: type = "sent"; break; case Telephony.Sms.MESSAGE_TYPE_OUTBOX: type = "outbox"; break; default: break; } c.moveToNext(); } } } else { Toast.makeText(this, "No message to show!", Toast.LENGTH_SHORT).show(); } } 

步骤1:首先,我们必须在清单文件中添加权限,如<uses-permission android:name="android.permission.RECEIVE_SMS"android:protectionLevel="signature" /> <uses-permission android:name="android.permission.READ_SMS" />

第2步:然后添加服务短信接收器类接收短信

  <receiver android:name="com.aquadeals.seller.services.SmsReceiver"> <intent-filter> <action android:name="android.provider.Telephony.SMS_RECEIVED"/> </intent-filter> </receiver> 

第3步:添加运行时权限

  private boolean checkAndRequestPermissions() { int sms = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS); int loc = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION); int loc2 = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION); List<String> listPermissionsNeeded = new ArrayList<>(); if (sms != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(Manifest.permission.READ_SMS); } if (loc != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(android.Manifest.permission.ACCESS_FINE_LOCATION); } if (loc2 != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(Manifest.permission.ACCESS_COARSE_LOCATION); } if (!listPermissionsNeeded.isEmpty()) { ActivityCompat.requestPermissions(this,listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),REQUEST_ID_MULTIPLE_PERMISSIONS); return false; } return true; } 

第4步:在您的应用程序中添加此类并testingInterface类

 public interface SmsListener{ public void messageReceived(String messageText);} 

SmsReceiver.java

  public class SmsReceiver extends BroadcastReceiver { private static SmsListener mListener; public Pattern p = Pattern.compile("(|^)\\d{6}"); @Override public void onReceive(Context context, Intent intent) { Bundle data = intent.getExtras(); Object[] pdus = (Object[]) data.get("pdus"); for(int i=0;i<pdus.length;i++) { SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdus[i]); String sender = smsMessage.getDisplayOriginatingAddress(); String phoneNumber = smsMessage.getDisplayOriginatingAddress(); String senderNum = phoneNumber ; String messageBody = smsMessage.getMessageBody(); try { if(messageBody!=null){ Matcher m = p.matcher(messageBody); if(m.find()) { mListener.messageReceived(m.group(0)); } else {}} } catch(Exception e){} } } public static void bindListener(SmsListener listener) { mListener = listener; }} 

快乐的编码

 String WHERE_CONDITION = unreadOnly ? SMS_READ_COLUMN + " = 0" : null; 

改为:

 String WHERE_CONDITION = unreadOnly ? SMS_READ_COLUMN + " = 0 " : SMS_READ_COLUMN + " = 1 "; 
    Interesting Posts