Android的:如何释放资源,当应用程序终止? [英] Android: How to release resources when the application terminates?

查看:167
本文介绍了Android的:如何释放资源,当应用程序终止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了使用相机的应用程序和参加办法在执行过程中,屏幕始终打开。

I created an application which uses camera and during the appplication execution the screen is always on.

在OnCreate()方法,我加了锁:

In the onCreate() method I added the lock:

final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
this.mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
this.mWakeLock.acquire();

这是被覆盖的的onStop()方法:

And this is the overriden onStop() method:

@Override
protected void onStop() {

	if(mWakeLock.isHeld())
	{
		mWakeLock.release();
	}

	super.onStop();
}

但屏幕仍然在所有的时间申请终止后,如果我跑了相机的应用程序遇到这显然会出现,因为相机的资源没有释放一个错误。

But after the application termination the screen remains on all the time and if I run the camera application it encounters an error which obviously appears because the camera resources are not released.

有谁知道如何释放在应用程序终止所有资源?

Does anyone know how to release all resources on application termination?

推荐答案

我想从的OnCreate()将锁定 OnResume()。您希望看到生命周期的活动,而不是活动的整个生命周期中锁定。您活动可以definetly仍然运行在其前面的另一个活动上运行。

I would move the lock from OnCreate() to OnResume(). You want the lock during the visible lifetime of the Activity, not the entire lifetime of the Activity. You Activity could definetly still be running with another Activity running in front of it.

我会提出正式发布将OnPause()将OnPause()是最早的点您的应用程序通常应该由OS杀死。

I would move the release to OnPause(). OnPause() is the earliest point your application should normally be killed by the OS.

此外,我也不会检查,看看我是否在释放之前有锁。如果你使用 OnResume()获取锁; isHeld 应始终将OnPause真()

Additionally, I wouldn't check to see if I have the lock before releasing. If you use OnResume() to acquire the lock; isHeld should always be true in OnPause().

这篇关于Android的:如何释放资源,当应用程序终止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