老师,我添加了动态获取权限以后,下载的进度条能动,但是SD卡里面却看不到最后下载好的文件
1、manifest中加入了权限:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
2、剩下的java代码是这样的,没有任何报错
package com.xinshuiji.handlerproject; import android.Manifest; import android.app.Activity; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.provider.Settings; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.content.ContextCompat; import android.support.v7.app.AlertDialog; import android.util.Log; import android.view.View; import android.widget.ProgressBar; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; public class DownloadActivity extends FragmentActivity { private static final String TAG = "DownloadActivity"; public static final int DOWNLOAD_MESSAGE_CODE = 100001; private static final int DOWNLOAD_MESSAGE_FAIL_CODE = 100002; public static final String APP_URL = "http://download.sj.qq.com/upload/connAssitantDownload/upload/MobileAssistant_1.apk"; public static final int MY_REQUEST_CODE = 666; private Handler handler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_download); final ProgressBar progressBar = findViewById(R.id.progressBar); findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 点击后先检查权限,使用boolean值标记是否有权限 Boolean aBoolean = isAllPermissionGrant(new String[]{ Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE }); if (aBoolean) { new Thread(new Runnable() { @Override public void run() { download(APP_URL); } }).start(); return; } // 到此处时表明没有权限,这需要申请权限 ActivityCompat.requestPermissions( DownloadActivity.this, new String[]{ Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE }, MY_REQUEST_CODE ); } }); handler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what){ case DOWNLOAD_MESSAGE_CODE: progressBar.setProgress((Integer) msg.obj); break; case DOWNLOAD_MESSAGE_FAIL_CODE: Log.i(TAG, "handleMessage: fail"); break; } } }; } /** * 检查是否有权限的方法 * @param permissions 是需要检测权限的权限数组 * @return 返回是否有全部权限 */ private Boolean isAllPermissionGrant(String[] permissions){ for (String permission:permissions) { if (ContextCompat.checkSelfPermission(DownloadActivity.this, permission) != PackageManager.PERMISSION_GRANTED) { return false; } } return true; } private void download(String appUrl) { try { URL url = new URL(appUrl); URLConnection urlConnection = url.openConnection(); InputStream inputStream = urlConnection.getInputStream(); /* * 获取文件的总长度 * */ int contentLength = urlConnection.getContentLength(); // 放在SD卡的下面的imooc这个目录下面 String downloadFolderName = Environment.getExternalStorageDirectory() + File.separator + "imooc" + File.separator; File file = new File(downloadFolderName); if (!file.exists()) { file.mkdir(); } String fileName = downloadFolderName + "imooc.apk"; File apkFile = new File(fileName); if (apkFile.exists()) { apkFile.delete(); } // 下载的长度,他和总长度的比值就是progress int downloadSize = 0; byte[] bytes = new byte[1024]; int length; OutputStream outputStream = new FileOutputStream(fileName); while ((length = inputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, length); downloadSize += length; /* * update UI * */ Message message = Message.obtain(); message.obj = downloadSize * 100 / contentLength; message.what = DOWNLOAD_MESSAGE_CODE; // 此时需要一个handler去sendMessage handler.sendMessage(message); } inputStream.close(); outputStream.close(); } catch (MalformedURLException e) { Message message = Message.obtain(); message.what = DOWNLOAD_MESSAGE_FAIL_CODE; handler.sendMessage(message); e.printStackTrace(); } catch (IOException e) { Message message = Message.obtain(); message.what = DOWNLOAD_MESSAGE_FAIL_CODE; handler.sendMessage(message); e.printStackTrace(); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == MY_REQUEST_CODE) { boolean isAllGrant = true; for (int grantResult : grantResults) { if (grantResult != PackageManager.PERMISSION_GRANTED) { isAllGrant = false; break; } } if (isAllGrant) { new Thread(new Runnable() { @Override public void run() { download(APP_URL); } }).start(); }else { //弹出对话框告诉用户需要权限的原因,并引导用去去应用管理权限中手动打开权限按钮 openAppDetails(); } } } /* 打开App的详情设置 */ private void openAppDetails() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("备份通讯录需要访问 “通讯录” 和 “外部存储器” , “请到 应用信息 -> 权限” 中授予!"); builder.setPositiveButton("去手动授权", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(); intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); intent.addCategory(Intent.CATEGORY_DEFAULT); intent.setData(Uri.parse("package:"+getPackageName())); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); startActivity(intent); } }); builder.setNegativeButton("取消",null); builder.show(); } }
1
收起
正在回答
4回答
你打开这个/storage/emulated/0/目录看有没有
Android网络操作与数据存储2018版
- 参与学习 人
- 提交作业 307 份
- 解答问题 1613 个
本专题是联网及数据处理的必备技能。课程从网络基础知识到线程间协同工作、异步下载处理。介绍了Android内外部文件存储、轻量级数据库SQLite的使用。利用屏幕适配、状态保持、百度地图解决实际问题。
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星