无法从downloadmanager下载映像

50pmv0ei  于 2021-08-25  发布在  Java
关注(0)|答案(1)|浏览(295)

我制作了一个meme应用程序,它从api获取图像url,我正在解析它们并使用glide在recyler视图中显示,在我的项目布局中,我有两个按钮,一个用于共享,一个用于下载图像,我希望当用户单击下载按钮时,图像下载到用户手机上。
我正在为此使用下载管理器,但图像没有下载,这是我的适配器类

public class Adapter  extends RecyclerView.Adapter<Adapter.ViewHolder> {

Context context;
ArrayList<Model> modelArrayList;

public Adapter(Context context, ArrayList<Model> modelArrayList) {
    this.context = context;
    this.modelArrayList = modelArrayList;
}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

    View view  = LayoutInflater.from(context).inflate(R.layout.item_layout,parent,false);

    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
     String memeUrl = modelArrayList.get(position).getUrl();
     holder.setImage(memeUrl);
     holder.button.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {
             Intent sharing = new Intent(Intent.ACTION_SEND);
             sharing.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
             sharing.setType("text/plain");
             //  String sharebody = "Quizz time beautiful app";
             String subject = "Hey watch this cool meme Click this link "+memeUrl+"\n\n";

             sharing.putExtra(Intent.EXTRA_TEXT, subject);

            context.startActivity(Intent.createChooser(sharing, "Share using"));
         }
     });

     holder.buttonDownload.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {
             try {
                 downloadImage(memeUrl);
              }
             catch (Exception e){
                 e.printStackTrace();
             }
         }
     });
}

@Override
public int getItemCount() {
    return modelArrayList.size();
}

public  class ViewHolder extends RecyclerView.ViewHolder{

    ImageView memeImage;
    Button button, buttonDownload;

    public ViewHolder(@NonNull View itemView) {
        super(itemView);

        memeImage = itemView.findViewById(R.id.imageView);
        button = itemView.findViewById(R.id.button);
        buttonDownload = itemView.findViewById(R.id.btn_download);
    }

    void  setImage(String link){
        Glide.with(context).load(link).into(memeImage);
    }
}

void downloadImage(String url){
    DownloadManager downloadManager = null;
    downloadManager = (DownloadManager) context.getSystemService(context.DOWNLOAD_SERVICE);

    Uri downloaduri = Uri.parse(url);

    DownloadManager.Request request = new DownloadManager.Request(downloaduri);

    request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
            .setAllowedOverRoaming(false)
            .setTitle("meme1")
            .setMimeType("image/jpeg")
            .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
            .setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES, File.separator+"meme1"+".jpg");
    downloadManager.enqueue(request);

    Toast.makeText(context, "Image downloaded", Toast.LENGTH_SHORT).show();

}

}
logcat

2021-07-05 20:24:20.134 20262-20262/com.choudhary.memegram W/System.err: 
   java.lang.SecurityException: No permission to write to 
/storage/emulated/0/Pictures/meme1.jpg: 
 Neither user 10340 nor current process has android.permission.WRITE_EXTERNAL_STORAGE.
  2021-07-05 20:24:20.145 20262-20262/com.choudhary.memegram W/System.err:     at 
  android.os.Parcel.createException(Parcel.java:1953)
2021-07-05 20:24:20.145 20262-20262/com.choudhary.memegram W/System.err:     at 
android.os.Parcel.readException(Parcel.java:1921)

mymenifest

<?xml version="1.0" encoding="utf-8"?>
<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"/>

<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/Theme.MemeGram">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
b4lqfgs4

b4lqfgs41#

给你-

public void downloadFile(String url, String filepath, String title, String desc, Context context) {
        if (new File(filepath).exists()) {
            Toast.makeText(context, "This file is already downloaded.", Toast.LENGTH_LONG).show();
        } else {
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
            // 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);
                request.setTitle(title);
                request.setDescription(desc);
            }
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filepath);
            DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);

            manager.enqueue(request);
            final String finalDestination = filepath;
            final BroadcastReceiver onComplete = new BroadcastReceiver() {
                public void onReceive(Context context, Intent intent) {

                //Do what to do after the download completes
                }
            };
            registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

            Toast.makeText(context, "Download Started,check downloads when completed.", Toast.LENGTH_LONG).show();
        }
    }

相关问题