2021 Sep. 17.
概要
下記コード例では、
getConnectionSmb()において、非同期ワーカースレッドでSMB接続を行うconnectSmb(): Booleanの結果を取得している。
getConnectionSmb()内でviewModelScope.launch(Dispatchers.IO) { }を利用し、その中でconnectSmb()を呼び出している。
connectSmb()内ではコルーチンに関わるものは何も記述していない。
getConnectionSmb()内のviewModelScope.launch(Dispatchers.IO)により、connectSmb()内は非同期ワーカースレッドでの動作となり、また、そこに記述されたコマンドが、前の処理が終了したら次の処理着手と、順次実行されるので、SMB接続処理終了を待ってconnectSmb()の結果がgetConnectionSmb()に返される。
kotlinコード
SmbViewModel.kt
// 2021 Sep. 17 class SmbViewModel(val user: String, val password: String, val domain: String, val smbUrl: String): ViewModel() { lateinit var smb: SmbFile fun getConnectionSmb(){ viewModelScope.launch(Dispatchers.IO) { // connect to SMB server in worker thread Log.d("MyApp", "Now start Connecting to SMB") if (connectSmb()) { Log.d("MyApp", "Connected to SMB") } else { Log.d("MyApp", "Failed to connect to SMB") } } } // SMBサーバーに接続し、接続オブジェクトをsmbに入れる private fun connectSmb(): Boolean { try { val prop = Properties() // java.util.Properties prop.setProperty("jcifs.smb.client.minVersion", "SMB202") prop.setProperty("jcifs.smb.client.maxVersion", "SMB300") val baseCxt = BaseContext(PropertyConfiguration(prop)) val auth = baseCxt.withCredentials(NtlmPasswordAuthenticator(domain, user, password)) // connect to SMB server smb = SmbFile(smbUrl, auth) Log.d("MyApp", "List: "+ smb.list()) // Check if SmbFile() succeeded or failed } catch (e: Exception) { Log.d("MyApp", "1: " + e.toString()) try { smb.close() } catch (e: Exception) { Log.d("MyApp", "2: " + e.toString()) return false } return false } Log.d("MyApp", "Finished to connect to SMB function") return true }
SmbViewModelFactory.kt
// 2021 Sep. 06. import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider class SmbViewModelFactory(val user: String, val password: String, val domain: String, val smbUrl: String): ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return SmbViewModel(user, password, domain, smbUrl) as T } }