Passing Data from Broadcast Receiver to another Activity

后端 未结 2 452
囚心锁ツ
囚心锁ツ 2020-11-30 08:16

Hi I\'ve been having an issue with Broadcast Receivers and passing information to another activity. I\'m trying to create an application that will capture incoming SMS messa

相关标签:
2条回答
  • 2020-11-30 08:44
    1. Instantiate a BroadcastReceiver in the activity you want to get your data to, for example:

      private BroadcastReceiver mServiceReceiver = new BroadcastReceiver(){
          @Override
          public void onReceive(Context context, Intent intent)
          {
              //Extract your data - better to use constants...
              String IncomingSms=intent.getStringExtra("incomingSms");//
              String phoneNumber=intent.getStringExtra("incomingPhoneNumber");
      
          }
      };
      
    2. Unregister your receiver on onPause():

      @Override
      protected void onPause() {
          super.onPause();
          try {
              if(mServiceReceiver != null){
              unregisterReceiver(mServiceReceiver);
              }
          } catch (Exception e) {
             e.printStackTrace();
          }
      }
      
    3. Register it on onResume():

      protected void onResume() {
          super.onResume();
          IntentFilter filter = new IntentFilter();
          filter.addAction("android.intent.action.SmsReceiver");
          registerReceiver(mServiceReceiver , filter);
      }
      
    4. Broadcast your data from the service via an Intent, for Example:

      Intent i = new Intent("android.intent.action.SmsReceiver").putExtra("incomingSms", message);
      i.putExtra("incomingPhoneNumber", phoneNumber);
      context.sendBroadcast(i);
      

    and that's it! goodLuck!

    0 讨论(0)
  • 2020-11-30 08:49

    If you have your activity named ReceiveText, then in your BroadcastReceiver, you should do the following:

    Intent i = new Intent(context, ReceiveText.class);
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    i.putExtra("message", message.getMessageBody());
    context.startActivity(i);
    

    Then, in your activity, you will need to getExtra as so:

    Intent intent = getIntent();
    String message = intent.getStringExtra("message");
    

    And then you will use message as you need.

    If you simply want the ReceiveText activity to show the message as a dialog, declare <activity android:theme="@android:style/Theme.Dialog" /> in your manifest for ReceiveText and then set the message to a textview in the activity.

    Let me know if I need to add anything else.

    0 讨论(0)
提交回复
热议问题