var button:Button = v.findViewById(R.id.button3)
val intent = Intent(Intent.ACTION_GET_CONTENT)
val mimeType = "audio/*"
val packageManager = activity!!.packageManager
首先宣告按鈕(Button)
Intent.ACTION_GET_CONTENT 代表可以從手機中選取數據
mimeType 設置成audio 代表音訊
packageManager
button.setOnClickListener(View.OnClickListener {
intent.type = mimeType
val list: List<ResolveInfo> = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
if (list.isNotEmpty()) { // 如果有可用的Activity
val picker = Intent(Intent.ACTION_GET_CONTENT)
picker.putExtra(Intent.EXTRA_LOCAL_ONLY, false)
picker.type = mimeType
// 使用Intent Chooser
val destIntent = Intent.createChooser(picker, "選取MP3音樂")
startActivityForResult(destIntent, 100)
} else { // 沒有可用的Activity
Toast.makeText(activity,"沒東西",Toast.LENGTH_SHORT).show()
}