Skip to content

Instantly share code, notes, and snippets.

@friedger
Created April 16, 2017 20:20
Show Gist options
  • Save friedger/a83d909b1374aea8278a87b3a0a8f79b to your computer and use it in GitHub Desktop.
Save friedger/a83d909b1374aea8278a87b3a0a8f79b to your computer and use it in GitHub Desktop.
Deep Link Redirect to browser
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.widget.Toast;
import com.example.R;
import java.util.ArrayList;
import java.util.List;
public class BrowserIntentFactory {
public static void startRedirectToBrowser(Activity activity, Uri uri) {
Intent intent = redirectDeepLinkToBrowserIntent(activity, uri);
if (intent != null) {
activity.startActivity(intent);
} else {
Toast.makeText(activity, R.string.no_suitable_apps_installed, Toast.LENGTH_SHORT).show();
}
}
public static Intent redirectDeepLinkToBrowserIntent(Context context, Uri uri) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://"));
List<Intent> targetIntents = targetIntentsForChooser(context, uri, intent);
if (targetIntents.size() > 0) {
if (targetIntents.size() > 1) {
Intent targetIntent = targetIntents.remove(0);
Intent chooserIntent = Intent.createChooser(targetIntent, null);
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
targetIntents.toArray(new Parcelable[targetIntents.size()]));
return chooserIntent;
} else {
return targetIntents.get(0);
}
} else {
return null;
}
}
@Nullable
private static List<Intent> targetIntentsForChooser(Context context, Uri uri, Intent queryIntent) {
PackageManager packageManager = context.getPackageManager();
List<ResolveInfo> resolveInfoList = packageManager.queryIntentActivities(queryIntent,
PackageManager.MATCH_DEFAULT_ONLY);
List<Intent> targetIntents = new ArrayList<>();
String appPackageName = context.getPackageName();
for (ResolveInfo info : resolveInfoList) {
String packageName = info.activityInfo.packageName;
if (!appPackageName.equals(packageName)) {
Intent targetIntent = new Intent(Intent.ACTION_VIEW);
targetIntent.setData(uri);
targetIntent.setPackage(packageName);
if (packageManager.resolveActivity(targetIntent, 0) != null) {
targetIntents.add(targetIntent);
}
}
}
return targetIntents;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment