activity finish中finish和onDestroy的区别

8353人阅读
android 小技巧记录(9)
&这两天在弄android,遇到一个问题:所开发的小游戏中有背景音乐,玩的过程中始终有音乐在放着,然后在我退出游戏后,音乐还在播放!
  我看了一下我最开始写的退出游戏的代码,就是简单的finish()语句。我想应该是这个地方出了问题。后来想了想,以前好像见过有用System.exit(0)退出游戏的,然后就尝试了一下,发现问题果然解决了。
  现在来彻底弄清楚两者的区别。
  首先一个Activity是有生命周期的,onCreate,onStart,onResume,onPause,onStop,onDestroy...
  finish是Activity的类,仅仅针对Activity,当调用finish()时,只是将活动推向后台,并没有立即释放内存,活动的资源并没有被清理;当调用System.exit(0)时,杀死了整个进程,这时候活动所占的资源也会被释放。
  其实android的机制决定了用户无法完全退出应用,当你的application最长时间没有被用过的时候,android自身会决定将application关闭了。
------------------------------------------------------------------------------------------------------------
做Android开发不可避免会出现退出UI或者程序的问题。
如果退出当前运行的Activity,可以使用&& this.finish() 或者 System.exit(0) 。
如果退出整个程序,如下操作:
Intent intent=new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.startActivity(intent);
System.exit(0);
android.os.Process.killProcess(android.os.Process.myPid());
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:294995次
积分:3754
积分:3754
排名:第5459名
原创:68篇
转载:27篇
评论:162条
(1)(1)(3)(2)(1)(2)(1)(1)(1)(4)(1)(2)(1)(1)(4)(3)(1)(1)(2)(2)(7)(6)(6)(21)(6)(1)(1)(2)(2)(2)(1)(2)(1)(1)(1)finish/onDestroy/System.exit()的区别 - 沙翁 - 博客园
向昨天要经验;
向今天要结果;
向明天要动力
  Activity.finish():Call this when your activity is done and should be closed.   在你的activity动作完成的时候,或者Activity需要关闭的时候,调用此方法。  当你调用此方法的时候,系统只是将最上面的Activity移出了栈,并没有及时的调用onDestory()方法,其占用的资源也没有被及时释放。因为移出了栈,所以当  你点击手机上面的&back&按键的时候,也不会再找到这个Activity。
  Activity.onDestory():the system is temporarily destroying this instance of the activity to save space.  系统销毁了这个Activity的实例在内存中占据的空间。  在Activity的生命周期中,onDestory()方法是他生命的最后一步,资源空间等就被回收了。当重新进入此Activity的时候,必须重新创建,执行onCreate()方法。
  System.exit(0):退出整个应用程序,是针对整个Application的,将整个进程直接Kill掉。
  finish函数仅仅把当前Activity退出了,但是并没有释放他的资源。
  安卓系统自己决定何时从内存中释放应用程序。当系统没有可用内存到时候,会按照优先级,释放部分应用。
  转:http://blog.csdn.net/imzoer/article/details/9380807<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
