Skip to content Skip to sidebar Skip to footer

Update Textview In Broadcast Receivers

I want to update my text view on the receivers side as soon as I receive the message. I have the following code which creates the instance of main activity and uses it in the Broad

Solution 1:

What if you try like below:

publicclassMainactivityextendsactivity{

    protectedvoidonCreate(Bundle savedInstanceState) {
        setContentView(R.layout.your_layout);
        //register your receiver
    }

    protectedvoidonDestroy() {

        //unregister your receiversuper.onDestroy();
    }
    publicvoidupdateUI(final String s)
    {
        MainActivity.this.runOnUiThread(newRunnable() {
            @Overridepublicvoidrun() {
                TextView  textView=(TextView) findViewById(R.id.textView);
                textView.setText(s);
            }
       });
    }

    privateclasssmsreceiverextendsBroadcastReceiver
    {
        try{

             updateUI(str)

        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
}

Solution 2:

this is my code base you code it can work

public class MainActivity extends Activity {

privatestaticMainActivity ins;

privateButton mButton;

publicstaticMainActivitygetInst()
{
    return ins;
}

@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ins = this;

    mButton = (Button) findViewById(R.id.but_send);

    mButton.setOnClickListener(newOnClickListener() {

        @OverridepublicvoidonClick(View v) {
            Intent inten = newIntent(MainActivity.this, SmsReceiver.class);
            inten.setAction("com.example.demo.action.info");
            sendBroadcast(inten);
        }
    });
}

publicvoidupdateUI(final String s)
{
    MainActivity.this.runOnUiThread(newRunnable() {
     @Overridepublicvoidrun() {
         TextView  textView=(TextView) findViewById(R.id.tv_info);
         textView.setText(s);
     }
 });
}

}

public class SmsReceiver extends BroadcastReceiver {

@OverridepublicvoidonReceive(Context context, Intent intent) {
    try {
        if (MainActivity.getInst() != null)
            MainActivity.getInst().updateUI("Hello World");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

<receiverandroid:name="com.example.demoexample.SmsReceiver" ><intent-filter><actionandroid:name="com.example.demo.action.info" /></intent-filter></receiver>

Post a Comment for "Update Textview In Broadcast Receivers"