intent(1、传递参数)

intent意思为“意图、目的”,作为不同组件之间的信息传递媒介,主要是以下三个:

  • activity:     startActivity() 和 startActivityForResult();
  • Service:     startService() 和 bindService();
  • Broadcast: sendBroadcast()、sendOderedBroadcast()和sendStickyBroadcast();

intent在不同组件件传递参数,主要涉及如下几类:

  • 基本数据,如字符串、整数等,如下:
//发送

intent.putExtra("key1", "value1");

intent.putExtra("key2", 2.0f);



//接受

Intent intent  = this.getIntent();

String value1  = intent.getStringExtra("key1");

float  value2   = intent.getFloatExtra("key2",0);
  • 利用bundle
    • 将对象集成 Serializable 接口
public class User implements Serializable { //也可以是parcelable,类似
    • 向intent增加bundle,如下:
//发送

Bundle bundle = new Bundle();

                    

User user = new User();

user.setUsername("fredric");

user.setPassword("sinny");

bundle.putSerializable("user", user);

intent.putExtras(bundle);   



//接收

Intent intent = this.getIntent();

Bundle bundle = intent.getExtras();

        

User user = (User) bundle.get("user");     

 

  • 强制类型转换,如下例:
//发送

List<User> userlist = new ArrayList<User>();

for(int i = 0; i < 10; i++){

    User tmp = new User();

    tmp.setUsername("sinny");

    tmp.setPassword("fredric" + i);

    userlist.add(tmp);

}

                    

intent.putExtra("userlist", (Serializable)userlist);



//接收

List<User> userlist = (List<User>)intent.getSerializableExtra("userlist");

        

Iterator<User> iterator = userlist.iterator();

        

while(iterator.hasNext()){

    User tmp = iterator.next();

    Log.i(TAG_ACTIVITY, tmp.getUsername() + tmp.getPassword());

}

 

你可能感兴趣的:(intent)