您的访问请求被拒绝 403 Forbidden - ITeye技术社区
您的访问请求被拒绝
亲爱的会员,您的IP地址所在网段被ITeye拒绝服务,这可能是以下两种情况导致:
一、您所在的网段内有网络爬虫大量抓取ITeye网页,为保证其他人流畅的访问ITeye,该网段被ITeye拒绝
二、您通过某个代理服务器访问ITeye网站,该代理服务器被网络爬虫利用,大量抓取ITeye网页
请您点击按钮解除封锁&09:53 提问
这个activity finish 后 为什么内存没被回收 ?谁阻止了回收?!!!
public class LoginActivity extends FragmentActivity {
UMSocialService mController = UMServiceFactory.getUMSocialService("com.umeng.login");
@InjectView(R.id.photo_welcome)
RoundedImageView photoW
@InjectView(R.id.photo_welcome_con)
FrameLayout photoWelcomeC
@InjectView(R.id.photo_slogan)
ImageView photoS
@InjectView(R.id.login_type_title)
TextView loginTypeT
@InjectView(R.id.login_type_title_con)
FrameLayout loginTypeTitleC
@InjectView(R.id.btn_mobile)
FloatingActionButton btnM
@InjectView(R.id.btn_wechat)
FloatingActionButton btnW
@InjectView(R.id.btn_sina)
FloatingActionButton btnS
@InjectView(R.id.btn_qq)
FloatingActionButton btnQq;
@InjectView(R.id.action_con)
LinearLayout actionC
@InjectView(R.id.real_con)
LinearLayout realC
private Activity mC
private RoundProgressDialog nP
private SHARE_MEDIA[] mPlatformsM
public String deviceToken = "";
private Timer tokenT
private int waitTime = 120;
private int tokenCount = 0;
private View.OnLongClickListener toggleServer = new View.OnLongClickListener() {
public boolean onLongClick(View v) {
if (SystemUtils.debug) {
ApiUtils.mDomain = ApiUtils.testDomain.equalsIgnoreCase(ApiUtils.mDomain) ? ApiUtils.realDomain : ApiUtils.testD
BuyueApp.get().setTestMode(ApiUtils.testDomain.equalsIgnoreCase(ApiUtils.mDomain));
SystemUtils.showMsg("change to: \n " + ApiUtils.mDomain, mContext);
EventDao evtDao = new EventDao(BuyueApp.get().getApplicationContext());
BoardDao boardDao = new BoardDao(BuyueApp.get().getApplicationContext());
CardDao cardDao = new CardDao(BuyueApp.get().getApplicationContext());
SyncDao syncDao = new SyncDao(BuyueApp.get().getApplicationContext());
syncDao.markDirty(Sync.EVENT);
syncDao.markDirty(Sync.BOARD);
evtDao.deleteAll();
boardDao.deleteAll();
cardDao.deleteAll();
} catch (SQLException e) {
SystemUtils.attemptPrintError(e);
@SuppressLint("NewApi")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = LoginActivity.
BuyueApp.get().addActivity(LoginActivity.this);
setContentView(R.layout.activity_login);
ButterKnife.inject(this);
//首次执行导入.db文件
DataManager dbHelper = new DataManager(this);
dbHelper.openDatabase();
dbHelper.closeDatabase();
umeng message
PushAgent mPushAgent = PushAgent.getInstance(mContext);
mPushAgent.enable();
umeng analytics
MobclickAgent.updateOnlineConfig(mContext);
umeng upadate
UmengUpdateAgent.update(this);
UmengUpdateAgent.setUpdateOnlyWifi(false);
deviceToken = "";
tokenTimer = new Timer();
TimerTask tokenTask = new TimerTask() {
public void run() {
if (deviceToken != null && !"".equalsIgnoreCase(deviceToken)) {
SpUtils.setSpStr(SpUtils.TEP_TOKEN,deviceToken);
tokenTimer.cancel();
deviceToken = UmengRegistrar.getRegistrationId(mContext);
tokenCount++;
if (tokenCount & 300) {
tokenTimer.cancel();
tokenTimer.schedule(tokenTask, 0, 100);
PushAgent.getInstance(mContext).onAppStart();
FileUtils.deleteSave();
FileUtils.clearCache();
regCasts();
adjustMyLayout();
initLogin();
TextView typeTitle = (TextView) findViewById(R.id.login_type_title);
typeTitle.setOnLongClickListener(toggleServer);
private void adjustMyLayout() {
private void regCasts() {
SystemUtils.registerReceiver(receiver, NameUitls.ACTION_DO_LOGIN, mContext);
SystemUtils.registerReceiver(finishReceiver, NameUitls.ACTION_LOGOUT, mContext);
SystemUtils.registerReceiver(timeOutReceiver, NameUitls.ACTION_TIMEOUT, mContext);
private void unRegCasts() {
SystemUtils.unregisterReceiver(receiver, mContext);
SystemUtils.unregisterReceiver(finishReceiver, mContext);
SystemUtils.unregisterReceiver(timeOutReceiver, mContext);
private void initPlatformMap() {
mPlatformsMap = new SHARE_MEDIA[]{SHARE_MEDIA.GOOGLEPLUS, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.SINA, SHARE_MEDIA.QQ};
按赞数排序
没人回答么!!!!!!!
private void initLogin() {
initPlatformMap();
LinearLayout actionCon = (LinearLayout) findViewById(R.id.action_con);
int len = actionCon.getChildCount();
String appId = Config.WX_APPID;
String appSecret = Config.WX_APPSERCRET;
UMWXHandler wxHandler = new UMWXHandler(LoginActivity.this, appId, appSecret);
wxHandler.addToSocialSDK();
mController.getConfig().setSsoHandler(new SinaSsoHandler());
String qqId = Config.QQ_APPID;
String qqKey = Config.QQ_APPKEY;
UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(LoginActivity.this, qqId, qqKey);
qqSsoHandler.addToSocialSDK();
mController.getConfig().addFollow(SHARE_MEDIA.SINA, Config.SINA_ID);
btnMobile.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
v.setEnabled(false);
Intent intent = new Intent();
intent.putExtra("umtoken",deviceToken);
intent.setClass(LoginActivity.this, SignMainActivity.class);
startActivity(intent);
NameUitls aboutUs = NameUitls.newInstance();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
aboutUs.show(ft, FRAG_SIGN_MAIN);
v.setEnabled(true);
btnMobile.setOnTouchListener(SystemUtils.TouchDark);
for (int i = 1; i & i++) {
FloatingActionButton btn = (FloatingActionButton) ((FrameLayout) actionCon.getChildAt(i)).getChildAt(0);
final int finalI =
final SHARE_MEDIA path = mPlatformsMap[finalI];
btn.setOnTouchListener(SystemUtils.TouchDark);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
disableBtns();
if (SystemUtils.isUnConnected(mContext)) {
SystemUtils.showMsg(mContext.getString(R.string.msg_net_timeout), mContext);
enableBtns();
attemptShowProgress("登录中", waitTime);
mController.doOauthVerify(LoginActivity.this, path, new SocializeListeners.UMAuthListener() {
public void onComplete(final Bundle value, SHARE_MEDIA share_media) {
progressDialog = ToolUtils.showRoundProgress("登录中", mContext);
if (value != null && !TextUtils.isEmpty(value.getString("uid"))) {
mController.getPlatformInfo(LoginActivity.this, path, new SocializeListeners.UMDataListener() {
public void onComplete(int status, Map&String, Object& info) {
if (status == 200 && info != null) {
User user =
switch (finalI - 1) {
user = SdkUtils.getUserFromWechat(info, deviceToken);
user = SdkUtils.getUserFromWeibo(info, deviceToken);
String puid = value.getString("uid");
user = SdkUtils.getUserFromQq(info, puid, deviceToken);
Boolean result = DataCenter.login(user, mContext);
dealLogin(result);
} catch (NullPointerException e) {
dealLogin(false);
prepareLogin();
public void onStart() {
prepareLogin();
SystemUtils.showMsg("授权失败,请稍后重试", mContext);
public void onStart(SHARE_MEDIA share_media) {
public void onError(SocializeException e, SHARE_MEDIA share_media) {
prepareLogin();
public void onCancel(SHARE_MEDIA share_media) {
prepareLogin();
if (BuyueApp.get().authed()) {
DataCenter.login(BuyueApp.get().getUser(), mContext, true);
Intent toMain = new Intent();
toMain.setClass(mContext, MainActivity.class);
toMain.putExtra(NameUitls.NEED_LOGIN_XMPP, true);
LoginActivity.this.startActivity(toMain);
LoginActivity.this.finish();
if (BuyueApp.get().getUser() != null && DataUtils.notZero(String.valueOf(BuyueApp.get().getUser().getId()))) {
attemptShowProgress("登录中", 30);
boolean result = DataCenter.login(BuyueApp.get().getUser(), mContext);
dealLogin(result);
public void dealLogin(boolean result) {
if (result == Boolean.TRUE) {
attemptShowProgress("登录中", waitTime);
SystemUtils.dismissDialog(nProgress);
SystemUtils.showMsg(R.string.msg_net_timeout, mContext);
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
UMSsoHandler ssoHandler = mController.getConfig().getSsoHandler(requestCode);
if (ssoHandler != null) {
ssoHandler.authorizeCallBack(requestCode, resultCode, data);
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
BuyueApp.get().onTerminate();
return super.onKeyDown(keyCode, event);
private BroadcastReceiver receiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
SystemUtils.dismissDialog(nProgress);
String ret = intent.getStringExtra("ret");
String data = intent.getStringExtra("data");
if (ApiUtils.RET_S.equalsIgnoreCase(ret)) {
Intent toMain = new Intent();
toMain.setClass(mContext, MainActivity.class);
toMain.putExtra(NameUitls.NEED_LOGIN_XMPP, true);
LoginActivity.this.startActivity(toMain);
LoginActivity.this.finish();
SystemUtils.showMsg(data, mContext);
enableBtns();
private BroadcastReceiver finishReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
SystemUtils.dismissDialog(nProgress);
private BroadcastReceiver timeOutReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
SystemUtils.dismissDialog(nProgress);
SystemUtils.showMsg(R.string.msg_net_timeout, mContext);
enableBtns();
protected void onResume() {
enableBtns();
tokenCount = 0;
super.onResume();
SystemUtils.bindLocation(mContext);
MobclickAgent.onResume(this);
public void onPause() {
super.onPause();
SystemUtils.unbindLocation(mContext);
MobclickAgent.onPause(this);
protected void onNewIntent(Intent intent) {
enableBtns();
protected void onDestroy() {
SystemUtils.dismissDialog(nProgress);
unRegCasts();
BuyueApp.get().removeActivity(LoginActivity.this);
super.onDestroy();
SystemUtils.debugLog("test-cache","login destroy",BuyueApp.get().getActivitys()+"");
private void disableBtns() {
btnQq.setEnabled(false);
btnWechat.setEnabled(false);
btnSina.setEnabled(false);
private void enableBtns() {
btnQq.setEnabled(true);
btnWechat.setEnabled(true);
btnSina.setEnabled(true);
private void prepareLogin() {
enableBtns();
SystemUtils.dismissDialog(nProgress);
private void attemptShowProgress(String msg, int waitTime) {
SystemUtils.dismissDialog(nProgress);
nProgress = ToolUtils.showRoundProgress(msg, mContext, waitTime);
夜深了 代码没看
activity在创建界面的时候,由setContentView创建一个主view(即绘制整个界面的父view),由于在finish的时候,这个view还持有activity的引用,因此activity无法被回收,造成内存泄漏
如果是这种情况,可以找我探讨一下~
大神,我也遇到同样的问题,求帮助qq
78关注|465收录
20关注|288收录
629关注|316收录
其他相似问题
相关参考资料Activity中finish()和onDestroy()的区别
finish()方法用于结束一个Activity的生命周期,而onDestory()方法则是Activity的一个生命周期方法,其作用是在一个Activity对象被销毁之前,Android系统会调用该方法,用于释放此Activity之前所占用的资源。
finish会调用到onDestroy方法,
可以在onDestroy里打印一句话,就会发现在finish方法那也会打印这句话。。。
Activity.finish()
Call this when
your activity is done and should be closed.
在你的activity动作完成的时候,或者Activity需要关闭的时候,调用此方法。
当你调用此方法的时候,系统只是将最上面的Activity移出了栈,并没有及时的调用onDestory()方法,其占用的资源也没有被及时释放。因为移出了栈,所以当你点击手机上面的“back”按键的时候,也不会再找到这个Activity。
Activity.onDestory()
the system is
temporarily destroying this instance of the activity to save
系统销毁了这个Activity的实例在内存中占据的空间。
在Activity的生命周期中,onDestory()方法是他生命的最后一步,资源空间等就被回收了。当重新进入此Activity的时候,必须重新创建,执行onCreate()方法。&
注:出自网络。感谢原作者的分享!
已投稿到:
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。

我要回帖

更多关于 finishactivity用法 的文章

 

随机推荐