如何解决有没有一种方法可以全面了解进程分配的所有内存?
| 首先讲一些背景故事。我的基本观点是,我的应用程序的三个主要视图都可以扩展。子视图为空,模拟和数字视图。我将这些子视图放入gridview(2x3),并将gridview放入slidedraw。这个滑动抽屉是我应用程序的关键。这是绝对必要的。滑动抽屉必须位于每个活动中,因此在活动更改时,我只是将状态存储在aapplication中,并在加载新活动时检索它。 当应用程序打开时,gridview将创建六个空视图并将其添加到其适配器。现在,当所有视图都为空时,该应用程序可以完美运行。我可以在活动中闲逛,并执行应用程序具有的所有其他功能。当我保持相同的活动时,我可以为自己的心脏内容创建模拟和数字视图。他们移动,删除并正确执行所有功能。但是,一旦我转到另一项活动,并且在gridview中甚至有一个模拟或数字视图,该应用就会通过ѭ0崩溃。 模拟视图和数字视图都会为它们自己创建两个位图。一个是视图的背景,另一个是视图的独特外观,这种外观变化很少,因此更适合用作位图。两个位图都非常小(在我的测试Evo上为221x221像素)。这使我认为我没有根据活动变化正确地回收它们。因此,我回去检查所有内容是否都已清理干净,并制定了一种完全破坏每个视图的方法。活动暂停时,每个变量都设置为null,并且所有位图都将被回收。 (注意:我使用记录器验证了onPause以及我的destroy方法确实得到了调用。) 现在-几天后-我仍然不知道为什么会引发此内存错误。我花了很多时间来查看DDMS和Memory Tracker,这很可能是有史以来最无用的东西。我完全受够了DDMS,无法通过愚蠢的事情告诉我任何有用的信息。 现在是问题了。有什么方法(方法/系统调用或其他方法)可以获取进程(我的应用程序)分配的完整列表,并可以打印/显示/保存到文件/等等...吗? 编辑1:这是对Falmarri的回应。我可能发布了很多内容,对此我深表歉意。如果您想查看更具体的内容,我很乐意为您提供帮助,那么您就没有理由破坏我的代码。 该剪辑来自BaseView:public abstract class GaugeBase extends View implements BroadcastListener {
protected static final String TAG = \"GaugeBase\";
// =======================================
// --- Declarations
/** Animation dynamics. */
protected float mTarget = 0,position = 0,velocity = 0.0f,acceleration = 0.0f;
protected long lastMoveTime = -1L;
/** Background objects. */
protected Bitmap mBackground;
protected Bitmap mFaceTexture;
protected float borderSize = 0.02f;
/** Face objects. */
protected Paint mRimShadowPaint,mTitlePaint,mFacePaint,mRimPaint,mRimBorderPaint;
protected Path mTitlePath;
/** Bounding rects. */
protected static RectF mRimRect,mFaceRect;
/** Text tools. */
protected static Typeface mTypeface;
/** The preferred size of the widget. */
private static final int mPreferredSize = 300;
/** The Broadcaster the gauge is registered to. */
protected SensorBroadcaster mCaster;
/** Is the view instantiated? */
private boolean isDestroyed = true;
// ---
// =======================================
public GaugeBase(Context context) {
super(context);
mCaster = ((AppionApplication)getContext().getApplicationContext())
.getSensorBroadcaster(AppionApplication.TEST_SENSOR);
lastMoveTime = System.currentTimeMillis();
setTarget(mCaster.getReading());
}
@Override protected void onAttachedToWindow() { super.onAttachedToWindow(); }
@Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); }
@Override protected void onSizeChanged(int w,int h,int oldw,int oldh) { regenerate(); }
@Override public void onBroadcastReceived() { setTarget(mCaster.getReading()); }
@Override protected void onMeasure(int widthMeasureSpec,int heightMeasureSpec) {
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int chosenWidth = chooseDimension(widthMode,widthSize);
int chosenHeight = chooseDimension(heightMode,heightSize);
int chosenDimension = Math.min(chosenWidth,chosenHeight);
setMeasuredDimension(chosenDimension,chosenDimension);
}
@Override protected void onDraw(Canvas canvas) {
if (isDestroyed) return;
if (mBackground == null) regenerate();
canvas.drawBitmap(mBackground,null);
canvas.save(Canvas.MATRIX_SAVE_FLAG);
canvas.scale((float)getWidth(),(float)getWidth());
drawForeground(canvas); canvas.restore(); animate();
}
public HashMap<String,Object> onSavePersistentState() {
HashMap<String,Object> mState = new HashMap<String,Object>();
mState.put(\"sensor_broadcaster\",mCaster.getBroadcasterName());
mState.put(\"type\",this.getClass().getSimpleName());
return mState;
}
public void onRestorePersistentState(HashMap<String,Object> state) {
mCaster = ((AppionApplication)getContext().getApplicationContext())
.getSensorBroadcaster((String)state.get(\"sensor_broadcaster\"));
}
private final void setTarget(float target) { mTarget = target; animate(); }
private static final int chooseDimension(int mode,int size) {
if (mode == MeasureSpec.AT_MOST || mode == MeasureSpec.EXACTLY) return size;
else return mPreferredSize;
}
private final void animate() {
if (! (Math.abs(position - mTarget) > 0.01f)) return;
if (lastMoveTime != -1L) {
long currentTime = System.currentTimeMillis();
float delta = (currentTime - lastMoveTime) / 1000.0f;
float direction = Math.signum(velocity);
if (Math.abs(velocity) < 90.0f) acceleration = 10.0f * (mTarget - position);
else acceleration = 0.0f;
position += velocity * delta;
velocity += acceleration * delta;
if ((mTarget - position) * direction < 0.01f * direction) {
position = mTarget;
velocity = 0.0f;
acceleration = 0.0f;
lastMoveTime = -1L;
} else lastMoveTime = System.currentTimeMillis();
invalidate();
} else {
lastMoveTime = System.currentTimeMillis();
animate();
}
}
public void preInit() {
mTypeface = Typeface.createFromAsset(getContext().getAssets(),\"fonts/SFDigitalReadout-Heavy.ttf\");
mFaceTexture = BitmapFactory.decodeResource(getContext().getResources(),R.drawable.gauge_face);
BitmapShader shader = new BitmapShader(mFaceTexture,Shader.TileMode.MIRROR,Shader.TileMode.MIRROR);
Matrix matrix = new Matrix();
mRimRect = new RectF(0.05f,0.05f,0.95f,0.95f);
mFaceRect = new RectF(mRimRect.left + borderSize,mRimRect.top + borderSize,mRimRect.right - borderSize,mRimRect.bottom - borderSize);
mFacePaint = new Paint();
mFacePaint.setFilterBitmap(true);
matrix.setScale(1.0f / mFaceTexture.getWidth(),1.0f / mFaceTexture.getHeight());
shader.setLocalMatrix(matrix);
mFacePaint.setStyle(Paint.Style.FILL);
mFacePaint.setShader(shader);
mRimShadowPaint = new Paint();
mRimShadowPaint.setShader(new RadialGradient(0.5f,0.5f,mFaceRect.width() / 2.0f,new int[] { 0x00000000,0x00000500,0x50000500 },new float[] { 0.96f,0.96f,0.99f },Shader.TileMode.MIRROR));
mRimShadowPaint.setStyle(Paint.Style.FILL);
mRimPaint = new Paint();
mRimPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
mRimPaint.setShader(new LinearGradient(0.4f,0.6f,1.0f,Color.rgb(0xff0,0xf5,0xf0),Color.rgb(0x30,0x31,0x30),Shader.TileMode.CLAMP));
mRimBorderPaint = new Paint();
mRimBorderPaint.setAntiAlias(true);
mRimBorderPaint.setStyle(Paint.Style.STROKE);
mRimBorderPaint.setColor(Color.argb(0x4f,0x33,0x36,0x33));
mRimBorderPaint.setStrokeWidth(0.005f);
mTitlePaint = new Paint();
mTitlePaint.setColor(0xff000000);
mTitlePaint.setAntiAlias(true);
mTitlePaint.setTypeface(mTypeface);
mTitlePaint.setTextAlign(Paint.Align.CENTER);
mTitlePaint.setTextSize(0.2f);
mTitlePaint.setTextScaleX(0.8f);
// Now we prepare the gauge
init();
isDestroyed = false;
}
/** Update the gauge independent static buffer cache for the background. */
private void regenerate() {
if (isDestroyed) return;
if(mBackground != null) { mBackground.recycle(); mBackground = null; }
// Our new drawing area
mBackground = Bitmap.createBitmap(getWidth(),getHeight(),Bitmap.Config.ARGB_8888);
Canvas backCanvas = new Canvas(mBackground);
float scale = (float)getWidth();
backCanvas.scale(scale,scale);
drawRim(backCanvas);
drawFace(backCanvas);
drawTitle(backCanvas);
if (!(this instanceof EmptySpace)) { mCaster.getGroup().draw(backCanvas); }
regenerateBackground(backCanvas);
}
/** Prepare the view to be cleaned up. This is called to prevent memory leaks. */
public void destroy() {
isDestroyed = true;
if (mFaceTexture != null) { mFaceTexture.recycle(); mBackground = null; }
if (mBackground != null) { mBackground.recycle(); mBackground = null; }
mRimShadowPaint = null;
mRimShadowPaint = null;
mFacePaint = null;
mRimPaint = null;
mRimBorderPaint = null;
mTitlePath = null;
mRimRect = null; mFaceRect = null;
mTypeface = null;
destroyDrawingCache();
}
/**
* Create a bitmap of the gauge. The bitmap is to scale.
* @return The bitmap of the gauge.
*/
int tobitmap = 0;
public Bitmap toBitmap() {
Bitmap b = Bitmap.createBitmap(getWidth(),Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas();
canvas.setBitmap(b);
draw(canvas);
return b;
}
/** Update the gauge dependent static buffer cache for the background. */
protected abstract void regenerateBackground(Canvas canvas);
/** Initializes all of the objects the gauge widget will need before use. */
protected abstract void init();
/** This is called when drawing the background. Draws the bordered edge of the gauge. */
protected abstract void drawRim(Canvas canvas);
/** This is called when drawing the background. Draws the face of the gauge. */
protected abstract void drawFace(Canvas canvas);
/** This is called when drawing the background. Draws the title to the gauge. */
protected abstract void drawTitle(Canvas canvas);
/**
* This is called when drawing the foreground. The foreground includes items like the
* scale of an analog gauge,or the text of a digital gauge. Also any other necessary
* items that need drawing go here. Note: drawForeground is called quickly,repeatedly,* make it run fast and clean.
*/
protected abstract void drawForeground(Canvas canvas);
}
这是从数字视图来看的:(因为它较小并且仍然会导致错误)
public class DigitalGauge extends GaugeBase {
// ================================
// --- Drawing tools
private RectF lcdRect;
private Paint lcdPaint,detailPaint;
private Path facePath,borderPath;
// ---
// ================================
public DigitalGauge(Context context) {
super(context);
}
@Override protected void regenerateBackground(Canvas canvas) { }
@Override protected void init() {
lcdPaint = new Paint();
lcdPaint.setColor(0xff000000);
lcdPaint.setAntiAlias(true);
lcdPaint.setStrokeWidth(0.005f);
lcdPaint.setTextSize(0.4f);
lcdPaint.setTypeface(mTypeface);
lcdPaint.setTextAlign(Paint.Align.CENTER);
detailPaint = new Paint();
detailPaint.setColor(0xff000000);
detailPaint.setTextSize(0.2f);
detailPaint.setStrokeWidth(0.005f);
detailPaint.setAntiAlias(true);
detailPaint.setTypeface(mTypeface);
detailPaint.setTextScaleX(0.8f);
detailPaint.setTextAlign(Paint.Align.CENTER);
facePath = new Path();
facePath.moveTo(0.12f,0.0f);
facePath.lineTo(0.88f,0.0f);
facePath.arcTo(new RectF(),90);
// TODO Make the trapazoidal look of the digital gauge
lcdRect = new RectF(mFaceRect.left + borderSize,mFaceRect.top + borderSize,mFaceRect.right - borderSize,mFaceRect.top - borderSize - lcdPaint.getTextSize());
}
@Override protected void drawRim(Canvas canvas) {
canvas.drawRect(mRimRect,mRimPaint);
canvas.drawRect(mRimRect,mRimBorderPaint);
}
@Override protected void drawFace(Canvas canvas) {
canvas.drawRect(mFaceRect,mFacePaint);
canvas.drawRect(mFaceRect,mRimBorderPaint);
}
@Override protected void drawTitle(Canvas canvas) {
canvas.drawText(mCaster.getBroadcasterSerial(),mFaceRect.left - 0.1f,mFaceRect.top + 0.1f,mTitlePaint);
}
@Override protected void drawForeground(Canvas canvas) {
String display = \"000000\" + String.valueOf(Math.ceil(position));
String read = display.substring(display.length()-8,display.length() - 2);
canvas.drawText(read,lcdRect.top + lcdPaint.getTextSize() / 2,lcdPaint);
/**canvas.drawText(mContext.getResources().getStringArray(R.array.pressureTypes)[measurement],lcdRect.top + lcdPaint.getTextSize(),detailPaint);*/
}
}
至于通过应用程序的状态,我将视图的类型和该视图所代表的Caster的字符串名称放入哈希映射中。我将该哈希图传递给gridview,然后将所有六个地图放入一个数组,该数组将表示gridview中视图的位置。然后将该数组保存在应用程序中,并根据需要进行检索。
这是gridview。我考虑的更多,这堂课是我认为可能存在问题的地方。
public class Workbench extends GridView {
/** Our debugging tag */
private static final String TAG = \"Workbench\";
/** Name of the Workbench. */
private String mId = \"-1\";
/** The title of the Workbench. */
private String mTitle = \"Workbench\";
/** The list of Widgets that will be handled by the bench */
private GaugeBase[] mContent = new GaugeBase[6];
/** The current selection from the bench */
private int mSelection = -1;
/** When a GaugeBase is moves we want to remove from the adapter. Now we won\'t lose it.*/
private GaugeBase mHeldGaugeBase = null;
private Bitmap mHold = null;
private boolean mIsHolding = false;
private float x = -1000f,y = -1000f; // Where the held bitmap should be
private Bitmap trash;
private RectF trashBox;
// The touch listener we will use if we need to move a widget around
private OnTouchListener mWidgetExchanger = new OnTouchListener() {
@Override public boolean onTouch(View v,MotionEvent e) {
int w = getWidth(); int h = getHeight();
float xx = e.getX(); float yy = e.getY();
switch (e.getAction()) {
case MotionEvent.ACTION_DOWN: // Fall through
case MotionEvent.ACTION_MOVE:
if (mIsHolding) {
x = e.getX() - mHold.getWidth()/2; y = e.getY() - mHold.getHeight()/2;
postInvalidate(); break;
}
case MotionEvent.ACTION_UP:
if (mIsHolding) {
if (trashBox.contains(xx,yy)) removeGaugeBase(mSelection);
else {
if ((xx < w / 2) && (yy < h /3)) makeSwitch(0);
else if ((xx > w / 2) && (yy < h /3)) makeSwitch(1);
else if ((xx < w / 2) && (yy > h /3) && (yy < h * .666)) makeSwitch(2);
else if ((xx > w / 2) && (yy > h /3) && (yy < h * .666)) makeSwitch(3);
else if ((xx < w / 2) && (yy > h *.666)) makeSwitch(4);
else if ((xx > w / 2) && (yy > h *.666)) makeSwitch(5);
}
mSelection = -1;
//mHeldGaugeBase.destroy(); mHeldGaugeBase = null;
mHold.recycle(); mHold = null;
trash.recycle(); trash = null;
mIsHolding = false;
setOnTouchListener(null);
x = -1000f; y = -1000f;
((AppionApplication)getContext().getApplicationContext()).vibrate(200); update();
}
break;
}
return true;
}
};
public Workbench(Context context) { this(context,null); }
public Workbench(Context context,AttributeSet attrs) { this(context,attrs,0); }
public Workbench(Context context,AttributeSet attrs,int defStyle) {
super(context,defStyle);
for (int i = 0; i < mContent.length; i++) {
mContent[i] = new EmptySpace(getContext());
}
setAdapter(new BenchAdapter());
this.setOnItemClickListener(new OnItemClickListener() {
@Override public void onItemClick(AdapterView<?> arg0,View view,final int pos,long arg3) {
if (mContent[pos] instanceof EmptySpace) {
CharSequence[] items = {\"Analog\",\"Digital\"};
AlertDialog.Builder adb = new AlertDialog.Builder(getContext());
adb.setTitle(\"Add a widget?\")
.setItems(items,new DialogInterface.OnClickListener () {
@Override public void onClick(DialogInterface arg0,int position) {
mContent[pos].destroy();
mContent[pos] = null;
SensorBroadcaster s = ((AppionApplication)getContext().getApplicationContext()).
getSensorBroadcaster(AppionApplication.TEST_SENSOR);
switch (position) {
case 0: // Add an Analog GaugeBase to the Workbench
mContent[pos] = new AnalogGauge(getContext());
// TODO: Option to link to a manager
break;
case 1: // Add a digital GaugeBase to the Workbench
mContent[pos] = new DigitalGauge(getContext());
// TODO: Option to link to a manager
break;
} mContent[pos].preInit();
update();
}
});
adb.show();
} //else new GaugeBaseDialog(getContext(),Workbench.this,(GaugeBase)view,pos).show();
}
});
setOnItemLongClickListener(new OnItemLongClickListener() {
@Override public boolean onItemLongClick(AdapterView<?> arg0,View arg1,int pos,long arg3) {
mSelection = pos;
mHold = mContent[pos].toBitmap();
mHeldGaugeBase = mContent[pos];
mHeldGaugeBase.destroy();
trash = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(getContext().getResources(),R.drawable.trash),getWidth() / 10,getHeight() / 10,true);
trashBox = new RectF(getWidth() / 2 - trash.getWidth()/2,getHeight() - trash.getHeight(),getWidth() /2 + trash.getWidth() /2,getHeight());
mContent[pos] = new EmptySpace(getContext());
update();
mIsHolding = true;
setOnTouchListener(mWidgetExchanger);
((AppionApplication)getContext().getApplicationContext()).vibrate(300);
return false;
}
});
}
/**
* Perform a switch in within the bench. Exchange on slot with another.
* @param slot The slot of the widgets list that we are switching to.
*/
public void makeSwitch(int slot) {
if (mSelection == -1) return;
Log.i(TAG,\"Performing a Widget switch\");
mContent[mSelection].destroy();
mContent[mSelection] = mContent[slot];
mContent[slot] = mHeldGaugeBase;
mContent[slot].preInit();
mContent[slot].invalidate();
Log.d(TAG,\" mSelection = \" + mContent[mSelection] + \" slot = \" +mContent[slot]);
update();
}
解决方法
这是对@mah的回应,但是评论太长了。
它总是以
系统页面大小
这不一定是真的。特别是使用Android应用程序。有许多具有不同语义的不同内存分配器。但是,假设您是在谈论JAVA,而不是NDK(C ++),那么透明度甚至更低。 Java的虚拟机(或更确切地说是dalvik)几乎肯定会在计算机启动时过度分配内存,然后当应用程序请求少量内存时,它将从该池中为您提供内存。
如果其池中的内存不足,它将从操作系统中分配另一个块,并将其添加到其池中,然后从那里返回一个块。
但是,如果您请求大的内存块,例如您想要一个位图,则JVM(或dalvik机器)很可能会使用系统的
mmap
方法,该方法映射一部分内存。根据实际情况,它可以制作一个私有的匿名地图,然后让您访问其中的各个部分。或者,它可以将文件映射到内存,这基本上是磁盘上的内容的内存视图。 dalvic可能就是这样处理大型位图分配的。
并提出了一种完全
破坏了每个视图
首先,您真的无法直接控制Java。将对象设置为null不会删除它。即使您假定仅对该对象有一个引用,您也必须等到垃圾回收器清理对象的数据。
真的不可能告诉您问题所在,甚至是提示。我只能说的是,您可能在比您实际需要的更多的地方分配了位图空间。或者,您将引用保留在未清除的地方。
我只是将状态存储在
应用程序,并在
新的活动负载。
这是相当模糊的,但是我先来看一下您在做什么。例如,如果您将位图作为可解析的对象传递,则可能会根据需要分配3-4倍的空间。通过可解析的接口发送大型自定义对象和位图非常昂贵。
我建议一些事情之一。您都可以延迟加载位图。也就是说,不要将它们存储在任何地方。仅在需要时将它们拉起。这可能是一个解决方案,因为您可能认为自己的性能超出了编译器。但是,我保证编译器在有效使用内存方面比您更聪明。
-
或者,您可以尝试相反的操作,并且仅在应用程序加载时加载位图,并确保每次显示时都不会创建新的位图或其他任何内容。这样,它仅在内存中存在一次,并且如果确实太大,您将尽早崩溃并到达已知的位置。
-
最后,如果您确实找不到解决方案,并且您确实认为Java进程确实内存不足,则可以重新编写NDK中处理位图视图的部分。这样,您无需明确地进行处理就不会对它们进行垃圾收集和重新创建。
-
现在是问题了。有办法吗
(方法/系统调用等)
我可以得到完整的清单
进程的分配(我的应用)和
打印/显示/保存到文件/
等等...吗?
我确定有。但是,这很大,但绝非易事。您可能需要做的就是用跟踪谁请求内存的版本替换系统的glibc(即malloc函数)。但是,即使这样也会被Java虚拟机混淆。
长话短说,发布一些代码,尤其是要处理和保存视图和位图的部分。
更新:
仅仅看一下您的代码,我就会检查ѭ5的调用频率,尤其是因为这个原因:
mBackground = Bitmap.createBitmap(getWidth(),getHeight(),Bitmap.Config.ARGB_8888);
Canvas backCanvas = new Canvas(mBackground);
我不是Java位图内存管理方面的专家,但我想那会很昂贵。
, 我建议您看一下这个视频。
它在很多方面都给了我帮助,我也遇到了位图大小和虚拟机内存预算的问题。
从我的经验来看:我养成了在.recycle()之后到处调用System.gc()的坏习惯。我知道这样做不好,但是经过数小时的调试,为什么我的位图没有得到正确的回收,它还是帮助我防止了强制关闭。
,您可以查看/ proc / self / maps(在进程内)或/ proc / [process id] / maps,但这不可能告诉您您想要什么,并且不会进行系统调用。当您在进程内分配内存时,即使只分配1个字节,它总是以系统页面大小的倍数执行(4kb,也许更多),但是它将在内部进行管理。在从系统接收更多内存之前,将来的分配来自该块。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。