Android BroadcastReceiver onReceive Update TextView in MainActivity

后端 未结 5 1918
说谎
说谎 2020-12-01 04:04

In MainActivity I have a TextView: textV1. I also have a method in MainActivity that updates that textview:

public void updateTheTextView(final String t) {
         


        
5条回答
  •  北海茫月
    2020-12-01 04:33

    create an instance of the class and then pass the value to the function that changes TextView value follow these steps please : in your BroadcastReceiver overRide onReceive method and paste These lines or changes theme as you wish

    private Handler handler = new Handler(); // Handler used to execute code on the UI thread
    // Post the UI updating code to our Handler
    handler.post(new Runnable() {
        @Override
        public void run() {
        //Toast.makeText(context, "Toast from broadcast receiver", Toast.LENGTH_SHORT).show();
        YourActivityToUpdate.updateTheTextView(message);
        YourActivityToUpdateinst = YourActivityToUpdate.instance();
            if(inst != null)  { // your activity can be seen, and you can update it's context
            inst.updateTheTextView(message);
            }
        }
    });
    

    now we explain the updateTheTextView and inst in YourActivityToUpdate class Paste these Lines please

    private static SignUpVerify mInst;
    
    public static SignUpVerify instance() {
            return mInst;
    }
    @Override
    public void onStart() {
        super.onStart();
        mInst = this;
    }
    
    @Override
    public void onStop() {
        super.onStop();
        mInst = null;
    }
    

    and this is the updateTheTextView method that should be placed in YourActivityToUpdate class

    public void updateTheTextView(final String verifyCodeValue) {
                    Log.i("verifyCodeValue", verifyCodeValue);
                    YourTextViewToUpdate.setText(verifyCodeValue);
        }
    

    i think this is a better way thanks to "kevin-lynx"

提交回复
热议问题