How can I install Android PlayStore application from another application programmatically? - java

I am new to creating android application and I am working on project where I need to download and install application from Android Playstore and install without user input. The only solution i could find is to launch market app and then click install button manually. But I want to install automatically. Is there any better way?

Installation of apps without user input isn't possible, but you can ask user to install it by following intent:
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(GOOGLE_PLAY_APP_URL));
startActivity(intent);
And for check if app is already installed you can use something like this:
public static boolean isInstalled(Context context, String packageName) {
PackageManager pkgManager = context.getPackageManager();
Intent launchIntent = new Intent(Intent.ACTION_MAIN);
launchIntent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> resInfo = pkgManager.queryIntentActivities(launchIntent, 0);
for (int i = 0; i < resInfo.size(); i++) {
ResolveInfo ri = resInfo.get(i);
String pkgName = ri.activityInfo.packageName;
if (pkgName.contains(packageName)) {
return true;
}
}
return false;
}

Related

Instagram application does not open with Android Intent

This is my code, the thing is I don't want to send images I just want the IG app to open. Yes the app is installed but still it is not getting picked up.
This was working fine till last week. Please help.
Uri uri = Uri.parse("http://instagram.com/");
Intent insta = new Intent(Intent.ACTION_VIEW, uri);
insta.setPackage("com.instagram.android");
if (isIntentAvailable(insta)) {
this.startActivityForResult(insta, REQUEST_CODE_MY_PICK);
} else {
}
private boolean isIntentAvailable(Intent intent) {
final PackageManager packageManager = getPackageManager();
List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
Try this
Uri appUri = Uri.parse("https://instagram.com/_u/user_name");
Uri browserUri = Uri.parse("https://instagram.com/user_name");
try{ //first try to open in instagram app
Intent appIntent = getPackageManager().getLaunchIntentForPackage("com.instagram.android");
if(appIntent != null){
appIntent.setAction(Intent.ACTION_VIEW)
appIntent.setData(appUri);
startActivity(appIntent);
}
}catch(Exception e){ //or else open in browser
Intent browserIntent = new Intent(Intent.ACTION_VIEW, browserUri);
startActivity(browserIntent);
}
Try to replace Uri.parse("http://instagram.com/") with Uri.parse("https://instagram.com/"). Also try to remove the isIntentAvailable and just call startActivity(insta) without 'forResult' and lastly remove insta.setPackage line.

Permission Denial: opening provider android.support.v4.content.FileProvider

I was having some problem when trying to perform an application upgrade in Android emulator. The flow of the scenario is from an Activity, I will execute AsyncTask A which open up fragment A, then inside AsyncTask A, I will check if version upgrade is available.
If available and user selected "Okay" from fragment A, I will proceed to AsyncTask B to open up fragment B which show a message to user saying that upgrading is in process. In AsyncTask B doInBackground(), I will execute the install() and in onPostExecute(), I will show successful message.
In my AsyncTask B where I execute the install:
#Override
protected Boolean doInBackground(Void... params) {
boolean ret= viewmodel.installApk(mActivity);
return ret;
}
In my view model class:
public boolean installApk(Activity mActivity){
boolean success = false;
String fullPath = scanDirectoryForApk();
System.out.println("INSTALLING APK ......................... ");
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri apkURI = FileProvider.getUriForFile(mActivity, mActivity.getApplicationContext().getPackageName() + ".provider", new File(fullPath));
intent.setDataAndType(apkURI, "application/vnd.android.package-archive");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mActivity.startActivity(intent);
return true;
}
However, when I execute the code above, no error message was shown and the version upgrade is not working as well. It basically just restart the intent and there is no upgrade at all.
It does not prompt me for the permission to install new version as well. Any ideas?
By the way, my android emulator is not rooted and therefore I could not use the "su" command approach.
Thanks!
EDIT
As suggestion by #Sagar, I changed my code above to:
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri apkURI = FileProvider.getUriForFile(mActivity, mActivity.getApplicationContext().getPackageName() + ".provider", new File(fullPath));
List<ResolveInfo> resInfoList = mActivity.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
mActivity.grantUriPermission(packageName, apkURI, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
intent.setDataAndType(apkURI, "application/vnd.android.package-archive");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mActivity.startActivity(intent);
And I am getting new error message from logcat:
Error staging apk from content URI
java.lang.SecurityException: Permission Denial: opening provider android.support.v4.content.FileProvider from ProcessRecord{3883c8 9647:com.google.android.packageinstaller/u0a20} (pid=9647, uid=10020) that is not exported from UID 10085
The intent error message is telling me "There was a problem parsing package".
You can try to merge
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
into
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NEW_TASK);
I met the same issue as you, and this solution rescued myself.

Android how to get name of app used to share

I'm using the following method to share an image with any app the user picks.
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/*");
File imageFileToShare = new File(imagePath);
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(imageFileToShare));
if (!TextUtils.isEmpty(text)) {
shareIntent.putExtra(Intent.EXTRA_TEXT, text);
}
context.startActivity(Intent.createChooser(shareIntent, "Share with").addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
This works fine, but now I'm trying to get the name of the app picked by the user for sharing. Is there a (standard) way to do this?
Thanks for the attention.
Jose
This is not supported prior to Android 6.0, when using the Android chooser. On Android 6.0+, you can use EXTRA_CHOOSER_REFINEMENT_INTENT_SENDER to provide an IntentSender that will be notified when the user makes a choice and what that choice is.
You are welcome to use PackageManager and queryIntentActivities() to find out what activities support your shareIntent and create your own UI for the user to choose from. Then, since it is your own UI, you will find out what the user chose.
You can try with this code:
PackageManager packageManager = getPackageManager();
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/*");
getNameFromApp(packageManager);
And
public String getNameFromApp(PackageManager packageManager) {
List<ResolveInfo> resolveInfos = packageManager.queryIntentActivities(shareIntent, 0);
int lastDot = 0;
String name = "";
for (int i = 0; i < resolveInfos.size(); i++) {
// Extract the label, append it, and repackage it in a LabeledIntent
ResolveInfo resolveInfo = resolveInfos.get(i);
String packageName = resolveInfo.activityInfo.packageName;
lastDot= packageName.lastIndexOf(".");
name = packageName.substring(lastDot + 1);
}
return name;
}
This code gets last app's name. But You can do it however you want to. Just do it!.

How can I make an apk auto install when download completes

Hi guys was wondering if there was a bit of code I could use that would make an app auto install once the download completes?
My app has a download section with in it. I was using Google Drive to handle the downloads. but I am encountering issues with some devices. So I have decided to move away from google
I am now using media fire as my host. My app uses direct download. But it always downloads using the download manager. What I would like it to do is more like how Google Drive works with direct download. Which is it gives me the option to install as soon as download completes.which i have now solved with these few lines of code
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new
File(Environment.getExternalStorageDirectory() + "/download/" + "app.apk")),
"application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
is there a way to check download folder before downloading the file. if the file is already there install if not got to web page for download. rather it saying parse error then going to webpage or having multiple downloads of same file.
Thanks in advance as always.
You can get the downloaded Uri after the download complete, so you don't have to specify a file name to save. If you use DownloadManager, below is a simple example.
final DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse("http://remotehost/your.apk"));
final long id = downloadManager.enqueue(request);
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
Intent installIntent = new Intent(Intent.ACTION_VIEW);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
installIntent.setDataAndType(downloadManager.getUriForDownloadedFile(id),
"application/vnd.android.package-archive");
} else {
Cursor cursor = downloadManager.query(new DownloadManager.Query().setFilterById(id));
try {
if (cursor != null && cursor.moveToFirst()) {
int status = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS));
String localUri = cursor.getString(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_LOCAL_URI));
if (status == DownloadManager.STATUS_SUCCESSFUL) {
installIntent.setDataAndType(Uri.parse(localUri), "application/vnd.android.package-archive");
}
}
} finally {
if (cursor != null) {
cursor.close();
}
}
}
installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.sendBroadcast(installIntent);
}
}
};
registerReceiver(broadcastReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

Sharing text with image to instagram using android intent

I know that this question has been asked several times before, I am trying to add caption to image shared to instagram using send intent
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/*");
shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shareIntent.putExtra(Intent.EXTRA_STREAM,uri);
shareIntent.putExtra(Intent.EXTRA_TEXT,"YOUR TEXT TO SHARE IN INSTAGRAM");
shareIntent.setPackage("com.instagram.android");
return shareIntent;
Has someone ever managed to make it work?
Is it not supported or has the support been revoked?
There was an official statement from Instagram (mid-2015) announcing that pre-populated captions would no longer be accepted in the iOS and Android apps:
Beginning today, the iOS Hooks and Android Intents will stop accepting captions passed by third party apps. This is a non-breaking change: existing mobile apps that utilize pre-filled captions will continue to be able to use this flow to share media through the Instagram apps, but now Instagram will ignore the caption text. To create a caption for a photo or video shared by a third party app, users will have to enter a caption manually, the same way they already do when sharing content using the Instagram native apps.
Looking at the Instagram documentation for Android, indeed we see that there's no mention of providing the conventional Intent.EXTRA_TEXT string extra in the intent as is customary for other apps. Their sample is limited to only providing a Uri:
// Add the URI to the Intent.
share.putExtra(Intent.EXTRA_STREAM, uri);
// Broadcast the Intent.
startActivity(Intent.createChooser(share, "Share to"));
I'm sorry to say that it simply isn't possible, and we're at the discretion of Facebook in making this decision.
Until it`s not solved by Instagram, I copy the text to the clipboard and instruct the user to paste it
#Override
public void onSingleImageSelected(Uri uri, String tag) {
fileProfileImage = uri.getPath();
compressProfileImage();
imgShareTosocial.setVisibility(View.VISIBLE);
Glide.with(getApplicationContext()).load(uri).into(imgShareTosocial);
}
#SuppressLint("CheckResult")
private void compressProfileImage() {
File file = new File(fileProfileImage);
new Compressor(this)
.compressToFileAsFlowable(file)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<File>() {
#Override
public void accept(File file) throws Exception {
compressProfileImage = file;
String imagePath = compressProfileImage.getAbsolutePath();
tvSelectMedia.setText(imagePath);
}
}, new Consumer<Throwable>() {
#Override
public void accept(Throwable throwable) throws Exception {
throwable.printStackTrace();
}
});
}
private void shareToInstagram() {
path = tvSelectMedia.getText().toString().trim();
Intent intent = getPackageManager().getLaunchIntentForPackage("com.instagram.android");
if (intent != null) {
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setPackage("com.instagram.android");
try {
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), path, "Step Up", "Step Up")));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
shareIntent.setType("image/jpeg");
startActivity(shareIntent);
} else {
// bring user to the market to download the app.
// 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.instagram.android"));
startActivity(intent);
}
}
I'm with the same problem. I think is not possible at this time.
In https://instagram.com/developer/mobile-sharing/android-intents/ only talk about Intent.EXTRA_STREAM, so i suppose that it's the only available.
Here is my code:
Intent instagramIntent = new Intent(Intent.ACTION_SEND);
instagramIntent.setType("image/*");
File media = new File(mediaPath);
Uri uri = Uri.fromFile(media);
instagramIntent.putExtra(Intent.EXTRA_STREAM, uri);
instagramIntent.setPackage("com.instagram.android");
PackageManager packManager = getPackageManager();
List<ResolveInfo> resolvedInfoList = packManager.queryIntentActivities(instagramIntent, PackageManager.MATCH_DEFAULT_ONLY);
boolean resolved = false;
for(ResolveInfo resolveInfo: resolvedInfoList){
if(resolveInfo.activityInfo.packageName.startsWith("com.instagram.android")){
instagramIntent.setClassName(
resolveInfo.activityInfo.packageName,
resolveInfo.activityInfo.name );
resolved = true;
break;
}
}
if(resolved){
startActivity(instagramIntent);
}else{
Toast.makeText(PromocionarMain.this, "Instagram App is not installed", Toast.LENGTH_LONG).show();
}
Instagram have stopped accepting pre-populated capitions to increase the quality of content in the system. See this post.
http://developers.instagram.com/post/125972775561/removing-pre-filled-captions-from-mobile-sharing

Categories