How can I read SMS messages from the device programmatically in Android?

后端 未结 11 2506
情深已故
情深已故 2020-11-22 02:48

I want to retrieve the SMS messages from the device and display them?

11条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 03:10

    There are lots of answers are already available but i think all of them are missing an important part of this question. Before reading data from an internal database or its table we have to understand how data is stored in it and then we can find the solution of the above question that is :

    How can I read SMS messages from the device programmatically in Android?

    So,In android SMS table is like look like this

    Know,we can select whatever we want from the database.In our case we have only required

    id,address and body

    In case of reading SMS:

    1.Ask for permissions

    int REQUEST_PHONE_CALL = 1;
    
       if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_SMS}, REQUEST_PHONE_CALL);
            }
    

    or

     
    

    2.Now your code goes like this

    // Create Inbox box URI
    Uri inboxURI = Uri.parse("content://sms/inbox");
    
    // List required columns
    String[] reqCols = new String[]{"_id", "address", "body"};
    
    // Get Content Resolver object, which will deal with Content Provider
    ContentResolver cr = getContentResolver();
    
    // Fetch Inbox SMS Message from Built-in Content Provider
    Cursor c = cr.query(inboxURI, reqCols, null, null, null);
    
    // Attached Cursor with adapter and display in listview
    adapter = new SimpleCursorAdapter(this, R.layout.a1_row, c,
            new String[]{"body", "address"}, new int[]{
            R.id.A1_txt_Msg, R.id.A1_txt_Number});
    lst.setAdapter(adapter);
    

    I hope this one will be helpful. Thanks.

提交回复
热议问题