簡體   English   中英

如何使用Android Studio在Kotlin代碼中添加try / catch?

[英]How to add try/catch in kotlin code using android studio?

我必須在使用Android Studio的同時在我的Kotlin代碼中添加try / catch,但不知道如何添加它。 以下是我必須添加try / catch的代碼。

我還沒有嘗試任何東西,因為我完全困惑在哪里嘗試/捕獲。

1。

class SmsReceiver : BroadcastReceiver(){
    override fun onReceive(context: Context?, intent: Intent) {

        val extras = intent.extras

        if(extras != null){

            val sms: Array<Any> = extras.getString("pdus") as Array<Any>

            for(i in sms.indices){
                val format = extras.getString("format")

                var smsMessage = if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
                    SmsMessage.createFromPdu(sms[i] as ByteArray,format)
                }else{
                    SmsMessage.createFromPdu(sms[i] as ByteArray)
                }

                var phoneNumber = smsMessage.originatingAddress
                val messageText = smsMessage.messageBody.toString()

                Toast.makeText(context,"$phoneNumber:(Private)\n" + "messageText: $messageText",Toast.LENGTH_SHORT).show()
            }
        }
    }

}

2。

class MainActivity :AppCompatActivity(){

    private val requestReceiveSms: Int = 3

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        if(ActivityCompat.checkSelfPermission(this,android.Manifest.permission.RECEIVE_SMS) !=
            PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.RECEIVE_SMS),
                requestReceiveSms)
        }

    }
}

我原本希望“ SMS收到Toast消息”,但是卻收到“不幸的是,應用程序已停止”並崩潰。

try {
    if(extras != null){

        val sms: Array<Any> = extras.getString("pdus") as Array<Any>

        for(i in sms.indices){
            val format = extras.getString("format")

            var smsMessage = if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
                SmsMessage.createFromPdu(sms[i] as ByteArray,format)
            }else{
                SmsMessage.createFromPdu(sms[i] as ByteArray)
            }

            var phoneNumber = smsMessage.originatingAddress
            val messageText = smsMessage.messageBody.toString()

            Toast.makeText(context,"$phoneNumber:(Private)\n" + "messageText: $messageText",Toast.LENGTH_SHORT).show()
        }
    }
}catch (ex:Exception){
   //your error handling code here
   //here, consider adding Log.e("SmsReceiver", ex.localizedMessage)
   //this log statement simply prints errors to your android studio terminal and will help with debugging, alternatively leave it out 
        if (context != null){
            Toast.makeText(context!!,ex.localizedMessage, Toast.LENGTH_SHORT).show()  
           }
}

您應該應用try catch可能引發異常的代碼。 對於您發布的代碼,在某些地方它可能會崩潰,例如索引超出范圍( sms[i] )或if( extras.getString("pdus" )找不到此密鑰,因此我的解決方案兩者都在同一個try catch中,然后您可以做例外處理由您決定。

如果要處理更具體的異常,也可以執行以下操作:

try {
            if(extras != null){

                val sms: Array<Any> = extras.getString("pdus") as Array<Any>

                for(i in sms.indices){
                    val format = extras.getString("format")

                    var smsMessage = if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
                        SmsMessage.createFromPdu(sms[i] as ByteArray,format)
                    }else{
                        SmsMessage.createFromPdu(sms[i] as ByteArray)
                    }

                    var phoneNumber = smsMessage.originatingAddress
                    val messageText = smsMessage.messageBody.toString()

                    Toast.makeText(context,"$phoneNumber:(Private)\n" + "messageText: $messageText",Toast.LENGTH_SHORT).show()
                }
            }
        }catch (indexOutOfBoundsException:IndexOutOfBoundsException){
           //your error handling code here
        } catch (nullpointer : NullPointerException){
          //your error handling code here
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM