在Android数据库收件箱中选择第一个SMS

Oli*_*ier 3 sms android

我迫切希望找到解决方案,所以我请求帮助!我是一名新的法国程序员.我的目标是创建一个能够显示SMS的小部件.我的问题是,我不知道如何创建一个光标,在内容中选择第一条短信://短信/收件箱请原谅我的英文不好,希望你能理解我的意思.谢谢您的回答.这是我的代码:

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);
 }
Run Code Online (Sandbox Code Playgroud)

}

Ant*_*ney 6

您需要设置特定权限(请参阅下面的链接),但这里是使用a Cursor检索第一条SMS消息的代码示例.

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(); 
Run Code Online (Sandbox Code Playgroud)

我建议查看FrontPage/Tutorials/SMS Messaging - Mobdev Wiki,它为处理Android上的SMS处理提供了很好的介绍.

编辑:

这些方法对您的应用程序不可见,因为它没有扩展到Activity超类.默认情况下,在开发应用程序时,它会从该关系继承方法.但是你本身并没有创建一个应用程序,而是在开发一个小部件.

幸运的是,在onUpdate方法中它们传递的是当前Context的超类,Activity因此我们可以使用变量context来调用getContentResolver(参见上面的代码)

我也startManagingCursor从代码中删除了方法,它不是完全必要的,它允许Activity Cursor根据Activity的生命周期处理给定的生命周期.

如果有任何问题,请告诉我.

编辑2:

在您的AndroidManifest.xml文件中,您需要设置正确的权限以避免任何异常,添加此行.

<uses-permission android:name="android.permission.READ_SMS"></uses-permission>
Run Code Online (Sandbox Code Playgroud)