I am getting this warning on resolveActivity line while using implicit intents and I am unable to open any website because of that.
btnWeb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String v = et.getText().toString();
Uri uri = Uri.parse(v);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
if (intent.resolveActivity(getPackageManager())!=null){
startActivity(intent);
}
}
});
Get rid of resolveActivity(). Just call startActivity(), but do so in a try/catch, so you can catch the ActivityNotFoundException if there is no Web browser available.
I use this codes to send user to another applications. I wan't the user get send to playstore if the application not exist on he's phone. I was searching for examples but i didn't find anything.
// Launch My App one after clicking the button1
public void launchAppOne(View view) {
Intent launchAppOne= getPackageManager().getLaunchIntentForPackage("com.app.android.myapp1");
startActivity(launchAppOne);
}
// Launch My A after clicking the button2
public void launchAppTwo(View view) {
Intent launchAppTwo = getPackageManager().getLaunchIntentForPackage("com.app.android.myapp2");
startActivity(launchAppTwo);
}
You can use this code. It tries to launch the app and if it doesn't exist, the playstore page for the app is opened.
String packageName = "org.mozilla.firefox";
Intent intent= getPackageManager().getLaunchIntentForPackage(packageName);
if (intent != null){
startActivity(intent);
}else{
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + packageName)));
}catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + packageName)));
}
}
In my app I am trying to provide two functions to the users. One is uploading a post with an image and the other is to upload post without an image. To do so I created Strings nonselected_image and selected_image (or selected_bitmap). In case of pressing one of the TextViews by user one of the strings will be passed within the intent consequently. It works great when user wishes to create non photo post but when he wants to create one with a photo there are two posts emerging, one with photo and the other without. What did I wrong? Here is my code.
Sending an intent and strings to the next activity
TextView nextScreen = (TextView) view.findViewById(R.id.tvNext);
nextScreen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating to the final share screen.");
if (isRootTask()) {
Intent intent = new Intent(getActivity(), NextActivity.class);
intent.putExtra(getString(R.string.selected_image), mSelectedImage);
startActivity(intent);
} else {
Intent intent = new Intent(getActivity(), AccountSettingsActivity.class);
intent.putExtra(getString(R.string.selected_image), mSelectedImage);
intent.putExtra(getString(R.string.return_to_fragment), getString(R.string.edit_profile_fragment));
startActivity(intent);
getActivity().finish();
}
}
});
noPhoto.setOnClickListener(new View.OnClickListener(){
public void onClick (View v) {
mSelectedImage = null;
Intent intent = new Intent(getActivity(), NextActivity.class);
intent.putExtra(getString(R.string.nonselected_image), nonSelectedImage);
startActivity(intent);
}
});
receiving an intent and taking actions accordingly to passed variable
public void onClick(View v) {
Log.d(TAG, "onClick: navigating to the final share screen.");
//upload the image to firebase
// Toast.makeText(NextActivity.this, "Attempting to upload new photo", Toast.LENGTH_SHORT).show();
String caption = mCaption.getText().toString();
if(intent.hasExtra(getString(R.string.selected_image))){
imgUrl = intent.getStringExtra(getString(R.string.selected_image));
Toast.makeText(NextActivity.this, "Attempting to upload a normal photo", Toast.LENGTH_SHORT).show();
mFirebaseMethods.uploadNewPhoto(getString(R.string.new_photo), caption, imageCount, imgUrl,null);
}
else if(intent.hasExtra(getString(R.string.selected_bitmap))){
bitmap = (Bitmap) intent.getParcelableExtra(getString(R.string.selected_bitmap));
Toast.makeText(NextActivity.this, "Attempting to upload a new bitmap", Toast.LENGTH_SHORT).show();
mFirebaseMethods.uploadNewPhoto(getString(R.string.new_photo), caption, imageCount, null,bitmap);
}
else if(intent.hasExtra(getString(R.string.nonselected_image)));{
Toast.makeText(NextActivity.this, "Attempting to upload new photo", Toast.LENGTH_SHORT).show();
imgUrl = intent.getStringExtra(getString(R.string.nonselected_image));
mFirebaseMethods.uploadNoPhoto(getString(R.string.new_photo), caption, imageCount, imgUrl, null); // HERE IS THE ERROR
}
I'm following share a text with button in custom listview but it doesn't work .
this is code for OnClick in ListViewAdapter.java :
OnClickListener clickListener = new OnClickListener() {
#Override
public void onClick(View v) {
try{
Context context = v.getContext();
String ab = (String) holder.tvComment.getText();
holder.tvComment.setText(ab);
Toast.makeText(context, ab, Toast.LENGTH_LONG).show();
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, ab);
sendIntent.setType("text/plain");
context.startActivity(sendIntent);
}
catch (Exception e){
Log.w("Share Data", "Error!");
}
}
};
holder.sharebtn.setOnClickListener(clickListener);
Try this way,hope this will help you to solve your problem.
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_TEXT,message);
try {
context.startActivity(Intent.createChooser(i, "Share"));
} catch (android.content.ActivityNotFoundException ex) {
ex.printStackTrace();
}
try starting your Activity this way
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
Calling Intent.createChooser() ,passing it your Intent object, it
returns a version of your intent that will always display the chooser.
This has some advantages:
Even if the user has previously selected a default action for this
intent, the chooser will still be displayed. If no applications match,
Android displays a system message. You can specify a title for the
chooser dialog.
I want to launch an installed package from my Android application. I assume that it is possible using intents, but I didn't find a way of doing it. Is there a link, where to find the information?
If you don't know the main activity, then the package name can be used to launch the application.
Intent launchIntent = getPackageManager().getLaunchIntentForPackage("com.package.address");
if (launchIntent != null) {
startActivity(launchIntent);//null pointer check in case package name was not found
}
I know this has been answered but here is how I implemented something similar:
Intent intent = getPackageManager().getLaunchIntentForPackage("com.package.name");
if (intent != null) {
// We found the activity now start the activity
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} else {
// Bring user to the market or let them choose an app?
intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setData(Uri.parse("market://details?id=" + "com.package.name"));
startActivity(intent);
}
Even better, here is the method:
public void startNewActivity(Context context, String packageName) {
Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
if (intent != null) {
// We found the activity now start the activity
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
} else {
// Bring user to the market or let them choose an app?
intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setData(Uri.parse("market://details?id=" + packageName));
context.startActivity(intent);
}
}
Removed duplicate code:
public void startNewActivity(Context context, String packageName) {
Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
if (intent == null) {
// Bring user to the market or let them choose an app?
intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://details?id=" + packageName));
}
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
I found the solution. In the manifest file of the application I found the package name: com.package.address and the name of the main activity which I want to launch: MainActivity
The following code starts this application:
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setComponent(new ComponentName("com.package.address","com.package.address.MainActivity"));
startActivity(intent);
// in onCreate method
String appName = "Gmail";
String packageName = "com.google.android.gm";
openApp(context, appName, packageName);
public static void openApp(Context context, String appName, String packageName) {
if (isAppInstalled(context, packageName))
if (isAppEnabled(context, packageName))
context.startActivity(context.getPackageManager().getLaunchIntentForPackage(packageName));
else Toast.makeText(context, appName + " app is not enabled.", Toast.LENGTH_SHORT).show();
else Toast.makeText(context, appName + " app is not installed.", Toast.LENGTH_SHORT).show();
}
private static boolean isAppInstalled(Context context, String packageName) {
PackageManager pm = context.getPackageManager();
try {
pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
return true;
} catch (PackageManager.NameNotFoundException ignored) {
}
return false;
}
private static boolean isAppEnabled(Context context, String packageName) {
boolean appStatus = false;
try {
ApplicationInfo ai = context.getPackageManager().getApplicationInfo(packageName, 0);
if (ai != null) {
appStatus = ai.enabled;
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return appStatus;
}
Edit depending on comment
In some versions - as suggested in comments - the exception thrown may be different.
Thus the solution below is slightly modified
Intent launchIntent = null;
try{
launchIntent = getPackageManager().getLaunchIntentForPackage("applicationId");
} catch (Exception ignored) {}
if(launchIntent == null){
startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://play.google.com/store/apps/details?id=" + "applicationId")));
} else {
startActivity(launchIntent);
}
Original Answer
Although answered well, there is a pretty simple implementation that handles if the app is not installed. I do it like this
try{
startActivity(getPackageManager().getLaunchIntentForPackage("applicationId"));
} catch (PackageManager.NameNotFoundException e) {
startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://play.google.com/store/apps/details?id=" + "applicationId")));
}
Replace "applicationId" with the package that you want to open such as com.google.maps, etc.
Here is my example of launching bar/QR code scanner from my app if someone finds it useful
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.setPackage("com.google.zxing.client.android");
try
{
startActivityForResult(intent, SCAN_REQUEST_CODE);
}
catch (ActivityNotFoundException e)
{
//implement prompt dialog asking user to download the package
AlertDialog.Builder downloadDialog = new AlertDialog.Builder(this);
downloadDialog.setTitle(stringTitle);
downloadDialog.setMessage(stringMessage);
downloadDialog.setPositiveButton("yes",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialogInterface, int i)
{
Uri uri = Uri.parse("market://search?q=pname:com.google.zxing.client.android");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
try
{
myActivity.this.startActivity(intent);
}
catch (ActivityNotFoundException e)
{
Dialogs.this.showAlert("ERROR", "Google Play Market not found!");
}
}
});
downloadDialog.setNegativeButton("no",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int i)
{
dialog.dismiss();
}
});
downloadDialog.show();
}
If you want to open specific activity of another application we can use this.
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
final ComponentName cn = new ComponentName("com.android.settings", "com.android.settings.fuelgauge.PowerUsageSummary");
intent.setComponent(cn);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try
{
startActivity(intent)
}catch(ActivityNotFoundException e){
Toast.makeText(context,"Activity Not Found",Toast.LENGTH_SHORT).show()
}
If you must need other application, instead of showing Toast you can show a dialog. Using dialog you can bring the user to Play-Store to download required application.
Check for the app, avoiding any crashes. If the app exists in the phone then it will be launched, otherwise it will search in Google Play. If no Google Play app installed in the phone, it will search in the Google Play Store via browser:
public void onLunchAnotherApp() {
final String appPackageName = getApplicationContext().getPackageName();
Intent intent = getPackageManager().getLaunchIntentForPackage(appPackageName);
if (intent != null) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} else {
onGoToAnotherInAppStore(intent, appPackageName);
}
}
public void onGoToAnotherInAppStore(Intent intent, String appPackageName) {
try {
intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setData(Uri.parse("market://details?id=" + appPackageName));
startActivity(intent);
} catch (android.content.ActivityNotFoundException anfe) {
intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setData(Uri.parse("http://play.google.com/store/apps/details?id=" + appPackageName));
startActivity(intent);
}
}
Starting from API 30 (Android 11) you can receive nullpointerexception with launchIntentForPackage
val launchIntent: Intent? = activity.packageManager.getLaunchIntentForPackage("com.google.android.gm")
startActivity(launchIntent)
To avoid this you need to add the needed package to the manifest
<queries>
<package android:name="com.google.android.gm" />
</queries>
Here is documentation
https://developer.android.com/training/package-visibility
And the medium article
https://medium.com/androiddevelopers/package-visibility-in-android-11-cc857f221cd9
It is possible to start an app's activity by using Intent.setClassName according to the docs.
An example:
val activityName = "com.google.android.apps.muzei.MuzeiActivity" // target activity name
val packageName = "net.nurik.roman.muzei" // target package's name
val intent = Intent().setClassName(packageName, activityName)
startActivity(intent)
To open it outside the current app, add this flag before starting the intent.
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
A related answer here
If you know the data and the action the installed package react on, you simply should add these information to your intent instance before starting it.
If you have access to the AndroidManifest of the other app, you can see all needed information there.
Steps to launch new activity as follows:
1.Get intent for package
2.If intent is null redirect user to playstore
3.If intent is not null open activity
public void launchNewActivity(Context context, String packageName) {
Intent intent = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.CUPCAKE) {
intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
}
if (intent == null) {
try {
intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setData(Uri.parse("market://details?id=" + packageName));
context.startActivity(intent);
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + packageName)));
}
} else {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
private fun openOtherApp() {
val sendIntent = packageManager.getLaunchIntentForPackage("org.mab.dhyanaqrscanner")
startActivity(sendIntent)
finishAffinity()
}
This will cover all scenarios
1.Get intent for package
2.If intent is null redirect user to playstore
3.If there is an issue with open playstore, then it opens on the default browser.
var intent = activity!!.packageManager.getLaunchIntentForPackage("com.google.android.youtube")
if (intent == null) {
if (intent == null) {
intent = try {
Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.google.android.youtube"))
} catch (e: Exception) {
Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com.google.android.youtube"))
}
}
startActivity(intent)
For Android 11 (API level 30) or higher, in AndroidManifest.xml,
<queries>
<package android:name="com.google.android.youtube" />
<package android:name="com.example.app" />
</queries>
Or simply we can allow for all packages (not recommended)
<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" tools:ignore="QueryAllPackagesPermission" />
References
Package visibility filtering on Android
Declaring package visibility needs
Try code below:
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setComponent(new ComponentName("package_name", "Class_name"));
if (intent.resolveActivity(getPackageManager()) != null)
{
startActivity(intent);
}
In Kotlin
fun openApplicationOrMarket(packageName: String) {
var intent = requireContext().packageManager.getLaunchIntentForPackage(packageName)
if (intent == null) {
intent = Intent(Intent.ACTION_VIEW)
intent.data = Uri.parse("market://details?id=$packageName")
}
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
requireContext().startActivity(intent)
}
Pass the package name and the message you want to show if package isn't installed ;-)
void openApp(String appPackageName,String message){
Intent launchIntent = getPackageManager().getLaunchIntentForPackage(appPackageName);
if (launchIntent != null) {
startActivity(launchIntent);
} else {
Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
}
}
Since kotlin is becoming very popular these days, I think it's appropriate to provide a simple solution in Kotlin as well.
var launchIntent: Intent? = null
try {
launchIntent = packageManager.getLaunchIntentForPackage("applicationId")
} catch (ignored: Exception) {
}
if (launchIntent == null) {
startActivity(Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://play.google.com/store/apps/details?id=" + "applicationId")))
} else {
startActivity(launchIntent)
}