Android高级技巧
16lz
2021-01-25
对《第一行代码——Android》的读书笔记
全局获取Context的技巧
解决脱离Activity时获取Context
Android提供了一个Application类,每当应用程序启动时系统会自动将这个类进行初始化。我们可以定制一个自己的Application类,以便管理程序内一些成员变量,比如说全局Context
public class MyApplication extends Application {private static Context context;public void onCreate(){context=getApplicationContext();}public static Context getContext(){return context;}}
重写父类的onCreate()方法,并通过调用getApplicationContext()方法得到一个用用程序级别的Context,然后又提供了一个静态的getContext()方法,在这里将刚才获取到的Context进行返回
最重要的是需要告知系统,当程序启动时应该初始化MyApplication类,而不是默认的Application类。
之后不管在任何地方,只需调用MyApplication.getContext()就可以啦
使用Intent传递对象
可以借助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;}}
Person person=new Person();person.setName("tom");Intent intent=new Intent(FristActivity.class,SecondActivity.class);intent.putExtra("person_data", person);startActivity(intent)
Person person=(~)getIntent().getSerializableExtra("person_data");
Parcelable方式
public class Person implements Parcelable {private String name;@Overridepublic int describeContents() {// TODO Auto-generated method stubreturn 0;}@Overridepublic void writeToParcel(Parcel dest, int flags) {// TODO Auto-generated method stubdest.writeString(name);}public static final Parcelable.Creator<Person>CREATOR=new Parcelable.Creator<Person>() {@Overridepublic Person createFromParcel(Parcel source) {// TODO Auto-generated method stubPerson person=new Person();person.name=source.readString();//读取namereturn person;}@Overridepublic Person[] newArray(int size) {// TODO Auto-generated method stubreturn new Person[size];}};}
在SecondActivity中
Person person=(~)getIntent().getParcelableExtra("person_data");
更多相关文章
- Android(安卓)6.0关于权限的问题
- Android面试题(25)-Bundle机制
- Retrofit 源码解析
- Android中调用系统摄像并且保存到指定位置的一些问题&Uri转文件
- Android(安卓)Binder机制(3) 本地服务注册过程
- Android(安卓)程序获取、设置铃声音量
- 【Android(安卓)开发教程】理解Intent对象
- Parcelable使用(跨进程,Intent传输)
- Android(安卓)View,ViewGroup 事件分发