我很想找到解决方案,所以我寻求帮助! 我是一名新的法国程序员。我的目标是创建一个能够显示 SMS 的小部件。 我的问题是我不知道如何创建一个光标来选择 content://sms/inbox 中的第一条短信 请原谅我的英语不好,我希望你能理解我的意思。 谢谢您的回答。 这是我的代码:
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);
}
最佳答案
您需要设置特定权限(阅读下面的链接),但这里是使用 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();
我建议查看 FrontPage/Tutorials/SMS Messaging - Mobdev Wiki它很好地介绍了如何在 Android 上处理 SMS。
编辑:
那些方法对您的应用程序不可见,因为它没有扩展到 Activity
父类(super class)。默认情况下,当您开发应用程序 时,它会从该关系继承方法。但您并不是在创建应用程序,而是在开发小部件。
幸运的是,在 onUpdate
方法中,它们传入了当前 Context
,它是 Activity
的父类(super class),因此我们可以使用变量 context
以调用 getContentResolver
(请参阅上面的代码)
我还删除了 startManagingCursor
代码中的方法,它不是完全必需的,它允许 Activity 根据 Activity 的生命周期处理给定的 Cursor
的生命周期。
如果有任何问题,请告诉我。
编辑 2:
在您的 AndroidManifest.xml
文件中,您需要设置正确的权限以避免任何异常,添加此行。
<uses-permission android:name="android.permission.READ_SMS"></uses-permission>
关于android - 在 Android 数据库收件箱中选择第一条短信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2223296/