[英]I can't find the right exception in Try-Catch Block — Android Studio Java
如果設備上存在兩個計算器中的任何一個,我正在嘗試制作一個按鈕來啟動兩個計算器之一。 我正在嘗試使用 Android 原裝計算器和三星。 我正在嘗試使用 try-catch 塊方法,但它不起作用。 它可以成功啟動 android 計算,但它沒有成功啟動三星,盡管我確定彈出計算在有問題的設備上。 相反,它使用 Toast 消息進行捕獲。 我假設我只是沒有正確的捕獲例外。 請幫我找到正確的代碼。
try {
//this is android original calculator
Intent i = new Intent();
i.setClassName("com.android.calculator2", "com.android.calculator2.Calculator");
startActivity(i);
}
catch (UnsupportedOperationException e){
//This Launch Samsung calculator
Intent i = new Intent();
i.setClassName("com.sec.android.app.popupcalculator","com.sec.android.app.popupcalculator.Calculator");
startActivity(i);
} catch (Exception e) {
//should no calculator found it will display this massage
Toast tt = Toast.makeText(MainActivity.this,"SORRY I CANT OPEN CALCULATOR", Toast.LENGTH_LONG);
tt.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
tt.show();
}
break;
在@SonTroung 的幫助下,我找到了解決方案。 我在上面使用了他的建議,但是在使用它時,它使沒有計算器的設備上的應用程序崩潰。 相反,我在第一個捕獲中添加了另一個“try {”。 那行得通。
try {
//this is android original calculator
Intent i = new Intent();
i.setClassName("com.android.calculator2", "com.android.calculator2.Calculator");
startActivity(i);
} catch (ActivityNotFoundException e) {
//This Launch Samsung calculator
try {
Intent i = new Intent();
i.setClassName("com.sec.android.app.popupcalculator", "com.sec.android.app.popupcalculator.Calculator");
startActivity(i);
} catch (Exception e) {
//should no calculator found it will display this massage
Toast tt = Toast.makeText(MainActivity.this, "SORRY I CANT OPEN CALCULATOR", Toast.LENGTH_LONG);
tt.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
tt.show();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.