退出应用的第N+1种方法-一行代码退出应用

退出应用的第N+1种方法

前N种方法

之前有在网上了解过退出应用的方法,其中包括在每个activity中注册关闭界面的广播接受者,当想推出应用时发一条广播关闭所有的界面,最常用的使用list去模拟任务栈的来管理activity,要退出应用使用遍历关闭所有activity。当然也有人发散思维用抛异常来结束。还有人就说用 startActivityForResult开启每个activity,然后再onActivityResult里面关闭每个界面。方法多种多样,大家都可以在网上搜,在这里作者就不再赘述,下面就有来读者介绍第N+1种方法

finishAffinity()介绍

第N+1方法的核心就是finishAffinity()方法,下面是官方的解释:

    Finish this activity as well as all activities immediately below it in the current task that have the same affinity. This is typically used when an application can be launched on to another task (such as from an ACTION_VIEW of a content type it understands) and the user has used the up navigation to switch out of the current task and in to its own task. In this case, if the user has navigated down into any other activities of the second application, all of those should be removed from the original task as part of the task switch.
    Note that this finish does not allow you to deliver results to the previous activity, and an exception will be thrown if you are trying to do so.

英语好的可以可以直接看上面的英语介绍,如果英语不好,笔者就用大学里四级没过的英语水平给大家翻一下,如果不对,还请大家批评指正。下面是翻译

Finish this activity as well as all activities immediately below it in the current task that have the same affinity.
关闭一个activity之后立即关闭当前任务栈中他下面那个具有相同血缘关系的activity的
This is typically used when an application can be launched on to another task
这个方法可以用来当一个应用想跳往另外一个栈时
(such as from an ACTION_VIEW of a content type it understands)
这句话太难,就当楼主没看见
and the user has used the up navigation to switch out of the current task and in to its own task.
和用户想跳出当前的栈并跳到自己的栈时
In this case,
既然这样
if the user has navigated down into any other activities of the second application,
如果用户已经跳往另外一个应用的activitys
all of those should be removed from the original task as part of the task switch.
所有的这个应用的activitys将会被移除
Note that this finish does not allow you to deliver results to the previous activity,
注意,这个方法不允许你返回结果给前一个activity,
 and an exception will be thrown if you are trying to do so.
如果你这样做的话会抛出异常

以上就是‘ finishAffinity()’的介绍,下面我们直接上代码。

退出应用实例

首先建立一个BaseActivity,然后建立四个继承自BaseActivity的Activity,项目结构如下图:

BaseActivity代码非常简单,代码如下:

package com.zhuyux.csdntest;

import android.app.Activity;

/**
 * Created by xiaozhu on 2016/7/20.
 */
public class BaseActivity extends Activity {
}

子Activity的代码如下

package com.zhuyux.csdntest;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends BaseActivity implements View.OnClickListener {

private Button open;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    initView();
}

private void initView() {
    open = (Button) findViewById(R.id.open);

    open.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.open:
            startActivity(new Intent(MainActivity.this,SecondActivity.class));
            break;
    }
}

}

子Activity的布局文件如下

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.zhuyux.csdntest.MainActivity">

   <Button
       android:id="@+id/open"
       android:textSize="25dp"
       android:text="k开启"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content" />
</RelativeLayout>

最后一个的Activity的代码如下

package com.zhuyux.csdntest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class FourActivity extends AppCompatActivity implements View.OnClickListener {

private Button close;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_four);
    initView();
}

private void initView() {
    close = (Button) findViewById(R.id.close);

    close.setOnClickListener(this);
}

@SuppressLint("NewApi")
@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.close:
            //退出应用核心类
            finishAffinity();
            break;
    }
}
}

最后一个Activity的布局文件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.zhuyux.csdntest.FourActivity">
    <Button
        android:id="@+id/close"
        android:textSize="25dp"
        android:text="关闭"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</RelativeLayout>

别忘记载清单文件中注册,运行依次点击按钮,就会跳到最后一个界面

如图

点击关闭按钮,则退出应用。感觉是不是很简单\

异常现象

回到官方的介绍最后一句

Note that this finish does not allow you to deliver results to the previous activity,
注意,这个方法不允许你返回结果给前一个activity,
and an exception will be thrown if you are trying to do so.
如果你这样做的话会抛出异常

什么情况下会出异常呢?首先,我们修改一下ThirstActivity里面的代码,把里面的代码

startActivity(new Intent(ThirstActivity.this,FourActivity.class));

替换成

startActivityForResult(new Intent(ThirstActivity.this,FourActivity.class),0);

