Androidダウンロードサーバー上のファイル

32166 ワード

購買依頼権限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

APIが6.0より大きい場合のアクティブな申請権限
public static void ApplyPermission(Context context) {
     
    ActivityCompat.requestPermissions((Activity) context, new String[]{
     
            Manifest.permission.CAMERA,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.INTERNET
    }, 1);
}

okhttp依存の追加
implementation 'com.squareup.okhttp3:okhttp:3.10.0'

ファイルツールクラスのダウンロード
public class DownloadUtil {
     

    private static DownloadUtil downloadUtil;
    private final OkHttpClient okHttpClient;

    public static DownloadUtil get() {
     
        if (downloadUtil == null) {
     
            downloadUtil = new DownloadUtil();
        }

        return downloadUtil;
    }

    public DownloadUtil() {
     
        okHttpClient = new OkHttpClient();
    }

    /**
     * @param url              
     * @param destFileDir           
     * @param destFileName       
     * @param listener         
     */
    public void download(final String url, final String destFileDir, final String destFileName, final OnDownloadListener listener) {
     
        Request request = new Request.Builder()
                .url(url)
                .build();

        OkHttpClient client = new OkHttpClient();

        try {
     
            Response response = client.newCall(request).execute();
        } catch (IOException e) {
     
            e.printStackTrace();
        }

        //    
        okHttpClient.newCall(request).enqueue(new Callback() {
     
            @Override
            public void onFailure(Call call, IOException e) {
     
                //         
                listener.onDownloadFailed(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
     

                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;

                //         
                File dir = new File(destFileDir);
                if (!dir.exists()) {
     
                    dir.mkdirs();
                }

                File file = new File(dir, destFileName);

                try {
     
                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
     

                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        //        
                        listener.onDownloading(progress);
                    }

                    fos.flush();
                    //    
                    listener.onDownloadSuccess(file);
                } catch (Exception e) {
     
                    listener.onDownloadFailed(e);
                }finally {
     
                    try {
     
                        if (is != null) {
     
                            is.close();
                        }
                        if (fos != null) {
     
                            fos.close();
                        }
                    } catch (IOException e) {
     

                    }
                }
            }
        });
    }

    public interface OnDownloadListener{
     
        //         
        void onDownloadSuccess(File file);
        //    
        void onDownloading(int progress);
        //      
        void onDownloadFailed(Exception e);
    }

}

使用
DownloadUtil.get().download("http://47.112.96.171:8081/in/test.html", "/mnt/sdcard/", "test.html",

        new  DownloadUtil.OnDownloadListener() {
     
            @Override
            public void onDownloadSuccess(File file) {
     
                Log.e("---------", "onDownloadSuccess");
            }
            @Override
            public void onDownloading(int progress) {
     
                Log.e("---------", "onDownloading");
            }
            @Override
            public void onDownloadFailed(Exception e) {
     
                Log.e("---------", "onDownloadFailed" + e.getMessage());

            }
        });


NetworkOnMainThreadException例外の解決:ネットワーク消費時間要求をサブスレッドに配置する
Handler handler = new Handler() {
     
    @Override
    public void handleMessage(Message msg) {
     
        super.handleMessage(msg);
        Bundle data = msg.getData();
        String val = data.getString("value");
        Log.i("mylog", "     -->" + val);
        // TODO
        // UI          
    }
};

/**
 *           
 */
Runnable networkTask = new Runnable() {
     
    @Override
    public void run() {
     
        // TODO
        //       http request.        
        DownloadUtil.get().download("http://47.112.96.171:8081/in/test.html", "/mnt/sdcard/", "test.html",
                new  DownloadUtil.OnDownloadListener() {
     
                    @Override
                    public void onDownloadSuccess(File file) {
     
                        Log.e("---------", "onDownloadSuccess");
                    }
                    @Override
                    public void onDownloading(int progress) {
     
                        Log.e("---------", "onDownloading");
                    }
                    @Override
                    public void onDownloadFailed(Exception e) {
     
                        Log.e("---------", "onDownloadFailed" + e.getMessage());
                    }
                });
    }

};

//  
new Thread(networkTask).start();

Communication to...not permitted by network security policy異常ネットワークセキュリティポリシーwww...comとの明文通信が許可されていない理由:Android P以降暗号化されていないトラフィック要求が制限されている
ソリューション:
  • resディレクトリの下にxmlフォルダを作成し、ファイルnetwork_を新規作成security_config.xml
  • ファイルに次の内容を入力します:
  • <?xml version="1.0" encoding="utf-8"?>
    <network-security-config>
        <base-config cleartextTrafficPermitted="true" />
    </network-security-config>
  • AndroidManifestのアプリケーションに新しいxmlファイル
  • を追加
    <application
            ****
            android:networkSecurityConfig="@xml/network_security_config"
            ****
     >