Sending Intent from BroadcastReceiver class to currently running activity

后端 未结 2 1382
名媛妹妹
名媛妹妹 2021-02-15 12:26

I have a class which extends BroadcastReceiver. On receiving a SMS, I would like to pass information to my main activity class to display the text in a box (Append,

2条回答
  •  醉话见心
    2021-02-15 12:46

    Modify your code as below.

     public class SmsReceiver extends BroadcastReceiver {
    @Override 
    
    public void onReceive(Context context, Intent intent)
        { 
            Intent i = new Intent(context, MainActivity.class);
                i.putExtra("updatedString","Hello");            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_SINGLE_TOP);
                context.startActivity(i);
        } 
    }
    
    public class MainActivity extends Activity{
    
      private TextView results;
      @Override 
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            Bundle extras = getIntent().getExtras();
            if(extras!=null){
                results = (TextView) findViewById(R.id.results);
                results.setVisibility(View.VISIBLE);
                results.append(extras.getString("updatedString"));
            } 
    
    @Override
        protected void onNewIntent(Intent intent) {
            super.onNewIntent(intent);
          //handle your intent here.Note this will be called even when activity first created.so becareful to handle intents correctly.
        }
    
    }
    

提交回复
热议问题