在项目中要在多个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中注册。
<application
android:name="cn.edu.cqu.bluetooth.dao.Bluetooth"
android:label="@string/app_name"
android:icon="@drawable/ic_launcher"
android:theme="@android:style/Theme.Holo.Light">
这个一定不能少。
下面就是写入数据。
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了!