一、实现APP前后台运行提示

目的:缓解安卓界面劫持的风险,让用户知道APP在后台运行,通常在按下HOME键,弹出APP在后台运行的提示。

第 1 步:创建一个BaseApplication类,继承Application,在BaseApplication类的OnCreate方法实现registerActivityLifecycleCallbacks

package com.example.helloandroid;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class BaseApplication extends Application {
    int count=0;
    @Override
    public void onCreate() {
        super.onCreate();
        this.registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle bundle) {
                Log.v(activity.toString(),"onActivityCreated--");
            }

            @Override
            public void onActivityStarted(Activity activity) {
                Log.v(activity.toString(),"onActivityStarted--");
                if (count == 0) {
                    Log.v("viclee", ">>>>>>>>>>>>>>>>>>>切到前台  lifecycle");
                    Toast.makeText(activity,"APP切到前台",Toast.LENGTH_SHORT).show();
                }
                count++;
            }

            @Override
            public void onActivityResumed(Activity activity) {
                Log.v(activity.toString(),"onActivityResumed--");
            }

            @Override
            public void onActivityPaused(Activity activity) {
                Log.v(activity.toString(),"onActivityPaused--");
            }

            @Override
            public void onActivityStopped(Activity activity) {
                Log.v(activity.toString(),"onActivityStopped--");
                count--;
                if (count == 0) {
                    Log.v("viclee", ">>>>>>>>>>>>>>>>>>>切到后台  lifecycle");
                    Toast.makeText(activity,"APP切到后台",Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
                Log.v(activity.toString(),"onActivitySaveInstanceState--");
            }

            @Override
            public void onActivityDestroyed(Activity activity) {
                Log.v(activity.toString(),"onActivityDestroyed--");
            }
        });
    }
}

第 2 步:在AndroidManifest.xml文件的<application></application>中,声明BaseApplication,如下图

<application
        android:name=".BaseApplication"

第 3 步:运行APP,查看效果

 

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