react-native 使用android DownloadM

2016-09-08  本文已影响0人  梦想扫地僧

当react-native项目中有版本更新需求时,android会用到下载新版本需求,此时,可以通过封装Native Modules 去调用android原生DownloadManager来实现下载,

1、书写功能类继承ReactContextBaseJavaModule,用于将方法暴露给js调用,程序中值得注意的地方是通过getCurrentActivity()来获取上下Context,而不是直接new Activity,若是直接new出来的实例是无法调用request.setDestinationInExternalFilesDir(xxx,xxx,xxx),此处会报错。

package com.testnativemodule;

import android.app.DownloadManager;

import android.app.DownloadManager.Request;

import android.content.Context;

import android.app.Activity;

import android.content.SharedPreferences;

import android.net.Uri;

import android.os.Environment;

import com.facebook.react.bridge.ReactApplicationContext;

import com.facebook.react.bridge.ReactContextBaseJavaModule;

import com.facebook.react.bridge.ReactMethod;

public class DownloadApk extends ReactContextBaseJavaModule{

DownloadManager downManager ;

Activity myActivity;

public DownloadApk(ReactApplicationContext reactContext) {

super(reactContext);

}

@Override

public String getName(){

return "DownloadApk";

}

@ReactMethod

public void downloading(String url,String description){

myActivity =getCurrentActivity();

downManager = (DownloadManager)myActivity.getSystemService(Context.DOWNLOAD_SERVICE);

Uri uri = Uri.parse(url);

DownloadManager.Request request = new Request(uri);

request.setAllowedNetworkTypes(Request.NETWORK_WIFI);

//设置通知栏标题

request.setNotificationVisibility(Request.VISIBILITY_VISIBLE);

request.setMimeType("application/vnd.android.package-archive");

request.setTitle("下载");

if(description==null||"".equals(description)){

description="目标apk正在下载";

}

request.setDescription(description);

request.setAllowedOverRoaming(false);

//设置文件存放目录

request.setDestinationInExternalFilesDir(myActivity, Environment.DIRECTORY_DOWNLOADS, description);

long downloadid=downManager.enqueue(request);

SharedPreferences sPreferences = myActivity.getSharedPreferences("ggfw_download", 0);

sPreferences.edit().putLong("ggfw_download_apk", downloadid).commit();

}

}


2、书写类继承ReactPackage接口,用于注册Native Modules,使得js上能够引入调用。

package com.testnativemodule;importcom.facebook.react.ReactPackage;importcom.facebook.react.bridge.JavaScriptModule;importcom.facebook.react.bridge.NativeModule;importcom.facebook.react.bridge.ReactApplicationContext;importcom.facebook.react.uimanager.ViewManager;importjava.util.ArrayList;importjava.util.Collections;importjava.util.List;public class DownloadApkPackage implementsReactPackage{@OverridepublicListcreateNativeModules(ReactApplicationContextreactContext){            Listmodules=newArrayList<>();            modules.add(newDownloadApk(reactContext));            returnmodules;  }@OverridepublicList>createJSModules(){returnCollections.emptyList();  }@OverridepublicListcreateViewManagers(ReactApplicationContext reactContext) {

return Collections.emptyList();

}

}

以上两个类已经实现了基本的下载功能,需要丰富下载其他逻辑如暂停,开始,等,DownLoadManager可以很好的实现,此处不对该类功能深入分析,网络上有很多的文章介绍它。


而外的一个功能,当下载完后,希望直接调用打开apk的安装界面,可以通过广播监听下载完成事件来实现。当监听到事件,判断服务下载的是否是我们所需的下载,是则进行打开安装界面:

3.我们可以写个类继承BroadcastReceiver,此处要注意的是使用Uri.fromFile(file)来取得下载文件的uri,网上有资料说dManager.getUriForDownloadedFile(myDwonloadID)来获取uri,但是此处使用却会使得程序本科,查看logcat日志信息描述大概为,找不到能够处理application/vnd.android.package-archive的Activity,后来发现应该是dManager.getUriForDownloadedFile返回的uri应该不是能够被正确指向下载文件的,具体原因我不是很清楚,故换了种方式来取得文件uri.

package com.testnativemodule;

import android.app.DownloadManager;

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.content.SharedPreferences;

import android.database.Cursor;

import android.net.Uri;

import android.os.Environment;

import android.util.Log;

import android.widget.Toast;

import java.io.File;

/**

* Created by audaque on 2016/9/6.

*/

public class DownLoadBroadcastReceiver extends BroadcastReceiver {

@Override

public void onReceive(Context context, Intent intent) {

long myDwonloadID = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);

SharedPreferences sPreferences = context.getSharedPreferences("ggfw_download", 0);

long refernece = sPreferences.getLong("ggfw_download_apk", 0);

if (refernece == myDwonloadID) {

DownloadManager dManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);

Intent install = new Intent(Intent.ACTION_VIEW);

//            Uri downloadFileUri = dManager.getUriForDownloadedFile(myDwonloadID);

DownloadManager.Query querybyId = new DownloadManager.Query();

querybyId.setFilterById(myDwonloadID);

Cursor myDownload = dManager.query(querybyId);

String dolownname=null;

if(myDownload.moveToFirst()){

int status = myDownload.getInt(myDownload.getColumnIndex(DownloadManager.COLUMN_STATUS));

if (status == DownloadManager.STATUS_SUCCESSFUL) {

// process download

int fileNameIdx = myDownload.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME);

//此处取得的是完整路径+文件名称

dolownname=myDownload.getString(fileNameIdx);

}else{

Toast.makeText(context,"下载失败,删除残留文件",Toast.LENGTH_LONG).show();

dManager.remove(myDwonloadID);

myDownload.close();

return;

}

myDownload.close();

}

if(dolownname==null){

return;

}

File file = new File(dolownname);

install.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");

install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

context.getApplicationContext().startActivity(install);

}

}

}

记得在AndroidManifest.xml中注册广播监听配置:

<receiver   android:name="com.testnativemodule.DownLoadBroadcastReceiver">

<intent-filter>

<action android:name="android.intent.action.DOWNLOAD_COMPLETE"/>

</intent-filter>

</receiver>


以上完成基本的下载功能,并下载完成后打开apk安装界面。

在js中引入NativeModules,通过其调用方式如下:

import {NativeModules} from 'react-native';

NativeModules.DownloadApk.downloading("http://len51-website.oss-cn-shenzhen.aliyuncs.com/app%2FSuiShoujie.apk","suishoujie.apk");

参数一为下载地址中的apk,下载保存文件名为第二个参数值suishoujie.apk。

上一篇下一篇

猜你喜欢

热点阅读