簡體   English   中英

BroadCastReceiver捕獲SMS_RECEIVED操作時在android中讀取SMS

[英]Reading SMS in android when SMS_RECEIVED action is captured by a BroadCastReceiver

我正在嘗試將收到的SMS的正文設置為EditText。 我正在使用BroadcastReceiver捕獲動作SMS_RECEIVED,並使用registerReceiver()方法對其進行注冊

問題是當我收到短信時,什么也沒有發生,並且EditText沒有更新。

我嘗試調試的內容

我嘗試僅在onCreate()方法中設置不帶有BroadcastReceiver的EditText,並使用特定編號已接收的msg文本對其進行更新。

public class CardActivity extends Activity {

EditText txtCardId;
final String SMS_URI_INBOX = "content://sms/inbox";
IntentFilter filter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.card);
    btnProceed = (Button) findViewById(R.id.btnProceed);
    txtCardId = (EditText) findViewById(R.id.txtCardId);
    filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
    registerReceiver(mBroadcastReceiver,filter);

    });
}

private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver(){
    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            context = getApplicationContext();
            Uri uri = Uri.parse(SMS_URI_INBOX);
            String[] projection = new String[] { "_id", "address", "person", "body", "date", "type" };
            Cursor cur = getContentResolver().query(uri, projection, "address='+919016832405'", null, "date desc");
            if (cur.moveToFirst()) {
                int index_Body = cur.getColumnIndex("body");
                String strbody;
                do {
                    strbody = cur.getString(index_Body);
                } while (cur.moveToNext());
                txtCardId.setText(strbody);

                if (!cur.isClosed()) {
                    cur.close();
                    cur = null;
                }
            } else {
                txtCardId.setText("nothing");
            } // end if
        }
        catch (SQLiteException ex) {
            Log.d("SQLiteException", ex.getMessage());
        }
    }};
}

我發現我誤會了

我在清單中使用了READ_SMS權限,而我需要使用RECEIVE_SMS。 有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM