After download how to open downloaded file? - android

DownloadManager.Request request = new DownloadManager.Request(uri);
request.setDestinationInExternalPublicDir(Environment.
DIRECTORY_DOWNLOADS, nameOfFile)
To open it
File file = new File(Environment.
DIRECTORY_DOWNLOADS, nameOfFile);
MimeTypeMap map = MimeTypeMap.getSingleton();
String ext = MimeTypeMap.getFileExtensionFromUrl(file.getName());
String type = map.getMimeTypeFromExtension(ext);
But I am getting an error message that file cannot be accessed.Check the location

Try using read permission:
android.permission.READ_EXTERNAL_STORAGE

Here is a working solution. Note: Dont use DownloadManager.COLUMN_LOCAL_FILENAME as it is deprecated in API 24. Use DownloadManager.COLUMN_LOCAL_URI instead.
Create fields downlaod manager and a long variable to hold the download id.
DownloadManager dm;
long downloadId;
String pendingDownloadUrl = url;
fial int storagePermissionRequestCode = 101;
Create download manager
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
register the broadcast receiver for download complete
BroadcastReceiver downloadCompleteReceiver = new BroadcastReceiver() {
#Override
public void onReceive(final Context context, final Intent intent) {
Cursor c = dm.query(new DownloadManager.Query().setFilterById(downloadId));
if (c != null) {
c.moveToFirst();
try {
String fileUri = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
File mFile = new File(Uri.parse(fileUri).getPath());
String fileName = mFile.getAbsolutePath();
openFile(fileName);
}catch (Exception e){
Log.e("error", "Could not open the downloaded file");
}
}
}
};
//register boradcast for download complete
registerReceiver(downloadCompleteReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
Start the download
Start the download
private void onDownloadStart(String url) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
downloadFile(url);
} else {
pendingDownloadUrl = url;
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, storagePermissionRequestCode);
} }
//Download file using download manager
private void downlaodFile(String url){
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
String filename = URLUtil.guessFileName(url, null, null);
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,filename);
downloadId = dm.enqueue(request);//save download id for later reference }
//Permission status
#Override public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode == storagePermissionRequestCode){
boolean canDownload = true;
for (int grantResult : grantResults) {
if (grantResult == PackageManager.PERMISSION_DENIED) {
canDownload = false;
break;
}
}
if(canDownload){
downlaodFile(pendingDownloadUrl);
}
} }
Open the downloaded file
private void openFile(String file) {
try {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.fromFile(new File(file)), "application/pdf");//this is for pdf file. Use appropreate mime type
startActivity(i);
} catch (Exception e) {
Toast.makeText(this,"No pdf viewing application detected. File saved in download folder",Toast.LENGTH_SHORT).show();
}
}
Now try download your file by calling downladFile(String url); method

Try like this...
protected void openFile(String fileName) {
Intent install = new Intent(Intent.ACTION_VIEW);
install.setDataAndType(Uri.fromFile(new File(fileName)),
"MIME-TYPE");
startActivity(install);
}

Related

Download Manager cannot download APK

I'm trying to download an apk file from the server, but the manager writes waiting for a connection and then writes that the download failed. But this file can be downloaded via Chrome or Retrofit + InputStream. Also i tried to download jpg for test and all works
const val APK_NAME = "test-apk.apk"
val downloadRequest = DownloadManager
.Request(Uri.parse(remoteUpdateConf.newAppStoreUrl))
.setAllowedNetworkTypes(
DownloadManager.Request.NETWORK_WIFI
or DownloadManager.Request.NETWORK_MOBILE
)
.setAllowedOverRoaming(false)
.setTitle(getString(R.string.update_downloading))
.setNotificationVisibility(
DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED
)
.setShowRunningNotification(true)
.setVisibleInDownloadsUi(true)
.setMimeType("application/vnd.android.package-archive")
.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS,
APK_NAME
)
downloadManager.enqueue(downloadRequest)
Use this code for download apk using Download Manager:
step 1: Download Apk:
private void DownloadFile(String urlPath, String fileName) {
try {
String OutputDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
outputFile = new File(OutputDir, fileName);
if (outputFile.exists()) {
outputFile.delete();
}
OutputFullPATH = outputFile.toString();
// Download File from url
Uri uri = Uri.parse(urlPath + fileName);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setTitle("Application Name apk download");
request.setDescription("Downloading Application Name apk");
//Setting the location to which the file is to be downloaded
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
//request.setDestinationInExternalFilesDir(UserAuthenticationActivity.this, Environment.DIRECTORY_DOWNLOADS, fileName + System.currentTimeMillis());
DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
DownloadID = downloadManager.enqueue(request);
IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
registerReceiver(receiver, filter);
//return output;
} catch (Exception e) {
}
}
step 2: After Download if you want to check status
public int getDownloadedStatus() {
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(DownloadID);
DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
Cursor cursor = downloadManager.query(query);
if (cursor.moveToFirst()) {
int columnOndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
int status = cursor.getInt(columnOndex);
return status;
}
return DownloadManager.ERROR_UNKNOWN;
}
public void CancelDownload() {
DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
downloadManager.remove(DownloadID);
}
step 3: Notification for Install
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
try {
ShowProgressBar(false);
Long DownloadedID = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
if (DownloadedID == DownloadID) {
if (getDownloadedStatus() == DownloadManager.STATUS_SUCCESSFUL) {
Toast.makeText(context, "Download Completed", Toast.LENGTH_LONG).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Uri contentUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", new File(OutputFullPATH));
Intent openFileIntent = new Intent(Intent.ACTION_VIEW);
openFileIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
openFileIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
openFileIntent.setData(contentUri);
startActivity(openFileIntent);
unregisterReceiver(this);
finish();
} else {
Intent install = new Intent(Intent.ACTION_VIEW);
install.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
install.setDataAndType(Uri.parse(OutputFullPATH),
"application/vnd.android.package-archive");
startActivity(install);
unregisterReceiver(this);
finish();
}
} else {
Toast.makeText(context, "Download Not Completed", Toast.LENGTH_LONG).show();
}
}
} catch (Exception ex) {
CrashAnalytics.CrashReport(ex);
}
}
};

Upload image with android-upload-service

