Эй, ребята, я делаю это простое приложение, чтобы получить apk, которые хранятся на сервере для клиентов. Я получил загруженный файл и хочу открыть его для установки.
, поэтому первая проблема заключается в том, что он загружает его дважды? во-вторых, я получаю сообщение об ошибке при анализе приложения, когда оно открывается? но если я открываю файл с телефона, оно работает ..
Первая загрузка с моего адаптера:
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
.mkdirs();
DownloadManager manager = (DownloadManager) context.getSystemService (Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request (Uri.parse (appUrlString));
request.setAllowedNetworkTypes (DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
request.setDescription ("Downloading");
request.setTitle (appName);
request.allowScanningByMediaScanner ();
request.setNotificationVisibility (
DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir (Environment.DIRECTORY_DOWNLOADS, appName+".apk");
manager.enqueue (request);
mCallback.onClick (String.valueOf (manager.enqueue (request)),appName);
}
});
Открытие файла из моя основная активность:
private BroadcastReceiver onDownloadComplete = new BroadcastReceiver () {
@Override
public void onReceive(Context context, Intent intent) {
//Fetching the download id received with the broadcast
long id = intent.getLongExtra (DownloadManager.EXTRA_DOWNLOAD_ID, -1);
spinner.setVisibility (View.GONE);
Toast.makeText (context, "Download Completed", Toast.LENGTH_SHORT).show ();
Log.d ("INTENT ", String.valueOf (id) + "DID " + downloadID);
openDownloadedAttachment(context, id);
}
};
@Override
public void onClick(String value, String fileName) {
spinner.setVisibility (View.VISIBLE);
Log.d ("INTENT REC", value + " " + fileName);
fileNameDownloaded = fileName;
downloadID = value;
}
private void openDownloadedAttachment(final Context context, final long downloadId) {
DownloadManager downloadManager = (DownloadManager) context.getSystemService (Context.DOWNLOAD_SERVICE);
DownloadManager.Query query = new DownloadManager.Query ();
query.setFilterById (downloadId);
Cursor cursor = downloadManager.query (query);
if (cursor.moveToFirst ()) {
int downloadStatus = cursor.getInt (cursor.getColumnIndex (DownloadManager.COLUMN_STATUS));
String downloadLocalUri = cursor.getString (cursor.getColumnIndex (DownloadManager.COLUMN_LOCAL_URI));
String downloadMimeType = cursor.getString (cursor.getColumnIndex (DownloadManager.COLUMN_MEDIA_TYPE));
if ((downloadStatus == DownloadManager.STATUS_SUCCESSFUL) && downloadLocalUri != null) {
openDownloadedAttachment (context, Uri.parse (downloadLocalUri), downloadMimeType);
}
}
cursor.close ();
}
private void openDownloadedAttachment(final Context context, Uri attachmentUri, final String attachmentMimeType) {
if (attachmentUri != null) {
// Get Content Uri.
if (ContentResolver.SCHEME_FILE.equals (attachmentUri.getScheme ())) {
// FileUri - Convert it to contentUri.
File file = new File (attachmentUri.getPath ());
attachmentUri = FileProvider.getUriForFile (MainActivity.this, "com.handshake.downloadmanager.provider", file);
System.out.println ("Opening: " + attachmentUri);
}
Intent openAttachmentIntent = new Intent (Intent.ACTION_VIEW);
openAttachmentIntent.setDataAndType (attachmentUri, attachmentMimeType);
openAttachmentIntent.setFlags (Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
context.startActivity (openAttachmentIntent);
System.out.println ("Opening attachement: " + openAttachmentIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText (context, context.getString (R.string.unable_to_open_file), Toast.LENGTH_LONG).show ();
}
}
}
У меня есть интерфейс, который сообщает моей mainActivity, какой идентификатор загрузки и когда она завершена.
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path
name="external_files"
path="." />
</paths>
provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provide_paths" />
</provider>
Так почему же скачать 2 раза? и сообщение об ошибке при попытке открыть его?
РЕДАКТИРОВАТЬ: я решить одну проблему с сообщением об ошибке для ошибки пакета. Мне нужно открыть настройки приложения для всех приложений, чтобы установить
private void askSettings(){
Intent intent = new Intent ();
intent.setAction (Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
Uri uri = Uri.fromParts ("package", this.getPackageName (), null);
intent.setData (uri);
this.startActivity (intent);
}
, но загрузка 2 раза - это моя головная боль lol