Select the first SMS message to enter the Android database

I desperately want to find a solution, so I will ask for help! I am a new French programmer. My goal is to create a widget that can display SMS. My problem is that I don’t know how to create a cursor that selects the first SMS message in the content: // sms / inbox Sorry my bad English, I hope you can understand my point. Thanks for your reply. this is my code:

package sfeir.monwidget;
import android.R.string;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.net.Uri;
import android.widget.RemoteViews;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.widget.ArrayAdapter;   


public class MonWidget extends AppWidgetProvider {

 public void onUpdate(Context context, AppWidgetManager appWidgetManager,
            int[] appWidgetIds) {
     Uri uri = Uri.parse("content://sms/inbox");
    // returns all the results.
    Cursor c= getContentResolver().query(uri, null, null ,null,null); 
    // called by the Activity.
    startManagingCursor(c);
    String body = null;
    String number = null;

    if(c.moveToFirst()) { // move cursor to first row
       // retrieves the body and number of the SMS
       body = c.getString(c.getColumnIndexOrThrow("body")).toString();
       number = c.getString(c.getColumnIndexOrThrow("address")).toString();
    }

    // when your done, close the cursor.
    c.close(); 
 RemoteViews updateViews = new RemoteViews(context.getPackageName(),
         R.layout.widget_layout);


 updateViews.setTextColor(R.id.text, 0xFF000000);
 updateViews.setTextViewText(R.id.text, (CharSequence) body);

 ComponentName thisWidget = new ComponentName(context, MonWidget.class);
 appWidgetManager.updateAppWidget(thisWidget, updateViews);
 }

}

+3
source share
2 answers

You will need to set certain permissions (see the link below), but here is a sample code to use Cursorto retrieve the first SMS message.

Uri uri = Uri.parse("content://sms/inbox");
// returns all the results from the given Context
Cursor c = context.getContentResolver().query(uri, null, null ,null,null); 

String body = null;
String number = null;

if(c.moveToFirst()) { // move cursor to first row
   // retrieves the body and number of the SMS
   body = c.getString(c.getColumnIndexOrThrow("body")).toString();
   number = c.getString(c.getColumnIndexOrThrow("address")).toString();
}

// when your done, close the cursor.
c.close(); 

FrontPage/Tutorials/SMS Messaging - Wiki Mobdev, SMS Android.

EDIT:

, Activity. . , , .

, onUpdate Context, Activity, Context getContentResolver (. )

startManagingCursor , , Activity Cursor .

, - .

2:

AndroidManifest.xml , - , .

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

- SMS_RECEIVED . .

0

Source: https://habr.com/ru/post/1731895/


All Articles