从BroadCastRecevier将数据传递到活动

从BroadCastRecevier将数据传递到活动

本文介绍了从BroadCastRecevier将数据传递到活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个短信阅读器应用程序,我展示senderno和邮件正文插入自定义列表视图。对于传入的消息我已经注册的广播接收器和填充ListView控件。

I have an SMS reader application and i am showing the senderno and message body into the Custom Listview. For the incoming messages i have registered a broadcast receiver and populating the listView.

每当一个新的消息在广播接收机我能够得到它的到来,但我想传递到活动这一数据。

Whenever a new message is coming in the broadcast Receiver i am able to get it but I want to this data to be passed onto the activity.

在code片段是:

MainActvity.java

public class MainSmsActivity extends Activity{
    private ListView smsList;
    SmsAdapter smsAdapter;
    private SmsDao smsDao;
    private List<SmsDao> smsDataList;

     @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sms_demo);
        smsDataList = new ArrayList<SmsDao>();
        Intent intent = new Intent();
        intent.setAction("com.mobile.sms.IncomingSms");
        sendBroadcast(intent);
        populateSms();
   }

public void populateSms(){
        Uri inboxURI = Uri.parse("content://sms/inbox");
        String[] reqCols = new String[] { "_id", "address", "body", "date" };
        ContentResolver cr = getContentResolver();
        Cursor cursor = cr.query(inboxURI, reqCols, null, null, null);
        smsDataList.clear();

        for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
            smsDao = new SmsDao();
            smsDao.setMessageBody(cursor.getString(1));
            smsDao.setSenderNo(cursor.getString(2));
            smsDao.setMessageTime(cursor.getLong(3));
            smsDataList.add(smsDao);
          }
        smsAdapter = new SmsAdapter(this,smsDataList);
        smsList.setAdapter(smsAdapter);
        smsAdapter.notifyDataSetChanged();
        cursor.close();
}
}

IncomingSms.Java

public class IncomingSms extends BroadcastReceiver {
    final SmsManager sms = SmsManager.getDefault();
    public void onReceive(Context context, Intent intent) {
        final Bundle bundle = intent.getExtras();
        try {
            if (bundle != null) {
                final Object[] pdusObj = (Object[]) bundle.get("pdus");
                for (int i = 0; i < pdusObj.length; i++) {
                    SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                    String phoneNumber = currentMessage.getDisplayOriginatingAddress();

                    String senderNum = phoneNumber;
                    String message = currentMessage.getDisplayMessageBody();
                    int duration = Toast.LENGTH_LONG;  // HERE I WANT TO SEND MESSAGE BODY TO THE MAIN ACTIVITY CLASS
                    Toast toast = Toast.makeText(context,
                            "senderNum: " + senderNum + ", message: " + message, duration);
                    toast.show();
                } // end for loop
            } // bundle is null
        } catch (Exception e) {
            Log.e("SmsReceiver", "Exception smsReceiver" + e);
        }
    }

我能够intially收到的所有邮件到列表视图,但我想要的ListView中应该得到自动只要新邮件到达更新。

I am able to receive all the messages intially into the list view but I want that the ListView should get automatically updated as soon as new message arrives.

推荐答案

在您broadcasereceiver做这样的事情:(使用意向)

In your broadcasereceiver do something like this: (use that intent)

public class SMSReceiver extends BroadcastReceiver {

public static final String NOTIFICATION = "receiver_sms";
@Override
public void onReceive(Context context, Intent intent) {

    Log.i("onReceive methode", "new SMS Comming");

    Bundle myBundle = intent.getExtras();

    SmsMessage[] messages = null;
    String strMessage = "", address = "";
    abortBroadcast();
    if (myBundle != null) {
        // get message in pdus format(protocol description unit)
        Object[] pdus = (Object[]) myBundle.get("pdus");
        // create an array of messages
        messages = new SmsMessage[pdus.length];
        Log.i("onReceive methode", "new SMS Comming");
        for (int i = 0; i < messages.length; i++) {
            // Create an SmsMessage from a raw PDU.
            messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
            // get the originating address (sender) of this SMS message in
            // String form or null if unavailable
            address = messages[i].getOriginatingAddress();

            // get the message body as a String, if it exists and is text
            // based.
            strMessage += messages[i].getMessageBody();
            strMessage += "\n";
        }

        // show message in a Toast
    }
        // this is what you need
        Intent broadcast = new Intent(NOTIFICATION);
        broadcast.putExtra("data", strMessage);
        LocalBroadcastManager.getInstance(context).sendBroadcast(broadcast);

}

然后注册UR接收器乌尔活动

and then register ur receiver in ur activity

public BroadcastReceiver receiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.e(tag, "SMS Received.");
        // Intent i = getIntent();
        Bundle b = intent.getBundleExtra("SMS");
        // String bun = b.getString("MyData");
        Log.i(tag, "Bundle:  " + b);
        String str = intent.getStringExtra("data");

        parseSMSData(str);
    }
};

然后在onResume():

and then in onResume():

@Override
protected void onResume() {
    super.onResume();
    LocalBroadcastManager.getInstance(this).registerReceiver(receiver,
            new IntentFilter(SMSReceiver.NOTIFICATION));
}

和中的onDestroy(),您必须取消注册接收这样的:

and in onDestroy() you must unregister that receiver like this:

@Override
protected void onDestroy() {
    // Unregister since the activity is about to be closed.
    LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
    super.onDestroy();
}

,也不要忘了在应用程序标记添加这个在乌拉圭回合清单文件:

and also don't forget to add this in ur manifest file in application tag:

 <receiver android:name=".SMSBroadcastReceiver">
        <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED"></action>
        </intent-filter>
    </receiver>

这篇关于从BroadCastRecevier将数据传递到活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 18:45