将数据从BroadCastRecevier传递到活动

时间:2014-12-16 11:03:11

标签: java android

我有一个短信阅读器应用程序,我将senderno和消息正文显示在自定义列表视图中。对于收到的消息,我已经注册了广播接收器并填充了listView。

每当广播Receiver中出现新消息时,我都可以获取它,但我希望将这些数据传递给活动。

代码段是:

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);
        }
    }

我能够在列表视图中接收所有消息,但我希望ListView在新消息到达后立即自动更新。

3 个答案:

答案 0 :(得分:1)

OnResume()注册您的服务,然后您就可以在班级内轻松访问

@Override
public void onResume()
{
    super.onResume();
    this.registerReceiver(this.yourservice, new IntentFilter("your service type"));
}

并取消注册onpause()

中的服务
@Override
public void onPause() {
    super.onPause();
    try
    {
        this.unregisterReceiver(this.your service);
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
}

在您的活动中添加您的广播接收器,

private WakefulBroadcastReceiver IncomingSms = new WakefulBroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        //use your receiver content
     }

答案 1 :(得分:1)

在你的broadcasereceiver中做这样的事情:(使用那个意图)

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);

}

然后在你的活动中注册你的接收者

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():

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

并且在onDestroy()中你必须注销这个接收器:

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

并且也不要忘记在应用标记中的清单文件中添加它:

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

答案 2 :(得分:0)

将以下课程放在MainSmsActivity中,以便您能够处理列表。

private class IncomingSms extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
       if (intent.getAction().equals("incomingSms")) {
       //your impl here
       }
    }
 }

并在onCreate()活动的MainSmsActivity中,放置以下代码

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
...
    IncomingSms broadcastReceiver = new IncomingSms(); // declare it outside so that it should be accessible in onDestroy()
    IntentFilter intentFilter = new IntentFilter("incomingSms");
    registerReceiver(broadcastReceiver , intentFilter);
}

并在onDestroy()中放置以下代码

@Override
protected void onDestroy() {
   if (broadcastReceiver != null) {
      unregisterReceiver(broadcastReceiver);
    }
   super.onDestroy();
}