Skip to content

Instantly share code, notes, and snippets.

@sahara-ooga
Last active March 18, 2020 15:00
Show Gist options
  • Save sahara-ooga/31f8873209fe0fff86b31723fa596d5a to your computer and use it in GitHub Desktop.
Save sahara-ooga/31f8873209fe0fff86b31723fa596d5a to your computer and use it in GitHub Desktop.
アンドロイドメモ

LiveData

LifecycleOwnerインターフェイスに準拠したオブジェクトのライフサイクルに応じて、オブザーバーに情報を通知するオブジェクト。

adbコマンド

複数の端末(エミュレーター含む)を動かしているときに、端末を指定してコマンドを実行する

$ adb devices
List of devices attached
L2NY760L6999J3D device
emulator-5554   device
$ adb shell ps -A -s K2AXB7606962J3D | grep app_name
u0_u999      26810   924 4354472  79892 0                   0 S com.example.android.codelabs.lifecycle

ワイヤレスデバッグを始める

予め、Android端末のIPアドレスを控えておき、Android端末と開発端末を同じネットワークに接続しておく。

Android端末と開発端末を有線で接続する。

$ adb tcpip 5555
$ adb connect <<android ip adress>>
$ adb disconnect

Wi-Fi越しにadb接続する - Qiita

ビルドで処理を分ける

[Android] debug ビルド時のソースを分ける & debug ビルドあれこれ - Qiita

if (BuildConfig.DEBUG) {
    // ...
}

デバッグビルドとその他のビルドを共存させる

build.gradle(app)と、AndroidManifestの編集が必要。

buildTypes {
        debug {
            //デバッグ時のインストールでは、アプリケーションIDを分ける
            //Google Play Store版、リリースビルドと共存するため
            applicationIdSuffix = ".debug"
        }
<provider
            android:name="androidx.core.content.FileProvider"
            <!-- 変更前  android:authorities="hogehoge-application-id-literal.fileprovider"  -->
            android:authorities="${applicationId}.fileprovider"
          <!--後略-->

Androidのデバッグ版とリリース版でパッケージ名、バージョン名、アプリ名、アイコンを変更する - Qiita

Product Flavorの使用

Product Flavorの定義

build.gradleに定義する。

android {
    ...
    productFlavors {
        create("production")
        create("develop")
    }
}

Product Flavorによる処理の分岐

if (BuildConfig.FLAVOR == "develop") {
//Product Flavorが"develop"のときに行う処理
}

OSバージョンで処理を分ける

[Android] OSのバージョンごとに処理や表示を分ける方法 - Qiita

Y.A.M の 雑記帳: Android ビルドバージョンで処理を分岐する

Google Play Storeに公開するにあたって設定したこと。

アプリを公開する  |  Android Developers

アイコン

512x512の素材を用意して、res右クリックからnew> image assets。以降はポチポチすればよしなに出来る。

AndroidManifest

<manifest>タグには、以下の属性を設定しなければならない。

android:versionName 外部に公開される値

android:versionCode 内部用の値

buid.gradleにも同じ値を設定する。

 |  Android Developers

Kotlinのコンストラクタ

初期化時に入力値(引数)のバリデーションを行ってから、プロパティに代入したい

ここでは例として、「引数の文字列が空文字だった場合、特定の文字列を代わりに値として設定する」ケースを挙げる。

class UserId(value: String) {
  val value = if (value == "") "anonymous" else value
}

Lifecycle.Stateの取得

現在のライフサイクル上の状態を取得する事ができる。

アプリ全体の状態

ProcessLifecycleOwner.get().lifecycle.currentState

Activityの状態

this.lifecycle.currentState

import android.hardware.Sensor
import android.hardware.SensorManager
//どのセンサーが利用可能かを調べる
interface SensorChecker {
var sensorManager: SensorManager
/*
* 取得できるセンサーの一覧を出力する
* */
fun availableSensors(): List<String> {
val sensors = sensorManager.getSensorList(Sensor.TYPE_ALL)
return sensors.map { it.name }
}
/*
* センサーが取得できるかどうかを調べる
* */
fun canGetSensor(sensorNumber: Int): Boolean {
val sensor = sensorManager.getDefaultSensor(sensorNumber)
return sensor != null
}
}

View Binding

android studioは3.6以上が必要。

ビューバインディングの使用をbuild.gradleに宣言する。

android {
   viewBinding.enabled = true
}

kotlin DSLの場合:

build.gradle.kts(.)

buildscript {
    dependencies {
       //3.6.0以上を指定
        classpath("com.android.tools.build:gradle:3.6.0")
  }
}

app/build.gradle.kts

android {
    viewBinding.isEnabled = true
}

バインディングしたいUIパーツにIDを追加する。IDを追加しないと、バインディングクラス内にそのビューへの参照は生成されない。

<!-activity_main.xml内->
<TextView
 android:id="@+id/text_view"       

バインディングクラスを初期化して、セットする。

//MainActivityに対応するバインディングクラス
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)

