ActivityLifecycleCallbacks使用示例

简介: MyApplication如下: package com.cc;import java.util.LinkedList;import android.

MyApplication如下:

package com.cc;

import java.util.LinkedList;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
/**
 * Demo示例:
 * ActivityLifecycleCallbacks使用示例
 * 
 * ActivityLifecycleCallbacks用于对应用中Activity的生命周期的追踪和回调
 * 
 * 使用ActivityLifecycleCallbacks可实现:
 * 1 判断App是否在后台运行
 * 2 关闭该应用所有Activity
 * 
 * 
 * (1)判断App是否在后台运行
 * 在该实现中采用activityCounter记录Activity的个数.
 * 通过对于activityCounter是否为0判断当前APP是否在前台运行.
 * 
 * 从ActivityLifecycleCallbacks的实现方法中我们的惯性思维是:
 * 在ActivityLifecycleCallbacks的onActivityResumed()中activityCounter+1.
 * 在onActivityPaused()中activityCounter-1,
 * 但是这么对么?
 * 
 * 先看一下界面跳转时两个Activity的生命周期
 * 当从Activity A跳转到Activity B时,两个Activity的生命周期如下:
 * A.onPause()->B.onCreate()->B.onStart()-> B.onResume()-> A.onStop()
 * 
 * 假若按照上述方式那么:
 * 在A启动后activityCounter=1;
 * 当从A跳转到B时在调用A.onPause()时执行:activityCounter-1=0;
 * 即该APP运行在后台.
 * 这当然是错的,两个界面切换的过程中APP当然是运行在前台的。
 * 
 * 如下修改:
 * 在onActivityStarted()中对于activityCounter+1
 * 在onActivityStopped()中对于activityCounter-1
 * 小结:注意Activity跳转时的生命周期
 * 
 * (2)关闭该应用所有Activity
 *    2.1 利用LinkedList<Activity>管理应用中的界面
 *    2.2 在ActivityLifecycleCallbacks的onActivityCreated()
 *        将Activity添加到LinkedList中
 *        在ActivityLifecycleCallbacks的onActivityDestroyed()
 *        将Activity从LinkedList中移除
 *    2.3 关闭应用时销毁LinkedList中所有Activity
 * 
 * 备注说明:
 * 1 ActivityLifecycleCallbacks是在API 14及其以上才有的
 * 2 在Android4.0以下可以在BaseActivity中按照该思路实现
 *
 */
public class MyApplication extends Application {
	private static int activityCounter=0;
	private static MyApplication mApplicationInstance;
	private static LinkedList<Activity> mActivityLinkedList;
	private ActivityLifecycleCallbacksImpl mActivityLifecycleCallbacksImpl;
	@Override
	public void onCreate() {
		super.onCreate();
		mApplicationInstance=new MyApplication();
		mActivityLinkedList=new LinkedList<Activity>();
		mActivityLifecycleCallbacksImpl=new ActivityLifecycleCallbacksImpl();
		this.registerActivityLifecycleCallbacks(mActivityLifecycleCallbacksImpl);
	}
	
	public static MyApplication getInstance() {
		if (null==mApplicationInstance) {
			mApplicationInstance=new MyApplication();
		}
		return mApplicationInstance;
	}
	
	//判断App是否在后台运行
	public boolean isAppRunningBackground(){
		boolean flag=false;
		if(activityCounter==0){
			flag=true;
		}
		return flag;
	}
	
	//退出应用
	public void finishAllActivity(){
		//unregisterActivityLifecycleCallbacks(mActivityLifecycleCallbacksImpl);
		System.out.println("--> mActivityLinkedList.size()="+mActivityLinkedList.size());
		if(null!=mActivityLinkedList){
			for(Activity activity:mActivityLinkedList){
				if(null!=activity){
					activity.finish();
				}
			}
		}
	}
	
	
	private class ActivityLifecycleCallbacksImpl implements ActivityLifecycleCallbacks{
		@Override
		public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
			System.out.println("onActivityCreated --> "+activity.getClass().getName());
			if (null!=mActivityLinkedList&&null!=activity) {
				mActivityLinkedList.addFirst(activity);
			}
		}