并添加以下代码

 @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
    if (data!=null){
     Toast.makeText(ThirstActivity.this,     ""+data.getStringExtra("data"), Toast.LENGTH_SHORT).show();
        }
}

然后再FourActivity中 finishAffinity();之前添加如下代码

 Intent intent = getIntent();
 intent.putExtra("data","我返回结果了");
 setResult(2,intent);

点击关闭,就会报一下异常

当然这丝毫不影响我们使用,因为我们的目的是推出应用,而不是返回结果给项目中的某个界面

时间: 2024-08-08 05:24:06

退出应用的第N+1种方法-一行代码退出应用的相关文章

Android-完全退出当前应用程序的四种方法

Android程序有很多Activity,比如说主窗口A,调用了子窗口B,如果在B中直接finish(), 接下里显示的是A.在B中如何关闭整个Android应用程序呢?本人总结了几种比较简单的实现方法. 1. Dalvik VM的本地方法 android.os.Process.killProcess(android.os.Process.myPid())    //获取PID   System.exit(0);   //常规java.c#的标准退出法,返回值为0代表正常退出 2. 任务管理器方

Java读取文件夹大小的6种方法及代码

这篇文章介绍了JAVA读取文件夹大小的几种方法实例,有需要的朋友可以参考一下. (一)单线程递归方式 package com.taobao.test; import java.io.File; public class TotalFileSizeSequential { public static String fileName = "C:\\Documents and Settings\\Administrator\\桌面\\monkeytalk"; // 递归方式 计算文件的大小

python将两个数组合并成一个数组的两种方法的代码

内容过程中,把写内容过程中常用的内容收藏起来,下面的资料是关于python将两个数组合并成一个数组的两种方法的内容,希望能对小伙伴们有帮助. c1 = ["Red","Green","Blue"]c2 = ["Orange","Yellow","Indigo"]c1.extend(c2) assert c1 == ["Red","Green",&q

python遍历数组的两种方法的代码

工作过程中,把开发过程中较好的一些内容段备份一下,下面内容是关于python遍历数组的两种方法的内容,希望对小伙伴有用途. colours = ["red","green","blue"] for colour in colours: print colour # red # green # blue 下面的方法可以先获得数组的长度,然后根据索引号遍历数组,同时输出索引号 colours = ["red","gree

用Fiddler可以设置浏览器的UA 和 手动 --Chrome模拟手机浏览器(iOS/Android)的三种方法,亲测无误!

附加以一种软件的方法是:用Fiddler可以设置浏览器的UA 以下3种方法是手动的 通过伪装User-Agent,将浏览器模拟成Android设备. 第一种方法:新建Chrome快捷方式 右击桌面上的Chrome浏览器图标,在弹出的右键菜单中选择“复制”,复制一个图标副本到桌面.右击该副本,选择“属性”,打开相应的对话框,在“目标”文本框的字符后面添加以下语句:“--user-agent="Android"”,如下图: 注意user前面是两个“-”,并且“chrome.exe”与“--

关于火狐(firefox)及ie下event获取的两种方法

第一种方法: 代码如下: function a(e){ e=e||window.event; alert(e.keyCode); } ie浏览器如下调用 代码如下: <body onclick="a()"> firefox火狐浏览器如下调用 代码如下: <body onclick="a(event)"> 这样就可以调用成功. 这种方法在firefox需要带个参数过去,不是太好,下面介绍第二种方法 . 第二种方法: 代码如下: function

JAVA之线程同步的三种方法

最近接触到一个图片加载的项目,其中有声明到的线程池等资源需要在系统中线程共享,所以就去研究了一下线程同步的知识,总结了三种常用的线程同步的方法,特来与大家分享一下.这三种方法分别是:synchronized代码段.synchronized修饰方法/类.ThreadLocal本地线程变量. 我们通过一个例子来表现这三种方法:一张银行卡里面有300块钱,15个线程从这张银行卡中取钱,每个线程取一次且每次取20块钱:当当前余额不足100元时,则向账户中汇款20元.三种方法每种方法都有5个线程.我们预期

css:图标与文字对齐的两种方法

(好久没写博客了,这几个月的积累比较零碎,记在本子上,现在开始整理归类) 在平时写页面的过程中,常遇到要把小图标与文字对齐的情况.比如: 总结了两种方法,代码量都比较少. 第一种 对img设置竖直方向对齐为middle, <div> <img src="" class="heart"> <span>1169</span> <img src="" class="comment"

java中遍历MAP的几种方法

java中遍历MAP的几种方法 Java代码 Map<String,String> map=new HashMap<String,String>();    map.put("username", "qq");    map.put("passWord", "123");    map.put("userID", "1");    map.put("em