バインディングクラスのプロパティとしてUIパーツの参照を取れる。

binding.textView.text = "test"

バインディングクラスの初期化はby lazyを使うことも可能。

class MainActivity : AppCompatActivity() {
    private val binding by lazy {
        ActivityMainBinding.inflate(layoutInflater)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        binding.textView.text = "test"
    }
}

View BindingとData bindingは同時にbuild.gradleに共存できないようだ。

ビューバインディング | android developer

ViewModelの生成

ViewModel

引数なし

//ViewModelの定義

//生成するコード

引数あり

ViewModelの定義

class SensorViewModel(context: Context, minimumPitch: Int, maxPitch: Int) : ViewModel() {
    @Suppress("UNCHECKED_CAST")
    class Factory(
            private val context: Context,
            private val minimumPitch: Int,
            private val maxPitch: Int
    ) : ViewModelProvider.NewInstanceFactory() {
        override fun <T : ViewModel?> create(modelClass: Class<T>): T {
            return SensorViewModel(context, minimumPitch, maxPitch) as T
        }
    }
}

ViewModelを使う側での生成

//Activity内
val sensorViewModel = ViewModelProvider(
                this,
                SensorViewModel.Factory(this, minimumPitch, maxPitch)
        ).get(SensorViewModel::class.java)

AndroidViewModel

追加の引数なし

ViewModelの定義

class FooViewModel(application: Application) : AndroidViewModel(application) {
}

ViewModelを生成するコード

    private val fooViewModel by lazy {
        ViewModelProvider(this).get(FooViewModel::class.java)
    }

追加の引数あり

ViewModelの定義

class FooViewModel(
        application: Application,
        private val some: Some) : AndroidViewModel(application) {
  
    /**
     * 依存性注入ファクトリー
     * */
    class Factory(
            private val application: Application,
            private val some: Some
    ) : ViewModelProvider.AndroidViewModelFactory(application) {
        override fun <T : ViewModel?> create(modelClass: Class<T>): T {
            return when (modelClass) {
                FooViewModel::class.java -> {
                    FooViewModel(
                            application = application,
                            some = some
                    ) as T
                }
                else -> {
                    throw  RuntimeException("Cannot create an instance of $modelClass")
                }
            }
        }
    }
}

ViewModelを生成するコード

    private val  fooViewModel: FooViewModel by lazy {
        ViewModelProvider(this,
                FooViewModel.Factory(
                        application,
                        Some()
                )
        ).get(FooViewModel::class.java)
    }

Reference

ViewModel、ViewModelProviderについて調べてみた(Android) - URL Memo - Medium

Android Architecture Components 初級 ( MVVM + LiveData + Coroutines 編 ) ref: https://qiita.com/Tsutou/items/69a28ebbd69b69e51703

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment