Activity的生命周期
关于Activity活动方法小实例
package com.example.activitylife;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private static final String TAG="ActivityLife";
private Button btnstart;
private TextView tvDispaly;
private int count=0;
private boolean mainFlag=false;
private boolean isPause=true;
private Handler handler =new Handler();
@Override
/**
* onCreate做创建
* 在Activity生命周期中onCreate只调用一次
*/
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i("TAG","onCreate");
// 启动线程
new Thread(){
public void run(){
mainFlag=true;
while (mainFlag){
if (!isPause) { //是否暂停
count++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
@Override
public void run() {
//运行在主线程中
tvDispaly.setText(count + "");
}
});
}
}
}
}.start();
btnstart=(Button)findViewById(R.id.btnstart);
tvDispaly=(TextView)findViewById(R.id.tvDispaly);
btnstart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//使线程暂停及继续运行
isPause=!isPause;
}
});
}
protected void onStart() { //加载到内存,Activity不可见
super.onStart();
Log.i("TAG","onStart");
}
protected void onResume() { //显示出来获得焦点,Activity可见
super.onResume();
Log.i("TAG","onResume");
isPause=false;
}
protected void onPause() { //暂停失去焦点,Activity可见
super.onPause();
Log.i("TAG","onPause");
isPause=true;
}
protected void onStop() { //停止,Activity不可见
super.onStop();
Log.i("TAG","onStop");
}
protected void onDestroy() { //销毁,在Activity生命周期中onDestroy只调用一次
super.onDestroy();
mainFlag=false;
Log.i("TAG","onDestroy");
}
}