Android BroadcastReceiver within Activity

后端 未结 7 1433
后悔当初
后悔当初 2020-11-28 23:59

I\'m just trying this little sample project, all it does: Activity one has a Button that sends a Broadcast. Activity two displays a toast when received. Below is the code, t

相关标签:
7条回答
  • 2020-11-29 00:31

    Extends the ToastDisplay class with BroadcastReceiver and register the receiver in the manifest file,and dont register your broadcast receiver in onResume() .

    <application
      ....
      <receiver android:name=".ToastDisplay">
        <intent-filter>
          <action android:name="com.unitedcoders.android.broadcasttest.SHOWTOAST"/>
        </intent-filter>
      </receiver>
    </application>
    

    if you want to register in activity then register in the onCreate() method e.g:

    onCreate(){
    
        sentSmsBroadcastCome = new BroadcastReceiver() {
    
            @Override
            public void onReceive(Context context, Intent intent) {
                Toast.makeText(context, "SMS SENT!!", Toast.LENGTH_SHORT).show();
            }
        };
        IntentFilter filterSend = new IntentFilter();
        filterSend.addAction("m.sent");
        registerReceiver(sentSmsBroadcastCome, filterSend);
    }
    
    0 讨论(0)
提交回复
热议问题