详解Android中Intent传递对象给Activity的方法

2019-12-10 18:14:10于丽

(6)onStop() 当activity转换成不可见的时候,这个方法调用。
(7)onDestory() 在activity消亡之前这个方法被返回。activity被消亡的原因可能是因为自身的结束也可能是因为系统回收了内存,具体是哪一种可以通过调用方法isFinishing()确认。
 
如果设备的配置信息发生了改变,activity也要发生改变,它要从它当前所处的阶段走向onDestory(),如果当前的activity所处的阶段在可视阶段或者是前景阶段,就会重新生成一个符合当前配置的activity。如果想要绕过重新生成一个activity,可以在manifest中的android:configChanges属性中设置,并且在发生相应的配置变化的时候,会调用activity的onConfigurationChanged(Configuration)方法,而不会去重新start一个activity,如果配置的变化没有事先在android:configChanges中声明,则不会调用此方法。

Intent传递对象给Activity
 通过Intent,一个activity可以很容易的启动另一个activity,并且传递相关的数据给activity,通过Intent的putEXtra()方法,可以传递boolean、int、double等基本数据类型,如果想要传递对象的话,那么该对象必须实现Serializable接口,通过intent方法的putExtra(String name,Serializable value)方法,将对象传递过去。在接收方的activity通过intent.getExtra(name)方法获得该对象。

发送消息的acitivity的layout.xml:

<RelativeLayout xmlns:android="http://www.easck.com/apk/res/android"
  xmlns:tools="http://www.easck.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context=".Main" >
 
  <Button
    android:id="@+id/btn"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="next" />
 
</RelativeLayout>

Main.java:

package com.app.main;
 
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
 
public class Main extends Activity {
 
  Button btn = null;
 
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
 
    setContentView(R.layout.main);
 
    btn = (Button) this.findViewById(R.id.btn);
 
    btn.setOnClickListener(new OnClickListener() {
 
      @Override
      public void onClick(View arg0) {
 
        Intent intent = new Intent();
 
        Person p = new Person();
 
        p.setName("wx");
 
        p.setGender("boy");
 
        p.setAge(25);
 
        intent.putExtra("person", p);
 
        intent.setClass(Main.this, NextMain.class);
 
        Main.this.startActivity(intent);
         
         
       
      }
 
    });
 
  }
}