下载后下载多个图像并更改扩展名

时间:2017-04-30 09:30:28

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

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

1 个答案:

答案 0 :(得分: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>