在RN中Android項目中通過Image標簽去顯示網(wǎng)絡圖片殉疼,但是由于RN原生并沒有提供去清除緩存的api倔既,所以需要自己去Android封裝原生方法缕碎。
RN Android圖片存放
在RN的Android端,Image標簽是實現(xiàn)原理是Fresco(一個Android端的圖片加載框架),所以如果需要進行圖片緩存清空善已,只需要調(diào)用Fresco的方法灼捂,然后再由js代碼調(diào)用即可。
代碼實現(xiàn)
原生端:
/**
* 原生模塊
*/
public class ImgCacheModule extends ReactContextBaseJavaModule {
public ImgCacheModule(ReactApplicationContext reactContext) {
super(reactContext);
}
/**
*
* @return js調(diào)用的模塊名
*/
@Override
public String getName() {
return "ImgCacheModule";
}
/*
清除緩存
*/
@ReactMethod
public void clearImgCache( Callback success,Callback error) {
try {
ImagePipeline imagePipeline = Fresco.getImagePipeline();
imagePipeline.clearMemoryCaches();
imagePipeline.clearDiskCaches();
// combines above two lines
imagePipeline.clearCaches();
success.invoke("刪除成功");
}
catch (Exception e){
error.invoke("刪除失敗");
}
}
/*
查看緩存區(qū)大小
*/
@ReactMethod
public void getImgCache( Callback success,Callback error) {
try {
// Fresco.getImagePipelineFactory().getMainFileCache().trimToMinimum();
Fresco.getImagePipelineFactory().getMainFileCache().trimToMinimum();
long size = Fresco.getImagePipelineFactory().getMainFileCache().getSize();//b
success.invoke(size+"");
}
catch (Exception e){
e.printStackTrace();
error.invoke("獲取失敗");
}
}
}
js端:
import React, {Component} from 'react';
import {
AppRegistry,
StyleSheet,
Text,
NativeModules,
Image,
View
} from 'react-native';
export default class CacheDemo extends Component {
constructor(props){
super(props);
this.state={
imgCache: '0'
}
}
_clickShowImgCache(){
NativeModules.ImgCacheModule.getImgCache((size)=>{this.setState({imgCache:size});alert('獲取成功');},(error)=>{alert(error)});
}
_clickClearImgCache(){
NativeModules.ImgCacheModule.clearImgCache((success)=>{ NativeModules.ImgCacheModule.getImgCache((size)=>{this.setState({imgCache:size})},(error)=>{});alert(success)},(error)=>{alert(error)});
}
render() {
return (
<View style={styles.container}>
<Image style={{width:100,height:100}} source={{uri: 'https://facebook.github.io/react/img/logo_og.png'}}/>
<Image style={{width:100,height:100}} source={{uri: 'http://ac-c6scxa78.clouddn.com/f6b64dc4bf7bee56.jpg'}}/>
<Text onPress={this._clickShowImgCache.bind(this)} >獲取緩存</Text>
<Text >{this.state.imgCache+'b'}</Text>
<Text onPress={this._clickClearImgCache.bind(this)} >清除緩存</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
flexDirection: 'column'
}
});
AppRegistry.registerComponent('CacheDemo', () => CacheDemo);
實現(xiàn)效果
cache.gif