andriod 多个Activity之间共享数据
在项目中要在多个Activity之间共享数据,刚开始想了多种方法,但是都失败了,通过查找资料,Android提供了一个叫Application的共享数据很合适,下面就贴出代码。
写一个继承Application的数据模型
package cn.edu.cqu.bluetooth.dao;import android.app.Application;public class Bluetooth extends Application{String mDeviceAddress;String mDeviceName;String phoneMac;public String getPhoneMac() {return phoneMac;}public void setPhoneMac(String phoneMac) {this.phoneMac = phoneMac;}public String getmDeviceAddress() {return mDeviceAddress;}public void setmDeviceAddress(String mDeviceAddress) {this.mDeviceAddress = mDeviceAddress;}public String getmDeviceName() {return mDeviceName;}public void setmDeviceName(String mDeviceName) {this.mDeviceName = mDeviceName;}
}
跟一般的数据模型很像,只不过这个是继承了Application,然后要在AndroidManifest.xml中注册。
这个一定不能少。
下面就是写入数据。
Bluetooth bluetooth = (Bluetooth) getApplicationContext();bluetooth.setPhoneMac(phoneMac);bluetooth.setmDeviceAddress(device.getAddress());bluetooth.setmDeviceName(device.getName());
然后获取数据
Bluetooth bluetooth = (Bluetooth) getApplicationContext();System.out.println("bluetooth---" + bluetooth);mDeviceName = bluetooth.getmDeviceName();mDeviceAddress = bluetooth.getmDeviceAddress();phoneMac = bluetooth.getPhoneMac();这样共享数据就OK了!
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
