全局获取Context、Intent传递对象、日志类

来源:互联网 发布:淘宝拍卖车不可过户 编辑:程序博客网 时间:2024/06/04 23:00

1. 全局获取Context

创建Application类:

public class MyApplication extends Application{

private static Context context;

@override

public void onCreate(){

context = getApplicationContext();

}

public static Context getContext(){

return context;

}

}

在Manifest中application标签中初始化:

android:name="com.lewanjiang.test.MyApplication"


使用Context:

MyApplication.getContext()


如果使用LitePal和百度地图,这种配置过application的库时,可将MyApplication中修改:在onCreate方法中添加一句:

LitePalApplication.initialize(context);


2.用Intent传递对象

2.1 Serializable:

public class Book implements Serializable{ private String name;private String author;...}

Book book.setName("bob")...setAuthor

intent.putExtra("tran_data",book);

获取:Book book=(Book)getIntent().getSerizlizableExtra("tran_data");


2.2 Parcelable:

public class Book implements Parcelable {

 name,author...

@Override

public int describeContents() {return 0;}

@Override

public void writeToParcel(Parcel dest,int flags) {

dest.writeString(name);

dest.writeInt(author);

}

public static final Parcelable.Creator<Book> CREATOR=new Parcelable.Creator<Book>() {

@Override

public Book createFromParcel(Parcel source) {

Book person = new Book();

book.name = source.readString();

book.author = source.readInt();

return person;

}

@Override

public Person[] newArray(int size) {

return new Person[size];

}

};

发送和上面一样,接收变为:getIntent().getParcelableExtra("tran_data");


3.定制日志:

public class LogUtil {

public static final int VERBOSE = 1;

public static final int DEBUG = 2;

INFO = 3;WARN=4;ERROR=5;NOTHING=6;

public static int level = VERBOSE;

public static void v(String tag,String msg){if(level<=VERBOSE) Log.v(ta,msg); }

}

原创粉丝点击