Android数据传递方式

一、使用Intent & Bundle传递数据。
(1)传递简单数据

//传递数据
Bundle bundle = new Bundle();
Intent intent = new Intent(MainActivity.this, TransmitActivity.class);
bundle.putString("name", "张三");
bundle.putString("age", "23");
intent.putExtra("person", bundle);
startActivity(intent);
//接收数据
Intent intent = getIntent();
Bundle bundle = intent.getBundleExtra("person");
String name = bundle.getString("name");
String age = bundle.getString("age");
tv_name.setText("姓名:" + name + "\n" + "年龄:" + age);

(2)传递复杂数据
把数据转成Serializable对象

public class Person implements Serializable {
    private String name;
    private String age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }
}
//传递数据
Person person = new Person();
person.setName("李四");
person.setAge("24");
Bundle bundle = new Bundle();
Intent intent = new Intent(MainActivity.this, TransmitActivity.class);
bundle.putSerializable("person", person);
intent.putExtras(bundle);
startActivity(intent);
//接收数据
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
Person person = (Person) bundle.getSerializable("person");
tv_name.setText("姓名:" + person.getName() + "\n" + "年龄:" + person.getAge());

(3)传递回传数据

//传递数据
Person person = new Person();
person.setName("李四");
person.setAge("24");
Bundle bundle = new Bundle();
Intent intent = new Intent(MainActivity.this, TransmitActivity.class);
bundle.putSerializable("person", person);
intent.putExtras(bundle);
startActivityForResult(intent, 200);

//重写onActivityResult方法,用来接收TransmitActivity回传的数据。
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == 30) {
        String name = data.getStringExtra("name");
        String age = data.getStringExtra("age");
        tv_name.setText("姓名:" + name + "\n" + "年龄:" + age);
    }
}
//onKeyDown方法,监听返回按钮。回传数据
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        Intent intent = new Intent();
        intent.putExtra("name", "王五");
        intent.putExtra("age", "25");
        setResult(30, intent);
        finish();
    }
    return true;
}

二、通过存储介质来分享数据:SharedPreferences
创建工具类

public class SharedPreferencesUtils {
    public static final String name = "test";
    private static SharedPreferencesUtils instance;


    public static SharedPreferencesUtils getInstance() {
        if (instance == null) {
            synchronized (SharedPreferencesUtils.class) {
                if (instance == null) {
                    instance = new SharedPreferencesUtils();
                }
            }
        }
        return instance;
    }

    /**
     * 保存数据,修改数据
     *
     * @param key
     * @param value
     * @param 
     */
    public  void setValue(@NonNull String key, V value) {
        SharedPreferences sp = MyApp.getInstance().getSharedPreferences(name, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        if (value instanceof String) {
            editor.putString(key, (String) value);
        } else if (value instanceof Integer) {
            editor.putInt(key, (Integer) value);
        } else if (value instanceof Long) {
            editor.putLong(key, (Long) value);
        } else if (value instanceof Boolean) {
            editor.putBoolean(key, (Boolean) value);
        } else if (value instanceof Float) {
            editor.putFloat(key, (Float) value);
        }
        editor.commit();
    }

    /**
     * 读取数据
     *
     * @param key
     * @param defaultValue
     * @param 
     * @return
     */
    public  V getValue(@NonNull String key, V defaultValue) {
        SharedPreferences sp = MyApp.getInstance().getSharedPreferences(name, Context.MODE_PRIVATE);
        Object value = defaultValue;
        if (defaultValue instanceof String) {
            value = sp.getString(key, (String) defaultValue);
        } else if (defaultValue instanceof Integer) {
            value = sp.getInt(key, (Integer) defaultValue);
        } else if (defaultValue instanceof Long) {
            value = sp.getLong(key, (Long) defaultValue);
        } else if (defaultValue instanceof Boolean) {
            value = sp.getBoolean(key, (Boolean) defaultValue);
        } else if (defaultValue instanceof Float) {
            value = sp.getFloat(key, (Float) defaultValue);
        }
        return (V) value;
    }

    /**
     * 清空数据
     */
    public void clearData() {
        SharedPreferences.Editor editor = MyApp.getInstance().
                getSharedPreferences(name, Context.MODE_PRIVATE).edit();
        editor.clear();
        editor.commit();
    }
}
//存储数据
SharedPreferencesUtils sharedPreferencesUtils = SharedPreferencesUtils.getInstance();
sharedPreferencesUtils.setValue("name", "赵六");
sharedPreferencesUtils.setValue("age", "26");
//获取数据
SharedPreferencesUtils sharedPreferencesUtils = SharedPreferencesUtils.getInstance(getApplicationContext());
String name = sharedPreferencesUtils.getValue("name", "null");
String age = sharedPreferencesUtils.getValue("age", "null");

三、通过接口的调用来传递数据
创建接口

public interface Transmit {
    void send(String name, String age);
}

调用接口

public class Person {
    public Transmit transmit;

    public Person(Transmit transmit) {
        this.transmit = transmit;
    }

    public void send() {
        transmit.send("田七", "27");
    }
}

实现接口

public class MainActivity extends AppCompatActivity implements Transmit {
    private TextView tv_name;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv_name = findViewById(R.id.tv_name);
        Person person = new Person(this);
        person.send();
    }


    @Override
    public void send(String name, String age) {
        tv_name.setText("姓名:" + name + "\n" + "年龄:" + age);
    }
}

四、通过广播的方式传递数据

//创建接收广播
public class MyBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String name = intent.getStringExtra("name");
        String age = intent.getStringExtra("age");
        tv_name.setText("姓名:" + name + "\n" + "年龄:" + age);
    }
}

//注册广播
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.intent.action.MY_BROADCAST_RECEIVER");
registerReceiver(new MyBroadcastReceiver(), intentFilter);
//发送广播
Intent intent = new Intent("android.intent.action.MY_BROADCAST_RECEIVER");
intent.putExtra("name","小明");
intent.putExtra("age","28");
sendBroadcast(intent);

你可能感兴趣的:(Android数据传递方式)