应用程序崩溃,当我尝试发送短信

问题描述:

我尝试在科特林发送短信,我写了简单的应用程序用下面的代码:应用程序崩溃,当我尝试发送短信

import android.support.v7.app.AppCompatActivity 
import android.os.Bundle 
import android.telephony.SmsManager 
import android.widget.TextView 
import kotlinx.android.synthetic.main.activity_main.* 

class MainActivity : AppCompatActivity() { 

override fun onCreate(savedInstanceState: Bundle?) { 
    super.onCreate(savedInstanceState) 
    setContentView(R.layout.activity_main) 
    val textView = findViewById(R.id.mainTextView) as TextView 
    SEND.setOnClickListener { 
     textView.setText("click") 
     val sm = SmsManager.getDefault() 
     sm.sendTextMessage("123123123", null, "test", null, null) 
     textView.setText("OK") 

    } 
    } 
} 

,当我试图通过USB电缆AndroidStudio应用不希望权限运行的应用程序尽管我已经添加了许可SEND_SMS来显示。当我按下按钮应用程序关闭时

+0

邮政logcat的? – Raghavendra

+0

您是否添加了运行时权限,如果您正在运行Android版本> = 23的应用程序 –

您必须自行申请许可。 在本guide

// Here, thisActivity is the current activity 
if (ContextCompat.checkSelfPermission(thisActivity, 
      Manifest.permission.SEND_SMS) 
    != PackageManager.PERMISSION_GRANTED) { 

    // Should we show an explanation? 
    if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity, 
     Manifest.permission.SEND_SMS)) { 

     // Show an explanation to the user *asynchronously* -- don't block 
     // this thread waiting for the user's response! After the user 
     // sees the explanation, try again to request the permission. 

    } else { 

     // No explanation needed, we can request the permission. 

     ActivityCompat.requestPermissions(thisActivity, 
      new String[]{Manifest.permission.SEND_SMS}, 
      MY_PERMISSIONS_REQUEST_SEND_SMS); 

     // MY_PERMISSIONS_REQUEST_SEND_SMS is an 
     // app-defined int constant. The callback method gets the 
     // result of the request. 
    } 
} 

描述如果你不想使用运行时的权限在您的摇篮目标SDK版本设置为21。

摇篮添加目标SDK这样的:

android { 
    defaultConfig { 
     ..... 
     ..... 
     targetSdkVersion 21 
    } 
}