【问题标题】:How to add try/catch in kotlin code using android studio?如何使用 android studio 在 kotlin 代码中添加 try/catch?
【发布时间】:2019-07-17 09:10:10
【问题描述】:

在使用 android studio 时,我必须在我的 kotlin 代码中添加 try/catch,但不明白如何添加。下面是我必须添加 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)
        }

    }
}

我希望“收到短信 Toast 消息”,但我收到“不幸的是,应用程序已停止”并崩溃..

【问题讨论】:

  • 你能发布崩溃中的 logcat 吗?
  • 嘿@MichaelDodd 使变量全局化的kotlin快捷方式是什么......就像在java中它的Ctrl+Alt+F
  • class MyApplication : Application() {var globalVar = "I am Global Variable"} 这样你就可以全局指定它了
  • @MichaelDodd 好的,我会发布它

标签: android kotlin try-catch


【解决方案1】:
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]) 或 (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
        }

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-14
  • 2021-01-15
  • 2012-06-19
  • 2012-04-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多