1.全局获取context的技巧
public class MyApplication extends Application {
private static Context context;
@Override
public void onCreate() {
super.onCreate();
context=getApplicationContext();
}
public static Context getContext() {
return context;
}
}
2.使用Intent传递对象
- 使用Intent传递对象有两种实现方式:Serializable和Parcelable
-Serializable序列化:
public class Person implements Serializable {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
//传递
Person person=new Person();
person.setName("huazai");
person.setAge(18);
Intent intent=new Intent(……);
intent.putExtra("persong_data",person);
//获取
Person person1= (Person) getIntent().getSerializableExtra("persong_data");
- Parcelable方式:
public class Song implements Parcelable {
private String name;
private String singer;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSinger() {
return singer;
}
public void setSinger(String singer) {
this.singer = singer;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(name); //此处写和下面的读 必须顺序一致
parcel.writeString(singer);
}
public static final Parcelable.Creator<Song> CREATOR=new Parcelable.Creator<Song>(){
@Override
public Song createFromParcel(Parcel parcel) {
Song song=new Song();
song.name=parcel.readString();
song.singer=parcel.readString();
return song;
}
@Override
public Song[] newArray(int i) {
return new Song[i];
}
};
}
//使用
//传递
Song song=new Song();
song.setName("隐形人");
song.setName("孙燕姿");
Intent intent=new Intent();
intent.putExtra("songInfo",person);
//获取
Song song1=(Song) getIntent().getParcelableExtra("songInfo");
- log工具
- 程序断点调试
3. 创建定时任务
Alarm机制
长时间在后台定时运行的服务
public class LongRunningService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread(new Runnable() {
@Override
public void run() {
//执行具体逻辑
}
}).start();
AlarmManager manager= (AlarmManager) getSystemService(MyApplication.getContext().ALARM_SERVICE);
int anhour=60*60*1000;
long triggerAtTime= SystemClock.elapsedRealtime()+anhour;
Intent intent1=new Intent(this,LongRunningService.class);
PendingIntent pi=PendingIntent.getService(this,0,intent1,0);
//set不够精确,是系统在耗电方面的优化; setExact()会保证任务精确的执行
manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,triggerAtTime,pi);
return super.onStartCommand(intent, flags, startId);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
4. Doze模式
- 当用户设备是android6.0以上,该设备未接电源,且屏幕关闭一段时间,就会进入到Doze模式;该模式下,会对CPU,网络,alarm等活动进行限制,从而延长电池寿命。
5.多窗口模式
- android 7.0 及以上
- 禁用
<application
android:resizeableActivity="false"
……
6. Lambda表达式
- java 8 特色功能,