话不多说上代码
public class MainActivity extends AppCompatActivity {
private Button cunn;
private Button xian;
private ImageView ttt;
//private EditText rrr;
public static final int EXTERNAL_STORAGE_REQ_CODE = 10 ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cunn =(Button)findViewById(R.id.cun);
xian=(Button)findViewById(R.id.xians);
ttt=(ImageView)findViewById(R.id.tt);
// rrr=(EditText)findViewById(R.id.rr);
//final Intent intent = new Intent(MainActivity.this,Download.class);
final MyDownloadManager myDownloadManager = new MyDownloadManager();
//final String path= rrr.getText().toString();
final String path = "https://dss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2534506313,1688529724&fm=26&gp=0.jpg";
//final String path1 = "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=1328477591,2018436166&fm=26&gp=0.jpg";
//final String dirname ="/sdcard/";
//final String filename ="rr";
//final Download download = new Download();
// final dd d =new dd();
cunn.setOnClickListener(new View.OnClickListener() {
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onClick(View view) {
myDownloadManager.addDownloadTask(path);
// try {
// d.ddt(path1,dirname,filename);
// } catch (IOException e) {
// e.printStackTrace();
// }
}
});
xian.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//File file = new File(String.valueOf(myDownloadManager.getDownloadDir()));
//Bitmap bm = BitmapFactory.decodeFile(myDownloadManager.getDownloadDir()+myDownloadManager.getfileName(path));
// ttt.setImageBitmap(bm);
ttt.setImageURI(Uri.fromFile(new File(myDownloadManager.getDownloadDir() +"/"+ myDownloadManager.getfileName(path))));
//ttt.setImageUri(Uri.fromFile(new File("/sdcard/test.jpg")));
}
});
int permission = ActivityCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// 请求权限
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
EXTERNAL_STORAGE_REQ_CODE);
}
}
public static String MD5(String path) {
// URL url = new URL(path);
//String url = path;
//String path = Environment.getExternalStorageDirectory().getAbsolutePath();
//final long startTime = System.currentTimeMillis();
//String filename=url.substring(url.lastIndexOf("/") + 1);
String filename ="pp.jpg";
return filename;
}
//
public class MyDownloadManager {
public static final int EXTERNAL_STORAGE_REQ_CODE = 10 ;
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE };
/**
* Checks if the app has permission to write to device storage
*
* If the app does not has permission then the user will be prompted to
* grant permissions
*
* @param activity
*/
public static void verifyStoragePermissions(Activity activity) {
// Check if we have write permission
int permission = ActivityCompat.checkSelfPermission(activity,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE);
}
}
private static final String TAG = "MyDownloadManager";
private File downloadDir; // 文件保存路径
private static MyDownloadManager instance; // 单例
private String fileName;
// 单线程任务队列
public static Executor executor;
private static final ThreadFactory sThreadFactory = new ThreadFactory() {
private final AtomicInteger mCount = new AtomicInteger(1);
public Thread newThread(Runnable r) {
return new Thread(r, "MyDownloadManager #" + mCount.getAndIncrement());
}
};
private static final BlockingQueue<Runnable> sPoolWorkQueue = new LinkedBlockingQueue<>(128);
public static final Executor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(1, 1, 1,
TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
public MyDownloadManager() {
// 初始化下载路径
downloadDir = new File("/sdcard/");
if (!downloadDir.exists()) {
downloadDir.mkdirs();
}
executor = new SerialExecutor();
}
/**
* 顺序执行下载任务
*/
private static class SerialExecutor implements Executor {
final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
Runnable mActive;
public synchronized void execute(final Runnable r) {
mTasks.offer(new Runnable() {
public void run() {
try {
r.run();
} finally {
scheduleNext();
}
}
});
if (mActive == null) {
scheduleNext();
}
}
protected synchronized void scheduleNext() {
if ((mActive = mTasks.poll()) != null) {
THREAD_POOL_EXECUTOR.execute(mActive);
}
}
}
/**
* 获取单例对象
*
* @return
*/
public static MyDownloadManager getInstance() {
if (instance == null) {
instance = new MyDownloadManager();
}
return instance;
}
/**
* 添加下载任务
*
* @param path
*/
public void addDownloadTask(final String path) {
Log.i(TAG, "进入run00");
executor.execute(new Runnable() {
@Override
public void run() {
Log.i(TAG, "进入run");
download(path);
}
});
}
/**
* 下载文件
*
* @param path
*/
private void download(String path) {
String fileName = MainActivity.MD5(path);
File savePath = new File(downloadDir, fileName); // 下载文件路径
//File finallyPath = new File(downloadDir, fileName + ".png"); // 下载完成后加入
if (savePath.exists()) { // 文件存在则已下载
Log.i(TAG, "file is existed");
return;
}
// 如果是Wifi则开始下载
if (savePath.exists() && savePath.delete()) { // 如果之前存在文件,证明没有下载完成,删掉重新创建
savePath = new File(downloadDir, fileName);
Log.i(TAG, "download 111111");
}
Log.i(TAG, "download start");
try {
byte[] bs = new byte[1024];
int len;
URL url = new URL(path);
InputStream is = url.openStream();
OutputStream os = new FileOutputStream(savePath,true);
Log.i(TAG, "download 22222");
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
is.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
//if (savePath.renameTo(finallyPath)) { // 下载完成后重命名为
// Log.i(TAG, "download end");
// }
}
/**
* 添加删除任务
*
* @param path
*/
public void addDeleteTask(final String path) {
executor.execute(new Runnable() {
@Override
public void run() {
delete(path);
}
});
}
/**
* 删除本地文件
*
* @param path
*/
private void delete(String path) {
String fileName = MainActivity.MD5(path);
File savePath = new File(downloadDir, fileName + ".png");
Log.i(TAG, savePath.getPath());
if (savePath.exists()) {
if (savePath.delete()) {
Log.i(TAG, "file is deleted");
}
}
}
/**
* 返回下载路径
*
* @return
*/
public File getDownloadDir() {
return downloadDir;
}
public String getfileName(String path){
String f =MainActivity.MD5(path);
return f;
}
}
//
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="保存"
android:id="@+id/cun"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="显示"
android:id="@+id/xians"
/>
<ImageView
android:id="@+id/tt"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
//
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.myapplication">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"
tools:ignore="ProtectedPermissions" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:requestLegacyExternalStorage="true"
>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
代码中我有很多尝试的地方 注释的地方可以忽略 或者可以参考