- 全局获取Context的技巧
Android提供了一个Application类,每当应用程序启动的时候,系统就会自动将这个类进行初始化。而我们可以定制一个自己的Application类,以便于管理程序内一些全局的状态信息,比如全局Context。
示例如下:
public class MyApplication extends Application{
private static Context context;
@Override
public void onCreate(){
context=getApplicationContext();
}
public static Context getContext(){
return context;
}
}
这里我们重写了父类的onCreate()方法,并通过调用getApplicationContext()方法得到了一个应用程序级别的Context,然后提供了一个静态的getContext()方法,返回刚才赋值的context。
接下来我们需要告知系统,当程序启动的时候应该初始化MyApplication类,而不是默认的Application类。即是在AndroidManifest.xml文件的<application>标签下进行指定就可以了,代码如下所示
…
<application
android:name=”com.example.XXX.MyApplication”
…>
…
解决与LitePal冲突的问题:
在MyApplication类的onCreate()中添加语句:LitePal.initialize(context);
- 使用Intent传递对象
- Serializable
Serializable是序列化的意思,表示将一个对象转换成可存储或可传输的状态。序列化后的对象可以在网络上进行传输,也可以存储本地。至于序列化的方法,只要让一个类去实现Serializable这个接口就行了。
示例如下:
public class Person implements Serializable{
private String name;
public String getName(){
return name;
}
Public void setName(String name){
this.name=name;
}
}
然后利用Intent传递它。
Intent intent=new Intent(MainActivity.this,SecondActivity.class);
Intent.putExtra(“person_data”,person);
startActivity(intent);
获取方法:
Person person=(Person) getIntent().getSerializableExtra(“person_data”);
-
- Parcelable
Public class Person implements Parceblable{
private String name;
private int age;
@Override
public int describeContents(){
return 0;
}
@Override
public void writeToParcel(Parcel dest,int flags){
dest.writeString(name);//写出name
dest.writeInt(age);//写出age
}
public static final Parcel.Creator<Person> CREATOR=new Parcelable.Creator<Person>(){
@Override
public Person createFromParcel(Parcel source){
Person person=new Person();
person.name=source.readString();//读取name
person.age=source.readInt();//读取age
return person;
}
@Override
public Person[] newArray(int size){
return new Person[size];
}
};
}
从上面的例子里可以看出Parcelable的具体用法。
传递代码与Serializable相同。
获取代码修改一下:
Person person =(Person) getIntent().getParcelableExtra(“person_data”);
一般建议使用第二种方法效率较高。