catch块中找不到合适的异常——android studio java

sqougxex  于 2021-07-07  发布在  Java
关注(0)|答案(1)|浏览(328)

我试着做一个按钮,如果设备上有两个计算器,它就会启动其中一个。我正在尝试使用android原始计算器和三星。我正在尝试使用try-catch块方法,但它不起作用。它可以成功地推出安卓计算,但它没有成功地推出三星一,虽然我肯定,弹出计算是在设备上的问题。取而代之的是,它与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;
8oomwypt

8oomwypt1#

在@sontroung的帮助下,我找到了解决办法。我用了他的建议,但当使用它时,它崩溃了设备上没有计算器的应用程序。相反,我在第一个catch中添加了另一个嵌套的'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();
    }
}

相关问题