瀏覽代碼

内存清理

压力锅
fyf 9 月之前
父節點
當前提交
e1b6a5ee7e
共有 12 個檔案被更改,包括 144 行新增154 行删除
  1. +1
    -1
      app/src/main/java/com/bonait/bnframework/common/base/BaseActivity.java
  2. +10
    -7
      app/src/main/java/com/bonait/bnframework/common/image/MyBitmapUtils.java
  3. +88
    -144
      app/src/main/java/com/bonait/bnframework/common/image/utils/LocalCacheUtils.java
  4. +3
    -0
      app/src/main/java/com/bonait/bnframework/common/linktab/good/GoodRightAdapter.java
  5. +3
    -1
      app/src/main/java/com/bonait/bnframework/common/linktab/makegood/MakeGoodRightAdapter.java
  6. +5
    -1
      app/src/main/java/com/bonait/bnframework/modules/home/activity/BottomNavigationMainActivity.java
  7. +10
    -0
      app/src/main/java/com/bonait/bnframework/modules/home/adapter/image_sp_adapter.java
  8. +7
    -0
      app/src/main/java/com/bonait/bnframework/modules/home/adapter/newgood_adapter.java
  9. +7
    -0
      app/src/main/java/com/bonait/bnframework/modules/home/adapter/newmakegood_adapter.java
  10. +4
    -0
      app/src/main/java/com/bonait/bnframework/modules/home/fragment/MakeGoodFragment.java
  11. +3
    -0
      app/src/main/java/com/bonait/bnframework/modules/home/fragment/from/GoodPeiFangActivity.java
  12. +3
    -0
      app/src/main/java/com/bonait/bnframework/modules/home/fragment/from/ImageChooseActivity.java

+ 1
- 1
app/src/main/java/com/bonait/bnframework/common/base/BaseActivity.java 查看文件

@@ -52,7 +52,7 @@ public class BaseActivity extends QMUIActivity implements EasyPermissions.Permis
@Override
protected void onDestroy() {
super.onDestroy();
LocalCacheUtils.Get().ClearBitmapFile();
LocalCacheUtils.Get().releaseMemory();
}

/**


+ 10
- 7
app/src/main/java/com/bonait/bnframework/common/image/MyBitmapUtils.java 查看文件

@@ -39,14 +39,17 @@ public class MyBitmapUtils {
}

//本地缓存
if(LocalCacheUtils.Get().SetBitmapFile(ivPic,name)){
return;
}

//网络缓存
if(url.contains("http"))
if(url!=null && !url.isEmpty())
{
mNetCacheUtils.getBitmapFromNet(ivPic,url);
if(LocalCacheUtils.Get().SetBitmapFile(ivPic,name)){
return;
}

//网络缓存
if(url.contains("http"))
{
mNetCacheUtils.getBitmapFromNet(ivPic,url);
}
}
}
/**


+ 88
- 144
app/src/main/java/com/bonait/bnframework/common/image/utils/LocalCacheUtils.java 查看文件

@@ -1,12 +1,16 @@
package com.bonait.bnframework.common.image.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Debug;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.os.Process;

import com.bonait.bnframework.R;
import com.bonait.bnframework.business.OrderServer;
@@ -20,6 +24,7 @@ import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;
@@ -59,18 +64,15 @@ public class LocalCacheUtils {

Glide.with(ivPic.getContext()).load(file)
//.override(width, height)
.thumbnail(0.1f) // 加载原始图片的10%作为缩略图
// .thumbnail(0.1f) // 加载原始图片的10%作为缩略图
//.fitCenter() // 缩放图片以适应ImageView的尺寸
.override(300, 150) // 设置目标图片的宽度和高度
.override(150, 75) // 设置目标图片的宽度和高度
.placeholder(R.mipmap.loading2)
.error(R.mipmap.loadingerror)
// .error(R.mipmap.loadingerror)
.skipMemoryCache(true) // 禁用内存缓存
.diskCacheStrategy(DiskCacheStrategy.NONE)
//.diskCacheStrategy(DiskCacheStrategy.ALL) // 缓存所有版本的图片
.into(ivPic);

if (!imageViews.contains(ivPic)) {
imageViews.add(ivPic);
}
System.out.println("从本地获取图片啦.....");
return true;
} catch (OutOfMemoryError e) {
@@ -81,119 +83,6 @@ public class LocalCacheUtils {
}
return false;
}

/**
* 清除
*/
public void ClearBitmapFile() {
try {
List<ImageView> vis = new ArrayList<>();
for (ImageView imageView : imageViews) {
if (!isActivityVisible(imageView.getContext())) {
imageView.setImageDrawable(null);
vis.add(imageView);
}
}

for (ImageView img : vis) {
imageViews.remove(img);
}
System.gc();
} catch (Exception ex) {
System.gc();
}
}

public List<ImageView> imageViews = new ArrayList<>();

/**
* 从本地读取图片---已经抛弃
*
* @param url
*/
public Bitmap getBitmapFromLocal(String url) {
String fileName = null;//把图片的url当做文件名,并进行MD5加密
try {
fileName = url;//MD5Encoder.encode(url);//AES.Encrypt(url);//MD5Encoder.encode(url);
File file = new File(CACHE_PATH, fileName);
Bitmap bitmap = null;
if (file.exists())//
{
bitmap = BitmapFactory.decodeStream(new FileInputStream(file));
}
return bitmap;
} catch (Exception e) {
e.printStackTrace();
}

return null;
}

/**
* 最新根据Url加载图片
*
* @param ivPic
* @param url
* @return
*/
public boolean getBitmapFromLocal_New(ImageView ivPic, String url) {
BitmapFactory.Options opts = null;
int width = 400;//ivPic.getWidth();//420;//210
int height = 200;
File file = new File(CACHE_PATH, url);
if (null != file && file.exists()) {
if (width > 0 && height > 0) {
opts = new BitmapFactory.Options();
// 只是返回的是图片的宽和高,并不是返回一个Bitmap对象
opts.inJustDecodeBounds = true;
// 信息没有保存在bitmap里面,而是保存在options里面
BitmapFactory.decodeFile(file.getPath(), opts);
// 计算图片缩放比例
final int minSideLength = Math.min(width, height);
// 缩略图大小为原始图片大小的几分之一。根据业务需求来做。
opts.inSampleSize = ImageUtils.computeSampleSize(opts, minSideLength,
width * height);
// 重新读入图片,注意此时已经把options.inJustDecodeBounds设回false
opts.inJustDecodeBounds = false;
// 设置是否深拷贝,与inPurgeable结合使用
opts.inInputShareable = true;
// 设置为True时,表示系统内存不足时可以被回 收,设置为False时,表示不能被回收。
opts.inPurgeable = true;
}
try {
Bitmap bitmap = BitmapFactory.decodeFile(file.getPath(), opts);
ivPic.setImageBitmap(bitmap);

if (!imageViews.contains(ivPic)) {
imageViews.add(ivPic);
}
System.out.println("从本地获取图片啦.....");
return true;
} catch (OutOfMemoryError e) {
e.printStackTrace();
}
}
return false;
}

/**
* 清除缓存
*/
public void Clear() {
List<ImageView> vis = new ArrayList<>();
for (ImageView imageView : imageViews) {

if (!isActivityVisible(imageView.getContext())) {
imageView.setImageDrawable(null);
vis.add(imageView);
}
}

for (ImageView img : vis) {
imageViews.remove(img);
}
}

/**
* 判断活动窗体是否正在显示
*
@@ -239,35 +128,90 @@ public class LocalCacheUtils {
return "";
}

private RandomAccessFile procStatFile;
private RandomAccessFile appStatFile;
private Long lastCpuTime;
private Long lastAppCpuTime;
/**
* 文件拷贝
*
* @param oldFilePath
* @param newFilePath
* 运行内存
*/
public void RunCPUOrMemory()
{
// int cpu = (int)sampleCPU();
// int mem = (int)sampleMemory();
// Log.e("实时内存消耗", ": CPU: " + cpu + "%" + ", Memory: " + mem + "MB");
releaseMemory();
}

