Activity 使用Retrofit实现应用下载

今天的是用retrofit 实现应用下载

  • 需要的权限和依赖

权限



依赖

implementation 'com.squareup.okhttp3:okhttp:3.10.0'//okhttp3
//retrofit基本依赖
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'io.reactivex.rxjava2:rxjava:2.0.1' //RxJava
implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'

  • 工具类
public class InstallUtil {


    public static final int UNKNOWN_CODE = 2019;

    public static void installApk(Context context, String path) {
        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
            startInstallO(context,path);
        }else if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.N){
            startInstallN(context,path);
        }else {
            startInstall(context,path);
        }
    }

    /**
     *android1.x-6.x
     *@param path 文件的路径
     */
    private static void startInstall(Context context, String path) {
        Intent install = new Intent(Intent.ACTION_VIEW);
        install.setDataAndType(Uri.parse("file://" + path), "application/vnd.android.package-archive");
        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(install);
    }

    /**
     * android7.x
     * @param path 文件路径
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private static void startInstallN(Context context, String path) {
        //参数1 上下文, 参数2 在AndroidManifest中的android:authorities值, 参数3  共享的文件
        Uri apkUri = FileProvider.getUriForFile(context, "com.baidu.download.provider", new File(path));
        Intent install = new Intent(Intent.ACTION_VIEW);
        //由于没有在Activity环境下启动Activity,设置下面的标签
        install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //添加这一句表示对目标应用临时授权该Uri所代表的文件
        install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        install.setDataAndType(apkUri, "application/vnd.android.package-archive");
        context.startActivity(install);
    }

    /**
     * android8.x
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    private static void startInstallO(final Context context, String path) {
        boolean isGranted = context.getPackageManager().canRequestPackageInstalls();
        if (isGranted) startInstallN(context,path);//安装应用的逻辑(写自己的就可以)
        else new AlertDialog.Builder(context)
                .setCancelable(false)
                .setTitle("安装应用需要打开未知来源权限,请去设置中开启权限")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface d, int w) {
                        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
                        Activity act = (Activity) context;
                        act.startActivityForResult(intent, UNKNOWN_CODE);
                    }
                })
                .show();
    }

}
  • MyServer.java
public interface MyServer {

    //http://cdn.banmi.com/banmiapp/apk/banmi_330.apk
    public String Url = "http://cdn.banmi.com/banmiapp/";

    @GET("apk/banmi_330.apk")
    Observable getData();

}

  • activity_main.xml



    
  • MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private File mSd;
    private static final String TAG = "MainActivity";
    /**
     * Retrofit
     */
    private Button mBtn2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initSD();
    }

    private void initSD() {

        // 判断该程序中是否有写入的权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            // 如果有,调用方法,获取到sd卡的全路径
            openSD();
        } else {
            // 如果没有,获取到该权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
        }

    }

    /**
     * 请求权限成功的结果
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 100 && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            openSD();
        }

    }

    private void openSD() {
        // Environment拥有一些可以获取环境变量的方法 

        // 判断外部存储状态是否为安装的状态
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            // 获取到sd卡的路劲
            mSd = Environment.getExternalStorageDirectory();
        }

    }

    private void initView() {
        mBtn2 = (Button) findViewById(R.id.btn2);
        mBtn2.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.btn2:
                retrofit();
                break;
        }
    }

    private void retrofit() {

        // 构建Retrofit对象
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(MyServer.Url)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();

        // 创建接口的对象
        MyServer myServer = retrofit.create(MyServer.class);

        // 调用接口中的方法
        Observable observable = myServer.getData();

        observable.subscribeOn(Schedulers.io()) // 在子线程中运行
                .subscribe(new Observer() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseBody value) {

                        // 通过请求体获取到数据流
                        InputStream inputStream = value.byteStream();

                        // 通过请求体获取到需要写入的长度
                        long max = value.contentLength();

                        saveFile(inputStream, mSd + "/" + "acc456.apk", max);

                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.d(TAG, "onError: "+e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });


    }

   
    /**
     * @param inputStream 输入流
     * @param s           安装程序的地址
     * @param max         安装的程序的总长度
     */
    private void saveFile(InputStream inputStream, final String s, long max) {
        // 读写进度
        long count = 0;

        try {
            // 实例化一个文件输出流
            FileOutputStream fileOutputStream = new FileOutputStream(new File(s));

            int length = -1;
            byte[] bytes = new byte[1024 * 100000];

            while ((length = inputStream.read(bytes)) != -1) {

                // 根据指定的长度,来写入数据
                fileOutputStream.write(bytes, 0, length);

                // 写入数据的进度
                count += length;

                Log.d(TAG, "progress: " + count + ",max:" + max);

            }

            // 关闭输入流
            inputStream.close();
            // 关闭输出流
            fileOutputStream.close();

            // 在主线程中运行
            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    Toast.makeText(MainActivity.this, "下载完成", Toast.LENGTH_SHORT).show();
                    // 安装apk
                    InstallUtil.installApk(MainActivity.this, s);
                }
            });


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }


}

你可能感兴趣的:(Activity 使用Retrofit实现应用下载)