After some research I came across an open library for multipart file uploading. In my case I want to upload an Image using PUT request which the images are either choose from gallery or by camera. These are the resources I am using:
1. https://github.com/gotev/android-upload-service
2. https://www.simplifiedcoding.net/android-upload-image-to-server/#comment-9852
ProfileSetting.java
public class ProfileSetting extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private ImageView CustomerIcon;
private Button confirm_button;
//storage permission code
private static final int STORAGE_PERMISSION_CODE = 123;
//Bitmap to get image from gallery
private Bitmap bitmap;
//Uri to store the image uri
private Uri selectedImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_setting);
//Requesting storage permission
requestStoragePermission();
confirm_button.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View view) {
uploadMultipart();
//PUT VOLLEY
//saveProfileAccount();
}
});
}
private void showPickImageDialog() {
AlertDialog.Builder builderSingle = new AlertDialog.Builder(ProfileSetting.this);
builderSingle.setTitle("Set Image ");
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
ProfileSetting.this,
android.R.layout.select_dialog_singlechoice);
arrayAdapter.add("Gallery");
arrayAdapter.add("Camera");
builderSingle.setNegativeButton(
"cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builderSingle.setAdapter(
arrayAdapter,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto, 1);
break;
case 1:
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, 0);
break;
}
}
});
builderSingle.show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case 0:
if(resultCode == RESULT_OK){
selectedImage = imageReturnedIntent.getData();
//CustomerIcon.setImageURI(selectedImage);
try{
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImage);
CustomerIcon.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
break;
case 1:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
//CustomerIcon.setImageURI(selectedImage);
try{
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImage);
//bitmap = bitmap.createScaledBitmap(bitmap, 150, 150, true);
CustomerIcon.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
break;
}
}
/*
* This is the method responsible for image upload
* We need the full image path and the name for the image in this method
* */
public void uploadMultipart() {
//getting name for the image
String name = "customer_icon";
//getting the actual path of the image
String path = getPath(selectedImage);
//Uploading code
try {
String uploadId = UUID.randomUUID().toString();
//Creating a multi part request
new MultipartUploadRequest(this, uploadId, Constants.UPLOAD_URL)
.addFileToUpload(path, "image") //Adding file
.addParameter("name", name) //Adding text parameter to the request
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(2)
.startUpload(); //Starting the upload
} catch (Exception exc) {
Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
}
}
//method to get the file path from uri
public String getPath(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
String document_id = cursor.getString(0);
document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
cursor.close();
cursor = getContentResolver().query(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
cursor.moveToFirst();
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
return path;
}
//Requesting permission
private void requestStoragePermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
return;
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
//If the user has denied the permission previously your code will come to this block
//Here you can explain why you need this permission
//Explain here why you need this permission
}
//And finally ask for the permission
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
//This method will be called when the user will tap on allow or deny
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//Checking the request code of our request
if (requestCode == STORAGE_PERMISSION_CODE) {
//If permission is granted
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Displaying a toast
Toast.makeText(this, "Permission granted now you can read the storage", Toast.LENGTH_LONG).show();
} else {
//Displaying another toast if permission is not granted
Toast.makeText(this, "Oops you just denied the permission", Toast.LENGTH_LONG).show();
}
}
}
}
I am getting this error :
FATAL EXCEPTION: main
java.lang.NullPointerException: uri
Also I am not sure how to set headers for authorization in this method.
Please help, thank you!
String url = " http://server.yourserver.com/v1/example";
try {
String uploadId = UUID.randomUUID().toString();
//Creating a multi part request
MultipartUploadRequest request = new MultipartUploadRequest(this, uploadId, UPLOAD_URL);
request.addFileToUpload(images.getPath(), "image_url");
request.setNotificationConfig(new UploadNotificationConfig());
request.setMaxRetries(2);
request.startUpload(); //Starting the upload
} catch (Exception exc) {
Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
}
check following code.(I used okHttp library).
private int uploadFile(String imagePath) {
Log.i("PATH",imagePath);
OkHttpClient client = new OkHttpClient();
File fileSource = new File(imagePath);
if (fileSource.isFile()){
Log.i("EXIST","exist");
}else {
Log.i("NOT EXIST","not exist");
}
final MediaType MEDIA_TYPE;
String imageType;
if (imagePath.endsWith("png")){
MEDIA_TYPE = MediaType.parse("image/png");
imageType = ".png";
}else {
MEDIA_TYPE = MediaType.parse("image/jpeg");
imageType = ".jpg";
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",Locale.US).format(new Date());
String fileName = "Prathap_"+timeStamp+imageType;
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM) .addFormDataPart("file",fileName,RequestBody.create(MEDIA_TYPE,fileSource))
.build();
Request request = new Request.Builder()
.url(your url)//your webservice url
.post(requestBody)
.build();
try {
Response response = client.newCall(request).execute();
if (response.isSuccessful()){
Log.i("SUCC",""+response.message());
}
String resp = response.message();
Log.i("MSG",resp);
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
add the below line in build.gradle under app folder.
compile 'com.squareup.okhttp3:okhttp:3.5.0'
First in build.gradle add this:
implementation "net.gotev:uploadservice:4.7.0"
then in onCreate() add code as bellow:
UploadServiceConfig.initialize(this.getApplication(), "UploadJSON",true);
then make two functions as bellow:
public void uploadJSONFile(String filePath, String UPLOAD_URL){
try {
String uploadId = UUID.randomUUID().toString();
//Creating a multi part request
MultipartUploadRequest request = new MultipartUploadRequest(MainActivity.this, UPLOAD_URL);
request.setMethod("POST");
request.addParameter("par1","1");
request.addHeader("hed","val");
request.addFileToUpload(filePath, "image_url");
request.setNotificationConfig(createNotificationChannel());
//request.setMaxRetries(2);
request.startUpload(); //Starting the upload
} catch (Exception exc) {
Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
}
}
private Function2<? super Context, ? super String, UploadNotificationConfig> createNotificationChannel() {
Function2<? super Context, ? super String, UploadNotificationConfig> test = null;
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Toast.makeText(this, "Build.VERSION.SDK_INT : YES", Toast.LENGTH_SHORT).show();
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel("UploadJSON", name, importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
UploadNotificationStatusConfig uploadNotificationStatusConfig = new UploadNotificationStatusConfig("Upload JSON",
"uploading...");
UploadNotificationStatusConfig uploadNotificationStatusConfigSucces = new UploadNotificationStatusConfig("Upload JSON",
"finished!");
UploadNotificationStatusConfig uploadNotificationStatusConfigError = new UploadNotificationStatusConfig("Upload JSON",
"Error!");
UploadNotificationStatusConfig uploadNotificationStatusConfigCancele = new UploadNotificationStatusConfig("Upload JSON",
"Canceled");
uploadNotificationConfig = new UploadNotificationConfig("UploadJSON",
true,
uploadNotificationStatusConfig,uploadNotificationStatusConfigSucces,
uploadNotificationStatusConfigError,
uploadNotificationStatusConfigCancele
);
test = new Function2<Context, String, UploadNotificationConfig>() {
#Override
public UploadNotificationConfig invoke(Context context, String s) {
return uploadNotificationConfig;
}
};
}else{
}
return test;
}
now call uploadJSONFile().
you can use retrofit's Multipart.Body for image uploading to server. This link will guide you how to upload files using multipart.

open pdf after downloaded it

I use this code to download pdf
downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setTitle("story" + name);
request.setDescription("download " + name);
request.setDestinationInExternalFilesDir(R_arabic.this,"/Rewayat/", name+".pdf");
Long reference = downloadManager.enqueue(request);
it work good and pdf downloaded in app folder in android/data
and i use this code to open pdf
File file = new File ("/data/com.kamal.ahmed.rewaya/files/Rewayat/"+name+".pdf");
Intent target = new Intent (Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file),"application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent = Intent.createchosser(target, "Open File");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
}
but when i try to open it i don't get right pdf file and get error file
i think path not right please help me
To download the document to external storage
DownloadManager.Request r = new DownloadManager.Request(Uri.parse(document_url));
// This puts the downloaded document in the Download directory
r.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "my_document.pdf");
r.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(r);
Code to open
public void OpenPDF() {
try {
File file = new File(Environment.getExternalStorageDirectory()
+ "/Download/" + "my_document.pdf");
if (!file.isDirectory())
file.mkdir();
Intent pdfIntent = new Intent("com.adobe.reader");
pdfIntent.setType("application/pdf");
pdfIntent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
pdfIntent.setDataAndType(uri, "application/pdf");
startActivity(pdfIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
You need permission to write external storage, check how to get permission in new android version (you have to request permission through code, not only in the manifest)
To request permission from the user in order to write external storage, place these two methods in your main activity
public boolean isStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v("PERMISSIONS", "Permission is granted");
return true;
} else {
Log.v("PERMISSIONS","Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
Log.v("PERMISSIONS","Permission is granted");
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
Log.v("PERMISSIONS","Permission: "+permissions[0]+ "was "+grantResults[0]);
//resume tasks needing this permission
}
}
and inside onCreate, call the method
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ...
isStoragePermissionGranted();
Inside manifest.xml before <application> tag put these two permissions
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Why cannot I install an .apk after downloading it

I make an Android App, and i make a feature about update.
I download an .apk file and use intent to install it.But it always has an error like "there was a problem when parsing the package"
my code is
I use a receiver to listen the action when download complete ,code is
private BroadcastReceiver mBroadcaseReceiver;
protected void onCreate(#Nullable Bundle savedInstanceState) {
mCheckUpdateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("AboutUsActivity","check update");
downloadApk();
}
});
mBroadcaseReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)){
Log.d("aboutusactivity","下载完成");
//下载完毕后安装
installApk();
}
}
};
registerReceiver(mBroadcaseReceiver,new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
private void downloadApk() {
Log.d("AboutusActivity","update");
DownloadManager.Request request = new DownloadManager.Request(Uri.parse("XXXXXX"));
request.setDescription("updating");
request.setTitle("title");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "yuedong.apk");
// 获得下载服务和队列文件
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
private void installApk() {
Intent mIntent = new Intent(Intent.ACTION_VIEW);
mIntent.setDataAndType(Uri.fromFile(new File(Environment.DIRECTORY_DOWNLOADS,"yuedong.apk")),
"application/vnd.android.package-archive");
this.startActivity(mIntent);
}
But it always like
So what's wrong with my code?
The app file .apk, that you have downloaded might be corrupted. If you try to install the corrupted apps, you will get the parse error "There was a problem parsing the package". So, try again downloading the app completely and install it.
Its may be because that file having private mode protection(access permission).Try this link.
I know the reason now
because my path which download the apk is not match the path that i choose to install the apk. so stupid i am.
i change it like
private void downloadApk(String url) {
Log.d(TAG,"download");
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDescription("updating");
request.setTitle("My app");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
}
request.setDestinationInExternalPublicDir("/xxx/","update.apk");
// 获得下载服务和队列文件
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
private void installApk() {
File mFile;
mFile = new File(Environment.getExternalStorageDirectory()+"/xxx/update.apk");
if (mFile.exists()){
Intent mIntent = new Intent(Intent.ACTION_VIEW);
mIntent.setDataAndType(Uri.parse("file://"+mFile.getAbsolutePath()),
"application/vnd.android.package-archive");
startActivity(mIntent);
}else {
Log.d(TAG,"the file is not exist");
}
}

open file in another app from my apps file directory android

Hi i am downloading a file from URL to my files directory using download manager and then trying to open it with Action_View intent. When i run the Action_View it lets me select quick office and but says can't open file. but when i click on the file from the notification bar it opens fine. Does anyone know how to correctly open a file from an app? what i'm trying to achieve is download a file from url detect when it has finished downloading and allow the user to choose which app to open it in.
heres what i have tried so far
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setTitle(filename);
// in order for this if to run, you must use the android 3.2 to compile your app
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
ContextWrapper c = new ContextWrapper(getBaseContext());
final String filePath = c.getFilesDir().getPath() + "/";
Log.v("Search", "filePath = " + filePath);
request.setDestinationInExternalFilesDir(getBaseContext(), filePath, filename);
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
Toast.makeText(getBaseContext(), "Downloading...", Toast.LENGTH_LONG).show();
BroadcastReceiver onComplete = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
openFile(filename);
}
protected void openFile(String fileName) {
String path = getFilesDir().getPath() +"/" + fileName;
File f = new File(path);
String Extension = Global.getFileExt(fileName);
MimeTypeMap myMime = MimeTypeMap.getSingleton();
String mimeType = myMime.getMimeTypeFromExtension(Extension);
try {
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
File file = new File(path);
intent.setDataAndType(Uri.fromFile(file),mimeType);
startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
Toast.makeText(getBaseContext(), "No handler for this type of file.", 4000).show();
}
}
};
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
} else{
}
return false;
}else{
view.loadUrl(url);
return true;
}
}

Categories

Resources