/**
* 释放内存
*/
public static void releaseMemory() {
System.runFinalization();
Runtime.getRuntime().gc();
Runtime.getRuntime().runFinalization();
System.gc();
}
/**
* 读取CPU
* @return
* @throws IOException
*/
public static boolean fileCopy(String oldFilePath, String newFilePath) throws IOException {
//如果原文件不存在
if (fileExists(oldFilePath) == false) {
return false;
private double sampleCPU() {
long cpuTime;
long appTime;
double sampleValue = 0.0D;
try {
if (procStatFile == null || appStatFile == null) {
procStatFile = new RandomAccessFile("/proc/stat", "r");
appStatFile = new RandomAccessFile("/proc/" + Process.myPid() + "/stat", "r");
} else {
procStatFile.seek(0L);
appStatFile.seek(0L);
}
String procStatString = procStatFile.readLine();
String appStatString = appStatFile.readLine();
String procStats[] = procStatString.split(" ");
String appStats[] = appStatString.split(" ");
cpuTime = Long.parseLong(procStats[2]) + Long.parseLong(procStats[3])
+ Long.parseLong(procStats[4]) + Long.parseLong(procStats[5])
+ Long.parseLong(procStats[6]) + Long.parseLong(procStats[7])
+ Long.parseLong(procStats[8]);
appTime = Long.parseLong(appStats[13]) + Long.parseLong(appStats[14]);
if (lastCpuTime == null && lastAppCpuTime == null) {
lastCpuTime = cpuTime;
lastAppCpuTime = appTime;
return sampleValue;
}
sampleValue = ((double) (appTime - lastAppCpuTime) / (double) (cpuTime - lastCpuTime)) * 100D;
lastCpuTime = cpuTime;
lastAppCpuTime = appTime;
} catch (Exception e) {
e.printStackTrace();
}
//获得原文件流
FileInputStream inputStream = new FileInputStream(new File(oldFilePath));
byte[] data = new byte[1024];
//输出流
FileOutputStream outputStream = new FileOutputStream(new File(newFilePath));
//开始处理流
while (inputStream.read(data) != -1) {
outputStream.write(data);
return sampleValue;
}
/**
* 读取内存消耗
* @return
*/
private double sampleMemory() {
double mem = 0.0D;
try {
// 统计进程的内存信息 totalPss
ActivityManager activityManager = (ActivityManager) ConfigName.getInstance().dishesCon.getSystemService(Context.ACTIVITY_SERVICE);
final Debug.MemoryInfo[] memInfo = activityManager.getProcessMemoryInfo(new int[]{Process.myPid()});
if (memInfo.length > 0) {
// TotalPss = dalvikPss + nativePss + otherPss, in KB
final int totalPss = memInfo[0].getTotalPss();
if (totalPss >= 0) {
// Mem in MB
mem = totalPss / 1024.0D;
}
}
} catch (Exception e) {
e.printStackTrace();
}
inputStream.close();
outputStream.close();
return true;
return mem;
}

public static boolean fileExists(String filePath) {
File file = new File(filePath);
return file.exists();
}
}

+ 3
- 0
app/src/main/java/com/bonait/bnframework/common/linktab/good/GoodRightAdapter.java 查看文件

@@ -3,6 +3,7 @@ package com.bonait.bnframework.common.linktab.good;
import android.content.res.Resources;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

@@ -37,4 +38,6 @@ public class GoodRightAdapter extends BaseQuickAdapter<LinkMode, BaseViewHolder>
newgood_adapter adapter = new newgood_adapter(getContext(), item.content);
view.setAdapter(adapter);
}


}

+ 3
- 1
app/src/main/java/com/bonait/bnframework/common/linktab/makegood/MakeGoodRightAdapter.java 查看文件

@@ -3,6 +3,7 @@ package com.bonait.bnframework.common.linktab.makegood;
import android.content.res.Resources;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

@@ -26,6 +27,7 @@ public class MakeGoodRightAdapter extends BaseQuickAdapter<LinkMode, BaseViewHol
Fdata=data;
}

public newmakegood_adapter adapter=null;
@Override
protected void convert(BaseViewHolder holder, LinkMode item) {
RecyclerView view= holder.getView(R.id.recycler_view);
@@ -33,7 +35,7 @@ public class MakeGoodRightAdapter extends BaseQuickAdapter<LinkMode, BaseViewHol
MyLayoutManager layout = new MyLayoutManager();
layout.setAutoMeasureEnabled(true);
view.setLayoutManager(layout);
newmakegood_adapter adapter = new newmakegood_adapter(getContext(), item.content);
adapter = new newmakegood_adapter(getContext(), item.content);
view.setAdapter(adapter);
}
}

+ 5
- 1
app/src/main/java/com/bonait/bnframework/modules/home/activity/BottomNavigationMainActivity.java 查看文件

@@ -20,6 +20,7 @@ import com.bonait.bnframework.common.helper.MQTT;
import com.bonait.bnframework.common.helper.MediaPlayerHelper;
import com.bonait.bnframework.common.helper.MessageLog;
import com.bonait.bnframework.common.helper.ThreadManager;
import com.bonait.bnframework.common.image.utils.LocalCacheUtils;
import com.bonait.bnframework.common.modbus.ModbusTcpServer;
import com.bonait.bnframework.common.tabbar.MainNavigateTabBar;
import com.bonait.bnframework.common.utils.NetworkUtils;
@@ -144,7 +145,10 @@ public class BottomNavigationMainActivity extends BaseActivity {
ConfigName.getInstance().PlcIsConnect = false;
}
}
Thread.sleep(10000);

