Java tutorial
//package com.java2s; /* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.os.Build; import android.text.TextUtils; import java.util.List; public class Main { /** * Start an intent normally. Assert that the intent can't be opened inside this app. */ public static void startActivityOutsideApp(Context context, Intent intent) { final boolean isPlatformDebugBuild = Build.TYPE.equals("eng") || Build.TYPE.equals("userdebug"); if (isPlatformDebugBuild) { if (getIntentInAppIfExists(context, intent) != null) { throw new AssertionError("startActivityOutsideApp() was called for an intent" + " that can be handled inside the app"); } } context.startActivity(intent); } /** * Returns a copy of {@param intent} with a class name set, if a class inside this app * has a corresponding intent filter. */ private static Intent getIntentInAppIfExists(Context context, Intent intent) { try { final Intent intentCopy = new Intent(intent); // Force this intentCopy to open inside the current app. intentCopy.setPackage(context.getPackageName()); final List<ResolveInfo> list = context.getPackageManager().queryIntentActivities(intentCopy, PackageManager.MATCH_DEFAULT_ONLY); if (list != null && list.size() != 0) { // Now that we know the intentCopy will work inside the current app, we // can return this intent non-null. if (list.get(0).activityInfo != null && !TextUtils.isEmpty(list.get(0).activityInfo.name)) { // Now that we know the class name, we may as well attach it to intentCopy // to prevent the package manager from needing to find it again inside // startActivity(). This is only needed for efficiency. intentCopy.setClassName(context.getPackageName(), list.get(0).activityInfo.name); } return intentCopy; } return null; } catch (Exception e) { // Don't let the package manager crash our app. If the package manager can't resolve the // intent here, then we can still call startActivity without calling setClass() first. return null; } } }