android開發記錄一些技巧

一些技巧

  1. 獲取全局context
public class MineApplication extends Application {
    private static Context context;

    public static Context getContext() {
        return context;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
    }

}
  1. 使用Intent傳遞對象

    Serializable 比Parcelable 效率低??

  2. 定製自己的日誌工具

  3. 創建定時任務

    定時啓動某服務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);
           }
  4. Doze模式

    用戶長時間不使用手機,會進入Doze模式,很多行爲被限制

    setAndAllowWhileIdle setExactAndAllowWhileIdle在doze模式也可以執行?

  5. 多窗口模式

    1).避免進入多窗口模式,重新創建

    android:configChanges=”orientation|keyboardHidden|screenSize|screenLayout”

    2).android:resizeableActivity=”false”

    此節點是否支持多窗口 activity或application

    3).targetSdkVersion 低於24並且不支持橫豎屏切換,就不支持多窗口模式

  6. lambda表達式

    使支持labda表達式

    android.compileOptions.sourceCompatibility 1.8
    android.compileOptions.targetCompatibility 1.8

    類似es6

    swipeRefresh.setOnRefreshListener(() -> 
       requestWeather(weatherId)
    );
    navButton.setOnClickListener((v)-> 
           drawerLayout.openDrawer(GravityCompat.START)
    );
  7. SerializedName

    public class Now{
    //通過註釋的方式建立映射關係
       @SerializedName("tmp")
       public String temperature;
    
       @SerializedName("cond")
       public More more;
    
       public class More {
    
           @SerializedName("txt")
           public String info;
    
       }
    
    }
  8. 背景圖和狀態欄融合

    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進行處理
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章