[英]I can't find the right exception in Try-Catch Block — Android Studio Java
I'm trying to make a button that launches one of two calculators should any of them exist on the device.如果设备上存在两个计算器中的任何一个,我正在尝试制作一个按钮来启动两个计算器之一。 I'm attempting to use the Android original calculator and Samsung.
我正在尝试使用 Android 原装计算器和三星。 I'm trying to use the try-catch block method but it doesn't work.
我正在尝试使用 try-catch 块方法,但它不起作用。 it can successfully launch the android calc but it doesn't successfully launch the Samsung one although I know for certain that the popup calc is on the device in question.
它可以成功启动 android 计算,但它没有成功启动三星,尽管我确定弹出计算在有问题的设备上。 instead, it goes to the catch with the Toast message.
相反,它使用 Toast 消息进行捕获。 I'm assuming that I just don't have the right exception for the catch.
我假设我只是没有正确的捕获例外。 please help me to find the correct code.
请帮我找到正确的代码。
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;
With @SonTroung help, I find the solution.在@SonTroung 的帮助下,我找到了解决方案。 I used his suggestion above but when using it, it crashed the app on the device which has no calculator.
我在上面使用了他的建议,但是在使用它时,它使没有计算器的设备上的应用程序崩溃。 instead, I added another 'try {' nested in the first catch.
相反,我在第一个捕获中添加了另一个“try {”。 that worked.
那行得通。
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.