		@Override
		public void onActivityStarted(Activity activity) {
			activityCounter++;
			System.out.println("onActivityStarted --> "+activity.getClass().getName()+",activityCounter="+activityCounter);
		}

		@Override
		public void onActivityResumed(Activity activity) {
			System.out.println("onActivityResumed --> "+activity.getClass().getName());
		}

		@Override
		public void onActivityPaused(Activity activity) {
			System.out.println("onActivityPaused --> "+activity.getClass().getName());
		}

		@Override
		public void onActivityStopped(Activity activity) {
			activityCounter--;
			System.out.println("onActivityStopped --> "+activity.getClass().getName()+",activityCounter="+activityCounter);
		}

		@Override
		public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
			System.out.println("onActivitySaveInstanceState --> "+activity.getClass().getName());
		}

		@Override
		public void onActivityDestroyed(Activity activity) {
			System.out.println("onActivityDestroyed --> "+activity.getClass().getName());
			if (null!=mActivityLinkedList&&null!=activity) {
				if (mActivityLinkedList.contains(activity)) {
					mActivityLinkedList.remove(activity);
				}
			}
		}
		
	}

}

FirstActivity如下:

package com.cc;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class FirstActivity extends Activity {
	 private Context mContext;
     private Button mOpenNewActivityButton;
     private Button mFinishThisActivityButton;
     private ClickListenerImpl mClickListenerImpl;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.first_activity);
		init();
	}
	
	private void init(){
		mContext=this;
		mClickListenerImpl=new ClickListenerImpl();
		mOpenNewActivityButton=(Button) findViewById(R.id.openNewActivityButton);
		mOpenNewActivityButton.setOnClickListener(mClickListenerImpl);
		mFinishThisActivityButton=(Button) findViewById(R.id.finishThisActivityButton);
		mFinishThisActivityButton.setOnClickListener(mClickListenerImpl);
	}
	
	
	private class ClickListenerImpl implements OnClickListener {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.openNewActivityButton:
				Intent intent=new Intent(mContext, SecondActivity.class);
				startActivity(intent);
				break;
			case R.id.finishThisActivityButton:
                finish();
				break;

			default:
				break;
			}

		}

	}
	
	@Override
	protected void onResume() {
		super.onResume();
		//System.out.println(" first Activity onResume --> "+MyApplication.getInstance().isAppRunningBackground());
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		//System.out.println(" first Activity onStop --> "+MyApplication.getInstance().isAppRunningBackground());
	}
	
	
}

SecondActivity如下:

package com.cc;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class SecondActivity extends Activity {
	 private Context mContext;
     private Button mOpenNewActivityButton;
     private Button mFinishThisActivityButton;
     private ClickListenerImpl mClickListenerImpl;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.second_activity);
		init();
	}
	
	private void init(){
		mContext=this;
		mClickListenerImpl=new ClickListenerImpl();
		mOpenNewActivityButton=(Button) findViewById(R.id.openNewActivityButton);
		mOpenNewActivityButton.setOnClickListener(mClickListenerImpl);
		mFinishThisActivityButton=(Button) findViewById(R.id.finishThisActivityButton);
		mFinishThisActivityButton.setOnClickListener(mClickListenerImpl);
	}
	
	
	private class ClickListenerImpl implements OnClickListener {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.openNewActivityButton:
				Intent intent=new Intent(mContext, ThirdActivity.class);
				startActivity(intent);
				break;

			case R.id.finishThisActivityButton:
                finish();
				break;

			default:
				break;
			}

		}

	}

	
}

ThirdActivity如下:

package com.cc;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class ThirdActivity extends Activity {
	 private Context mContext;
     private Button mFinishAllActivityButton;
     private Button mFinishThisActivityButton;
     private ClickListenerImpl mClickListenerImpl;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.third_activity);
		init();
	}
	
	private void init(){
		mContext=this;
		mClickListenerImpl=new ClickListenerImpl();
		mFinishThisActivityButton=(Button) findViewById(R.id.finishThisActivityButton);
		mFinishThisActivityButton.setOnClickListener(mClickListenerImpl);
		mFinishAllActivityButton=(Button) findViewById(R.id.finishAllActivityButton);
		mFinishAllActivityButton.setOnClickListener(mClickListenerImpl);
	}
	
	
	private class ClickListenerImpl implements OnClickListener {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.finishThisActivityButton:
                finish();
				break;
			case R.id.finishAllActivityButton:
				MyApplication.getInstance().finishAllActivity();
				break;
			default:
				break;
			}

		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		//System.out.println(" third Activity onResume --> "+MyApplication.getInstance().isAppRunningBackground());
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		//System.out.println(" third Activity onStop --> "+MyApplication.getInstance().isAppRunningBackground());
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		//System.out.println(" third Activity onDestroy --> "+MyApplication.getInstance().isAppRunningBackground());
	}

	
}

first_activity.xml如下:

<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.cc.FirstActivity" >

    <Button
        android:id="@+id/openNewActivityButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="open new Activity" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@id/openNewActivityButton"
        android:layout_centerInParent="true"
        android:layout_marginBottom="50dip"
        android:textSize="20sp"
        android:textColor="@android:color/holo_red_light"
        android:text="This is the first Activity" />

    <Button
        android:id="@+id/finishThisActivityButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/openNewActivityButton"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dip"
        android:text="finish this activity" />

</RelativeLayout>

second_activity.xml如下:

<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.cc.FirstActivity" >

    <Button
        android:id="@+id/openNewActivityButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="open new Activity" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@id/openNewActivityButton"
        android:layout_centerInParent="true"
        android:layout_marginBottom="50dip"
        android:textSize="20sp"
        android:textColor="@android:color/holo_red_light"
        android:text="This is the second Activity" />

    <Button
        android:id="@+id/finishThisActivityButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/openNewActivityButton"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dip"
        android:text="finish this activity" />

</RelativeLayout>

third_activity.xml如下:

<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.cc.FirstActivity" >

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@id/openNewActivityButton"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="100dp"
        android:text="This is the third Activity"
        android:textColor="@android:color/holo_red_light"
        android:textSize="20sp" />

    <Button
        android:id="@+id/finishThisActivityButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/textView"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dip"
        android:text="finish this activity" />

    <Button
        android:id="@+id/finishAllActivityButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/finishThisActivityButton"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dip"
        android:text="finish All Activity" />

</RelativeLayout>

AndroidManifest.xml如下:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.cc"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="14" />

    <application
        android:name="com.cc.MyApplication"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".FirstActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
       <activity android:name="com.cc.SecondActivity"/>
       <activity android:name="com.cc.ThirdActivity"/>
    </application>

</manifest>


相关文章
|
7月前
|
网络性能优化 调度 网络虚拟化
配置HQoS示例
HQoS简介 HQoS通过多级队列进一步细化区分业务流量,对多个用户、多种业务等传输对象进行统一管理和分层调度,在现有的硬件环境下使设备具备内部资源的控制策略,既能够为高级用户提供质量保证,又能够从整体上节约网络建设成本。 交换机的HQoS主要通过流队列和用户队列实现。
121 7
|
4月前
|
搜索推荐
示例
【8月更文挑战第27天】示例。
33 2
|
7月前
|
传感器 数据处理
示例三、光照度测试仪
示例三、光照度测试仪
58 1
一个完整的 ParentDataWidget 示例
一个完整的 ParentDataWidget 示例
132 0
一个完整的 ParentDataWidget 示例
|
Java Spring 网络安全
SpringHttpInvoker解析1-使用示例
HTTP invoker是一个新的远程调用模型,作为Spring框架的一部分,来执行基于HTTP的远程调用(让防火墙可以接受),并使用Java的序列化机制。 服务端 定义服务接口UserService import java.
848 0