一些技巧
- 獲取全局context
public class MineApplication extends Application {
private static Context context;
public static Context getContext() {
return context;
}
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
}
使用Intent傳遞對象
Serializable 比Parcelable 效率低??
定製自己的日誌工具
創建定時任務
定時啓動某服務setExact比set精確
AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE); int anHour = 8 * 60 * 60 * 1000; // 這是8小時的毫秒數 long triggerAtTime = SystemClock.elapsedRealtime() + anHour; Intent i = new Intent(this, AutoUpdateService.class); PendingIntent pi = PendingIntent.getService(this, 0, i, 0); manager.cancel(pi); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { manager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi); }else { manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi); }
Doze模式
用戶長時間不使用手機,會進入Doze模式,很多行爲被限制
setAndAllowWhileIdle setExactAndAllowWhileIdle在doze模式也可以執行?
多窗口模式
1).避免進入多窗口模式,重新創建
android:configChanges=”orientation|keyboardHidden|screenSize|screenLayout”
2).android:resizeableActivity=”false”
此節點是否支持多窗口 activity或application
3).targetSdkVersion 低於24並且不支持橫豎屏切換,就不支持多窗口模式
lambda表達式
使支持labda表達式
android.compileOptions.sourceCompatibility 1.8 android.compileOptions.targetCompatibility 1.8
類似es6
swipeRefresh.setOnRefreshListener(() -> requestWeather(weatherId) ); navButton.setOnClickListener((v)-> drawerLayout.openDrawer(GravityCompat.START) );
SerializedName
public class Now{ //通過註釋的方式建立映射關係 @SerializedName("tmp") public String temperature; @SerializedName("cond") public More more; public class More { @SerializedName("txt") public String info; } }
背景圖和狀態欄融合
if (Build.VERSION.SDK_INT >= 21) { View decorView = getWindow().getDecorView(); decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE); getWindow().setStatusBarColor(Color.TRANSPARENT); } //對decorView進行處理