How to pass data to BroadcastReceiver?

后端 未结 5 980
难免孤独
难免孤独 2020-12-08 21:43

What I am trying to do is that the numbers to which my application sends messages to, are passed to the BraodcastReceiver...but so far either I am getting null or BroadcastR

相关标签:
5条回答
  • 2020-12-08 21:58

    You starting an Activity instead of broadcasting Intent. Try to change

    startActivity(intent);
    

    to

    sendBroadcast(intent);
    

    UPDATE:

    You set no action and no component name to the Intent. Try create intent as following:

    Intent intent = new Intent(context, YourReceiver.class);
    intent.putExtra("phN", phoneNo);
    sendBroadcast(intent);
    
    0 讨论(0)
  • 2020-12-08 22:02

    You would send a broadcast like so:

    Intent intent = new Intent(action);
    intent.putExtra("phN", phoneNo);
    sendBroadcast(intent);
    

    The action parameter is a String that correlates to the action you registered the BroadcastReceiver with. So if you registered your receiver like so:

    MyBroadcastReceiver receiver = new MyBroadcastReceiver();
    registerReceiver( receiver, new IntentFilter( "com.myapp.myaction" ) );
    

    then action would be "com.myapp.myaction"

    0 讨论(0)
  • 2020-12-08 22:04

    use sendbroadcast instead of startactivity.it will work..!!

    0 讨论(0)
  • 2020-12-08 22:06

    Following @Jason 's example...I did this...

    In MainActivity or any activity from where you want to send intent from

    Intent intent = new Intent("my.action.string");
    intent.putExtra("extra", phoneNo); \\ phoneNo is the sent Number
    sendBroadcast(intent);
    

    and then in my SmsReceiver Class I did this

    public void onReceive(Context context, Intent intent) {
      String action = intent.getAction();
    
      Log.i("Receiver", "Broadcast received: " + action);
    
      if(action.equals("my.action.string")){
         String state = intent.getExtras().getString("extra");
    
      }
    }
    

    And in manifest.xml I added "my.action.string" though it was an option..

    <receiver android:name=".SmsReceiver" android:enabled="true">
        <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            <action android:name="my.action.string" />
            <!-- and some more actions if you want -->
        </intent-filter>
    </receiver>
    

    worked like charm!!

    0 讨论(0)
  • 2020-12-08 22:16

    Your problem is actually very simple. It's enough that change onReceive() code just like it :

    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
    
        Log.i("Receiver", "Broadcast received: " + action);
    
       if(action.equals("my.action.string")){
           String state = bundle.getString("phN");
    
       }
    }
    
    0 讨论(0)
提交回复
热议问题