文章目录
- 布局
- Activity
- BroadcastReceiver
- 文件工具类
- 图片工具类
- Manifest
- MyApplication
- 这里的demo是一个通过下载地址下载图片文件到手机本地,并在Activity中展示这种图片的例子。
布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
tools:context="com.example.downFile.MainActivity">
<ImageView
android:id="@+id/iv_main"
android:layout_width="300dp"
android:layout_height="300dp"
android:src="@color/colorAccent"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按钮"
android:onClick="onClick"/>
</LinearLayout>
Activity
package com.example.downFile;
import android.app.DownloadManager;
import android.content.Context;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.ImageView;
import com.example.downFile.service.DownLoadReceiver;
import java.io.File;
public class MainActivity extends AppCompatActivity {
private String mTag = getClass().getSimpleName();
private ImageView mIvMain;
private String mDownLoadPath = "https://www.baidu.com/img/bd_logo1.png";
private String mFileName = "12.jpg";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mIvMain = findViewById(R.id.iv_main);
}
public void onClick(View v) {
if (FileUtils.initPictureDir()) {
FileUtils.deDuplication(new File(FileUtils.PICTURE_DIR, mFileName));
downPciture();
} else {
Log.d(mTag, "目录初始化失败");
}
}
private void downPciture() {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(mDownLoadPath));
request.setAllowedOverRoaming(false);
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(mDownLoadPath));
request.setMimeType(mimeString);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
request.setVisibleInDownloadsUi(true);
request.setDestinationInExternalPublicDir(TheApplication.getContext().getPackageName()
+ File.separator + "yunli" + File.separator, mFileName);
DownloadManager downloadManager = (DownloadManager) TheApplication.getContext()
.getSystemService(Context.DOWNLOAD_SERVICE);
long taskId = downloadManager.enqueue(request);
DownLoadReceiver downLoadReceiver = new DownLoadReceiver(TheApplication.getContext(),
downloadManager, taskId, mFileName, mIvMain);
registerReceiver(downLoadReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
}
BroadcastReceiver
package com.example.downFile.service;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.util.Log;
import android.widget.ImageView;
import com.example.downFile.FileUtils;
import com.example.downFile.LogUtil;
import com.example.downFile.ImageUtils;
import java.io.File;
public class DownLoadReceiver extends BroadcastReceiver {
private String mTag = getClass().getSimpleName();
private DownloadManager downloadManager;
private long mTaskId;
private Context mContext;
private String mFileName;
private ImageView iv_main;
public DownLoadReceiver(Context context, DownloadManager downloadManager, long taskId, String fileName, ImageView iv_main) {
this.downloadManager = downloadManager;
this.mTaskId = taskId;
this.mContext = context;
this.mFileName = fileName;
this.iv_main = iv_main;
}
@Override
public void onReceive(Context context, Intent intent) {
checkDownloadStatus();
}
private void checkDownloadStatus() {
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(mTaskId);
Cursor c = downloadManager.query(query);
if (c.moveToFirst()) {
int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
switch (status) {
case DownloadManager.STATUS_PAUSED:
LogUtil.e(mTag, ">>>下载暂停");
case DownloadManager.STATUS_PENDING:
LogUtil.e(mTag, ">>>下载延迟");
case DownloadManager.STATUS_RUNNING:
LogUtil.e(mTag, ">>>正在下载");
break;
case DownloadManager.STATUS_SUCCESSFUL:
LogUtil.e(mTag, ">>>下载完成");
File file = new File(FileUtils.PICTURE_DIR, mFileName);
Log.d("文件", "存在不:" + file.exists() + "路径" + file.getPath());
ImageUtils.ShowPic2View(mContext, file.getPath(), iv_main);
c.close();
break;
case DownloadManager.STATUS_FAILED:
LogUtil.e(mTag, ">>>下载失败");
break;
}
}
c.close();
}
}
文件工具类
package com.example.downFile;
import android.os.Environment;
import android.util.Log;
import java.io.File;
public class FileUtils {
private static final String SD_ROOT = Environment.getExternalStorageDirectory().getPath();
public static final String PICTURE_DIR = SD_ROOT + File.separator + TheApplication.getContext().getPackageName()
+ File.separator + "yunli" + File.separator;
private FileUtils() {
}
public static boolean sdExist() {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
public static boolean initPictureDir() {
if (!sdExist()) {
return false;
}
File picFile = new File(PICTURE_DIR);
boolean exists = picFile.exists();
boolean mkdirs = picFile.mkdirs();
return exists || mkdirs;
}
public static void deDuplication(File file) {
if (file.exists()) {
Log.d("fileUtil", "存在了:" + file.getPath());
boolean isDelete = file.delete();
Log.d("fileUtil", "删除文件结果:" + isDelete);
} else {
Log.d("fileUtil", "文件不存在:" + file.getPath());
}
}
}
图片工具类
package com.example.downFile;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Base64;
import android.widget.ImageView;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class ImageUtils {
public static String GenerateImage(Context context, String imgStr) {
if (imgStr == null) {
UtilsTools.MsgBox(context, "图片不能为空");
return "";
}
try {
byte[] b = Base64Utils.decode(imgStr);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
String dirPath = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/zdgj/";
File fileDir = new File(dirPath);
if (!fileDir.exists()) {
fileDir.mkdirs();
}
String imgFilePath = dirPath + System.currentTimeMillis() + ".jpg";
File file = new File(imgFilePath);
if (!file.exists()) {
file.createNewFile();
}
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
SharedPrefUtil.putString(context, "facePic", imgFilePath);
UtilsTools.MsgBox(context, "图片已保存到本地");
return imgFilePath;
} catch (Exception e) {
UtilsTools.MsgBox(context, e.getMessage());
return "";
}
}
public static String imageToBase64(String path) {
if (TextUtils.isEmpty(path)) {
return null;
}
InputStream is = null;
byte[] data;
String result = null;
try {
is = new FileInputStream(path);
data = new byte[is.available()];
is.read(data);
result = Base64.encodeToString(data, Base64.DEFAULT);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
public static void ShowPic2View(Context context, String path, ImageView imageView) {
File localFile = new File(path);
try {
FileInputStream localStream;
localStream = new FileInputStream(localFile);
Bitmap bitmap = BitmapFactory.decodeStream(localStream);
imageView.setImageBitmap(bitmap);
localStream.close();
} catch (Exception e) {
e.printStackTrace();
UtilsTools.MsgBox(context, e.getMessage());
}
}
public static void DeletePicFromMobile(Context context, String imgPath) {
try {
ContentResolver resolver = context.getContentResolver();
Cursor cursor = MediaStore.Images.Media.query(resolver, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Images.Media._ID}, MediaStore.Images.Media.DATA + "=?", new String[]{imgPath}, null);
boolean result;
if (cursor.moveToFirst()) {
long id = cursor.getLong(0);
Uri contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
Uri uri = ContentUris.withAppendedId(contentUri, id);
int count = context.getContentResolver().delete(uri, null, null);
result = count == 1;
} else {
File file = new File(imgPath);
result = file.delete();
}
if (result) {
UtilsTools.MsgBox(context, "删除成功");
}
} catch (Exception e) {
UtilsTools.MsgBox(context, e.getMessage());
}
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.downFile">
<!--用于访问网络-->
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.CALL_PHONE"/>
<!--获取手机唯一标识IMEI-->
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<!--获取运营商信息,用于支持提供运营商信息相关的接口-->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<!--用于访问wifi网络信息,wifi信息会用于进行网络定位-->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<!--这个权限用于获取wifi的获取权限,wifi信息会用来进行网络定位-->
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_PHONE_STORAE"/>
<!-- 用于进行网络定位 -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<!-- 用于访问GPS定位 -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<!-- 通讯录权限 -->
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.WRITE_CONTACTS"/>
<!-- 相机 -->
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_SETTINGS"/>
<application
android:name="com.example.downFile.TheApplication"
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">
<activity android:name="com.example.downFile.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
MyApplication
package com.example.downFile;
import android.app.Application;
import android.content.Context;
import java.lang.ref.WeakReference;
public class TheApplication extends Application {
private static WeakReference<Context> mContext;
@Override
public void onCreate() {
super.onCreate();
mContext = new WeakReference<>(getApplicationContext());
}
public static Context getContext() {
return mContext.get();
}
}