【问题标题】:Download Multiple Images and Change Extension After Downloading下载多个图像并在下载后更改扩展名
【发布时间】:2017-09-28 00:44:50
【问题描述】:

我的要求是在活动或带有下载管理器的 AsycTask doinBackground 方法中循环下载多个图像(我只需要初始化下载,但即使在应用程序关闭后它也会继续下载图像)并将所有图像存储在 sd 卡中在我的应用程序文件夹(例如 MyAppFolder)中,因为我需要与另一个应用程序共享图像路径并在下载后 我需要更改图像的扩展名,使其在图库文件夹中不可见。

【问题讨论】:

    标签: android android-asynctask android-broadcastreceiver android-download-manager


    【解决方案1】:
    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
    
    
            String root_sd = Environment.getExternalStorageDirectory().toString();
            // Set the URL to download image 
            String PhotoPictureDownLoadPath= "http://test.com/test.jpg";
            String photoPictureDirectoryPath = root_sd + "/DownloadImages/";
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            // Call this method in a loop to DOwnLoad Multiple Images.
            new  DownloadImages(MainActivity.this,PhotoPictureDownLoadPath,photoPictureDirectoryPath);
        }
    }
    
    
    
    // Class to download Images
    public class DownloadImages {
        Context myContext;
        String myDownlaodURL;
        String mySdCardSaveImagePath;
    
        public DownloadImages(Context theContext, String theUrl, String thePath) {
            myContext = theContext;
            myDownlaodURL = theUrl;
            mySdCardSaveImagePath = thePath;
    
            String PhotoPictureName = getFilename(myDownlaodURL);
            File PhotoPictureSavePath = new File(mySdCardSaveImagePath + "/" + PhotoPictureName);
            if (PhotoPictureSavePath.exists()) {
                return;
            }
            if (!PhotoPictureSavePath.exists()) {
                download();
            }
        }
    
        public String getFilename(String theFileName) {
    
            String filename = theFileName.substring(theFileName.lastIndexOf("/") + 1, theFileName.length());
            return filename;
        }
    
        public void download() {
            Uri Download_Uri = Uri.parse(myDownlaodURL);
            DownloadManager downloadManager = (DownloadManager) myContext.getSystemService(myContext.DOWNLOAD_SERVICE);
            DownloadManager.Request request = new DownloadManager.Request(Download_Uri);
    
            //Restrict the types of networks over which this download may proceed.
            request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
            //Set whether this download may proceed over a roaming connection.
            request.setAllowedOverRoaming(true);
            //Set the local destination for the downloaded file to a path within the application's external files directory
            //request.setDestinationInExternalFilesDir(myContext, mySdCardSaveImagePath, split[split.length - 1]);
            //request.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES, split[split.length-1]);
    
            String[] split = myDownlaodURL.split("/");
            //Set the local destination for the downloaded file to the folder specified by user.
            File destinationFile = new File(mySdCardSaveImagePath, split[split.length - 1]);
            request.setDestinationUri(Uri.fromFile(destinationFile));
    
            //Set the title of this download, to be displayed in notifications (if enabled).
            request.setTitle(split[split.length - 1]);
            //Set a description of this download, to be displayed in notifications (if enabled)
            request.setDescription(mySdCardSaveImagePath);
    
            request.setVisibleInDownloadsUi(true);
    
            //Enqueue a new download and get the reference Id
            long downloadReference = downloadManager.enqueue(request);
        }
    }
    
    //change the extension of image after downloading
    public class DownloadBroadcastReceiver extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
                long downloadId = intent.getLongExtra(
                        DownloadManager.EXTRA_DOWNLOAD_ID, 0);
    
                DownloadManager myDownloadManager = (DownloadManager) context.getSystemService(context.DOWNLOAD_SERVICE);
                Cursor c = myDownloadManager.query(new DownloadManager.Query().setFilterById(downloadId));
                if (c.moveToFirst()) {
                    int columnIndex = c
                            .getColumnIndex(DownloadManager.COLUMN_STATUS);
                    if (DownloadManager.STATUS_SUCCESSFUL == c
                            .getInt(columnIndex)) {
    
                        int filenameIndex = c.getColumnIndex(DownloadManager.COLUMN_TITLE);
                        String filename = c.getString(filenameIndex);
    
                        int filePathIndex = c.getColumnIndex(DownloadManager.COLUMN_DESCRIPTION);
                        String filePath = c.getString(filePathIndex);
    
    
                        if (!filename.isEmpty()) {
                            int dotposition = filename.lastIndexOf(".");
                            String filename_Without_Ext = filename.substring(0, dotposition);
                            String Ext = filename.substring(dotposition + 1, filename.length());
                            String newFileName = filename_Without_Ext + ".change" + Ext;
                            boolean success = new File(filePath + "/" + filename).
                                    renameTo(new File(filePath + "/" + newFileName));
                            //Log.d("Log", "" + success);
                        }
    
                    }
                }
            }
        }
    }
    
    //use  bellow premissions
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
        <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
        <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
        <uses-permission android:name="android.permission.INTERNET"/>
    
         <!-- Register Receiver in Manifest-->
         <receiver android:name=".DownloadBroadcastReceiver">
                <intent-filter>
                    <action android:name="android.intent.action.DOWNLOAD_COMPLETE"/>
                </intent-filter>
         </receiver>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-28
      • 2020-09-17
      • 1970-01-01
      • 2010-10-13
      • 1970-01-01
      • 2018-03-07
      • 1970-01-01
      相关资源
      最近更新 更多