3

アプリに 4 つのボタンがあります。これらのボタンのうち 2 つでは、実行したいアプリがデバイスにあるかどうかを確認する必要があります。存在する場合は実行し、存在しない場合はトーストを表示します。

問題は、トーストを表示するとき、アプリケーションを閉じるときです。startActivity(Intent) でトーストを表示する最良の方法は何ですか???

これはコードです:

public void onClick(View v) {

    Intent LaunchIntent = null;
    boolean isTouch = isAppInstalled("com.enflick.android.ping");
    boolean isWpress = isAppInstalled("org.wordpress.android");


    switch (v.getId()) {
    case (R.id.botonPortafoli):
        LaunchIntent = new Intent(this, PortafoliActivity.class);
        break;
    case (R.id.botonSocial):
        LaunchIntent = new Intent(this, SocialActivity.class);
        break;

    case (R.id.botonTouch):

        if (isTouch) {
            LaunchIntent = getPackageManager().getLaunchIntentForPackage(
                    "com.enflick.android.ping");

        } else {
            Toast.makeText(this, R.string.no_inst, Toast.LENGTH_LONG)
                    .show();

            break;
        }

        break;
    case (R.id.botonWpress):

        if (isWpress) {
            LaunchIntent = getPackageManager().getLaunchIntentForPackage(
                    "org.wordpress.android");

            break;

        } else {

            Toast.makeText(this, R.string.no_inst, Toast.LENGTH_LONG)
            .show();


            break;
        }

    }
startActivity(LaunchIntent);
4

1 に答える 1

0

代わりにisAppInstalled("com.enflick.android.ping")、呼び出しを try/catch で囲むことができます。実際にアプリを起動しないとアプリがインストールされているかどうかを確認できないと思います...

public void onClick(View v) {

    Intent LaunchIntent = new Intent();

    if (v.getId() == (R.id.botonPortafoli)) {
        LaunchIntent = new Intent(this, PortafoliActivity.class);
        startActivity(LaunchIntent);
    } else if (v.getId() == (R.id.botonSocial)) {
        LaunchIntent = new Intent(this, SocialActivity.class);
        startActivity(LaunchIntent);
    } else if (v.getId() == (R.id.botonTouch)) {
        try {
            LaunchIntent = getPackageManager().getLaunchIntentForPackage(
                    "com.enflick.android.ping");
            startActivity(LaunchIntent);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, R.string.no_inst, Toast.LENGTH_LONG).show();
        }
    } else if (v.getId() == (R.id.botonWpress)) {
        try {
            LaunchIntent = getPackageManager().getLaunchIntentForPackage(
                    "org.wordpress.android");
            startActivity(LaunchIntent);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, R.string.no_inst, Toast.LENGTH_LONG).show();
        }
    }
}

公式の Twitter アプリがデバイスにインストールされているかどうかを確認しようとしていたときに、これが機能することを願っています。

ところで、安全のために、リソース ID が最終的な問題ではないことを回避するif-else代わりに、使用する方が良いかもしれません。switch

于 2012-12-05T16:53:16.743 に答える