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

Android 下载多个图像并在下载后更改扩展名,android,android-asynctask,android-broadcastreceiver,android-download-manager,Android,Android Asynctask,Android Broadcastreceiver,Android Download Manager,我的要求是使用下载管理器(我只需要初始化下载,但即使在应用程序关闭后,它仍会继续下载图像)以循环方式在活动或AsycTask doinBackground方法中下载多个图像,并将所有图像存储在我的应用程序文件夹(例如MyAppFolder)的sd卡中因为我需要与另一个应用程序共享图像路径,下载后 我需要更改图像的扩展名,使其在gallery文件夹中不可见 public类MainActivity扩展了AppCompatActivity{ public class MainActivity exte

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

public类MainActivity扩展了AppCompatActivity{
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>
@凌驾 创建时受保护的void(Bundle savedInstanceState){ 字符串root_sd=Environment.getExternalStorageDirectory().toString(); //设置URL以下载图像 字符串PhotoPicturedDownloadPath=”http://test.com/test.jpg"; 字符串photoPictureDirectoryPath=root_sd+“/DownloadImages/”; super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //在循环中调用此方法以下载多个图像。 新的下载图像(MainActivity.this、PhotoPicturedDownloadPath、PhotoPicturedDirectoryPath); } } //类下载图像 公共类下载图片{ 语境; 字符串myDownlaodURL; 字符串mySdCardSaveImagePath; 公共下载图像(上下文上下文、字符串URL、字符串路径){ myContext=上下文; myDownlaodURL=URL; mySdCardSaveImagePath=路径; 字符串PhotoPictureName=getFilename(myDownlaodURL); File PhotoPictureSavePath=新文件(mySdCardSaveImagePath+“/”+PhotoPictureName); 如果(PhotoPictureSavePath.exists()){ 返回; } 如果(!PhotoPictureSavePath.exists()){ 下载(); } } 公共字符串getFilename(字符串文件名){ String filename=theFileName.substring(theFileName.lastIndexOf(“/”)+1,theFileName.length()); 返回文件名; } 公开下载{ Uri下载\u Uri=Uri.parse(myDownlaodURL); DownloadManager DownloadManager=(DownloadManager)myContext.getSystemService(myContext.DOWNLOAD\u服务); DownloadManager.Request=新的DownloadManager.Request(下载Uri); //限制可以进行此下载的网络类型。 request.setAllowedNetworkTypes(DownloadManager.request.NETWORK_WIFI | DownloadManager.request.NETWORK_MOBILE); //设置此下载是否可以通过漫游连接继续。 request.setAllowedOverRoaming(true); //将下载文件的本地目标设置为应用程序外部文件目录中的路径 //setdestinationnexternalfilesdir(myContext,mySdCardSaveImagePath,split[split.length-1]); //request.setDestinationNexternalPublicDir(Environment.DIRECTORY_PICTURES,split[split.length-1]); 字符串[]split=myDownlaodURL.split(“/”); //将下载文件的本地目标设置为用户指定的文件夹。 File destinationFile=新文件(mySdCardSaveImagePath,split[split.length-1]); setDestinationUri(Uri.fromFile(destinationFile)); //设置此下载的标题,以在通知中显示(如果启用)。 请求.setTitle(拆分[split.length-1]); //设置此下载的说明,以在通知中显示(如果启用) setDescription(mySdCardSaveImagePath); request.setVisibleInDownloadsUi(true); //将新下载排队并获取引用Id long downloadReference=downloadManager.enqueue(请求); } } //下载后更改图像的扩展名 公共类DownloadBroadcastReceiver扩展了BroadcastReceiver{ @凌驾 公共void onReceive(上下文、意图){ String action=intent.getAction(); if(DownloadManager.ACTION\u DOWNLOAD\u COMPLETE.equals(ACTION)){ long downloadId=intent.getLongExtra( DownloadManager.EXTRA_DOWNLOAD_ID,0); DownloadManager myDownloadManager=(DownloadManager)context.getSystemService(context.DOWNLOAD\u SERVICE); 游标c=myDownloadManager.query(new DownloadManager.query().setFilterById(downloadId)); if(c.moveToFirst()){ int columnIndex=c .getColumnIndex(DownloadManager.COLUMN_状态); 如果(DownloadManager.STATUS_SUCCESSFUL==c .getInt(列索引)){ int filenameIndex=c.getColumnIndex(DownloadManager.COLUMN\u TITLE); 字符串文件名=c.getString(filenameIndex); int filePathIndex=c.getColumnIndex(DownloadManager.COLUMN_说明); 字符串filePath=c.getString(filePathIndex); 如果(!filename.isEmpty()){ int dotposition=filename.lastIndexOf(“.”); 字符串filename_不带_Ext=filename.substring(0,点位置); 字符串Ext=filename.substring(dotposition+1,filename.length()); 字符串newFileName=filename_,不带_Ext+“.change”+Ext; 布尔成功=新文件(filePath+“/”+文件名)。 重命名为(新文件(filePath+“/”+newFileName)); //Log.d(“Log”和“+success”); } } } } } } //使用下面的命令