【安卓开发快速入门】 APP前后台运行进行Toast提示
一、实现APP前后台运行提示目的:缓解安卓界面劫持的风险,让用户知道APP在后台运行,通常在按下HOME键,弹出APP在后台运行的提示。第 1 步:创建一个BaseApplication类,继承Application,在BaseApplication类的OnCreate方法实现registerActivityLifecycleCallbackspackage com.example.helloan
·
一、实现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,查看效果
更多推荐
已为社区贡献7条内容
所有评论(0)