1

亲爱的溢出成员我刚刚获得了使用意图从不同应用程序启动类的帮助,我现在想知道我是否会使用“If”和“Else”来检查包是否存在以及它是否继续启动它但是如果它没有显示通知用户不存在的祝酒词,并且我尝试启动意图的方式是单击按钮。谢谢帮助

这是我要添加 if 和 else 的代码块。

Button button91 = (Button) findViewById(R.id.dlc);
        button91.setOnClickListener(new OnClickListener() {         
            public void onClick(View v) {

                Intent i=new Intent("com.dlc.MainActivity.class"); startActivity(i);
            }
        });
4

2 回答 2

2

不,如果失败,if/else 将不会作为startActivity()throws 异常工作,因此您需要使用try/catch

Intent i=new Intent("com.dlc.MainActivity.class"); 

try {
  startActivity(i);
} catch ( Exception e ) {
    // start activiy failed - show toast etc...
}

您应该使用PackageManager'sgetPackageInfo()来确定是否存在某个包。

文档: http: //developer.android.com/reference/android/content/pm/PackageManager.htmlhttp://developer.android.com/reference/android/content/pm/PackageManager.html#getPackageInfo%28java。 lang.String,%20int%29

于 2013-04-07T10:50:09.800 回答
1

您也许可以玩弄这个并让它在您的应用程序中工作。这是我的示例,因为谷歌没有将他们最近的日历应用程序提供给早期版本,我不得不在我的应用程序中使用它。它检查用户是否拥有应用程序,如果没有,则在应用程序描述页面上启动 Google Play 商店,以便他们可以下载它以使用应用程序中的功能。希望这可以帮助!

boolean installed = appInstalledOrNot("com.google.android.calendar");  
    if(installed)
    {               
        Intent launchCalendar = new Intent();
        String deviceVersion = Build.VERSION.RELEASE;
        String[] versions = deviceVersion.split("\\.");
        ComponentName googleCalendar = new ComponentName("com.google.android.calendar", "com.android.calendar.LaunchActivity");

        if (Integer.valueOf(versions[0]) > 2) {
            if (Integer.valueOf(versions[1]) > 2) {
                //Froyo or greater (mind you I just tested this on CM7 and the less than froyo one worked so it depends on the phone...)
                googleCalendar = new ComponentName("com.google.android.calendar", "com.android.calendar.LaunchActivity");               
            }

        } else {
            //less than Froyo
            googleCalendar = new ComponentName("com.android.calendar", "com.android.calendar.LaunchActivity");
        }

        launchCalendar.setComponent(googleCalendar);
        startActivity(launchCalendar);

    } else {
            Intent googleCalendarInstall = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.google.android.calendar"));
            startActivity(googleCalendarInstall);
        Toast.makeText(DatesActivity.this, "Please install the Google Calendar app in order to use the calendar functionality.", Toast.LENGTH_LONG).show();
    }
    finish();
}

private boolean appInstalledOrNot(String uri) {
    PackageManager pm = getPackageManager();
    boolean app_installed = false;
    try {
           pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
           app_installed = true;
    } catch (PackageManager.NameNotFoundException e) {
           app_installed = false;
    }
    return app_installed;
}
于 2013-04-07T11:43:56.383 回答