How do I create an android Intent that carries data?

前端 未结 3 813
梦谈多话
梦谈多话 2020-12-02 01:45

I might have misunderstood how intents are supposed to be used, so I might be asking the wrong thing here. If that\'s the case, please help me get on the right track with th

相关标签:
3条回答
  • 2020-12-02 02:03

    Use the Intent bundle to add extra information, like so:

    Intent i = new Intent(MessageService.this, ViewMessageActivity.class);
    i.putExtra("name", "value");
    

    And on the receiving side:

    String extra = i.getStringExtra("name");
    

    Or, to get all the extras as a bundle, independently of the type:

    Bundle b = i.getExtras();
    

    There are various signatures for the putExtra() method and various methods to get the data depending on its type. You can see more here: Intent, putExtra.

    EDIT: To pass on an object it must implement Parcelable or Serializable, so you can use one of the following signatures:

    putExtra(String name, Serializable value)

    putExtra(String name, Parcelable value)

    0 讨论(0)
  • 2020-12-02 02:10

    You can do the following to add information into the intent bundle:

        Intent i = new Intent(MessageService.this, ViewMessageActivity.class);
        i.putExtra("message", "value");
        startActivity(i);
    

    Then in the activity you can retrieve like this:

        Bundle extras = getIntent().getExtras();
        String message = extras.getString("message");
    
    0 讨论(0)
  • 2020-12-02 02:12

    Starting the activity from your service each time a new message is received might not be what you want. For instance, if you are viewing a different activity you will be interrupted by the new message.

    You can use sendBroadcast(intent) along with a BroadcastReceiver to notify an activity that a new message has been received.

    0 讨论(0)
提交回复
热议问题