1,在Activity中实现Activity的声明周期方法。
onCreate()
onDestroy()
2,继承Application实现自定义生命周期管理
import java.util.Stack;
import android.app.Activity;
import android.app.Application;
public class MyApplication extends Application{
private static Stack<Activity> activityStack;
private static MyApplication singleton;
@Override
public void onCreate()
{
super.onCreate();
singleton=this;
}
// Returns the application instance
public static MyApplication getInstance() {
return singleton;
}
/**
* add Activity 添加Activity到栈
*/
public void addActivity(Activity activity){
if(activityStack ==null){
activityStack =new Stack<Activity>();
}
activityStack.add(activity);
}
/**
* get current Activity 获取当前Activity(栈中最后一个压入的)
*/
public Activity currentActivity() {
Activity activity = activityStack.lastElement();
return activity;
}
/**
* 结束当前Activity(栈中最后一个压入的)
*/
public void finishActivity() {
Activity activity = activityStack.lastElement();
finishActivity(activity);
}
/**
* 结束指定的Activity
*/
public void finishActivity(Activity activity) {
if (activity != null) {
activityStack.remove(activity);
activity.finish();
activity = null;
}
}
/**
* 结束指定类名的Activity
*/
public void finishActivity(Class<?> cls) {
for (Activity activity : activityStack) {
if (activity.getClass().equals(cls)) {
finishActivity(activity);
}
}
}
/**
* 结束所有Activity
*/
public void finishAllActivity() {
for (int i = 0, size = activityStack.size(); i < size; i++) {
if (null != activityStack.get(i)) {
activityStack.get(i).finish();
}
}
activityStack.clear();
}
/**
* 退出应用程序
*/
public void AppExit() {
try {
finishAllActivity();
} catch (Exception e) {
}
}
}
修改AndroidMenifest.xml应用配置文件。
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
<span style="color:#FF0000;"><strong> android:name="com.example.zxingdemo.MyApplication"</strong></span>
android:theme="@android:style/Theme.NoTitleBar" >
3,代码中进行生命周期控制
</pre><pre name="code" class="java">public class MainActivity2 extends Activity {
TextView textView6, textView7, textView8, textView9;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
<span style="color:#FF6666;"><strong>MyApplication.getInstance().addActivity(this);</strong></span>
setContentView(R.layout.permanent);
textView6 = (TextView) findViewById(R.id.textView6);
textView7 = (TextView) findViewById(R.id.textView7);
textView8 = (TextView) findViewById(R.id.textView8);
textView9 = (TextView) findViewById(R.id.textView9);
Bundle bundle = this.getIntent().getExtras();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity2.this,
MainActivity.class);
startActivity(intent);
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
<span style="color:#FF0000;"><strong>MyApplication.getInstance().finishActivity(this);</strong></span>
}
}
4,Activity中所有声明的控件必须实例化。