LocalCacheUtils.Get().RunCPUOrMemory();

Thread.sleep(5000);
} catch (Exception e) {
Log.i("PLC", "PLC重连接失败!" + e.getMessage());
}


+ 10
- 0
app/src/main/java/com/bonait/bnframework/modules/home/adapter/image_sp_adapter.java 查看文件

@@ -53,6 +53,16 @@ public class image_sp_adapter extends RecyclerView.Adapter<RecyclerView.ViewHold

}

/**
* 当列表不在使用时候
* @param holder The ViewHolder for the view being recycled
*/
@Override
public void onViewRecycled(@NonNull RecyclerView.ViewHolder holder) {
super.onViewRecycled(holder);
// 回收不可见的图片资源
((MyLCViewHolder1)holder).img.setImageDrawable(null);
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
try {


+ 7
- 0
app/src/main/java/com/bonait/bnframework/modules/home/adapter/newgood_adapter.java 查看文件

@@ -50,6 +50,13 @@ public class newgood_adapter extends RecyclerView.Adapter<RecyclerView.ViewHolde
Data = data;
}

@Override
public void onViewRecycled(@NonNull RecyclerView.ViewHolder holder) {
super.onViewRecycled(holder);
// 回收不可见的图片资源
((MyLCViewHolder1)holder).ImageUrl.setImageDrawable(null);
}

@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {


+ 7
- 0
app/src/main/java/com/bonait/bnframework/modules/home/adapter/newmakegood_adapter.java 查看文件

@@ -50,6 +50,13 @@ public class newmakegood_adapter extends RecyclerView.Adapter<RecyclerView.View
return new newgood_adapter.MyLCViewHolder1(inflate);
}

@Override
public void onViewRecycled(@NonNull RecyclerView.ViewHolder holder) {
super.onViewRecycled(holder);
// 回收不可见的图片资源
((MyLCViewHolder1)holder).ImageUrl.setImageDrawable(null);
}

@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
try {


+ 4
- 0
app/src/main/java/com/bonait/bnframework/modules/home/fragment/MakeGoodFragment.java 查看文件

@@ -74,6 +74,7 @@ import com.bonait.bnframework.modules.home.adapter.wl_adapter;
import com.bonait.bnframework.modules.home.fragment.mode.add_makegood_control;
import com.bonait.bnframework.modules.home.fragment.mode.add_manguan_control;
import com.bonait.bnframework.modules.home.fragment.mode.add_pf_control;
import com.bumptech.glide.Glide;
import com.litao.slider.NiftySlider;
import com.orhanobut.logger.Logger;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
@@ -652,6 +653,9 @@ public class MakeGoodFragment extends BaseFragment {
public void onDestroy() {
super.onDestroy();
Logger.d("第一页销毁");

rv_right.setAdapter(null);
Glide.get(getContext()).clearMemory();
}

/**


+ 3
- 0
app/src/main/java/com/bonait/bnframework/modules/home/fragment/from/GoodPeiFangActivity.java 查看文件

@@ -64,6 +64,7 @@ import com.bonait.bnframework.modules.home.fragment.GongnengFragment;
import com.bonait.bnframework.modules.home.fragment.mode.add_good_control;
import com.bonait.bnframework.modules.home.fragment.mode.add_pf_control;
import com.bonait.bnframework.modules.home.fragment.mode.add_pf_home_control;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.HttpHeaders;
@@ -420,6 +421,8 @@ public class GoodPeiFangActivity extends BaseActivity {
@Override
public void onDestroy() {
super.onDestroy();
rv_right.setAdapter(null);
Glide.get(this).clearMemory();
}

@Override


+ 3
- 0
app/src/main/java/com/bonait/bnframework/modules/home/fragment/from/ImageChooseActivity.java 查看文件

@@ -22,6 +22,7 @@ import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.common.view.MyLayoutManager;
import com.bonait.bnframework.modules.home.adapter.image_sp_adapter;
import com.bonait.bnframework.modules.home.fragment.mode.image_sp;
import com.bumptech.glide.Glide;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;

@@ -94,6 +95,8 @@ public class ImageChooseActivity extends BaseActivity {
@Override
public void onDestroy() {
super.onDestroy();
recyclerView.setAdapter(null);
Glide.get(this).clearMemory();
}

@Override


Loading…
取消
儲存