标签:
Activity及其生命周期
一、Activity初步认识:【创建、配置、启动Activity】
(二)、Activity的注册配置:
作为四大组件之一的Activity,必须要在AndroidManifest清单文件中进行注册。如果没有配置,而又在程序中启动了该Activity,将抛出异常(ActivityNotFoundException)。
注册配置的核心代码:
【附加思考】:<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<actionandroid:name="android.intent.action.MAIN" />
<categoryandroid:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity
android:name=".HeadpicActivity"
android:label="@string/title_activity_headpic" >
</activity>
</application>android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<actionandroid:name="android.intent.action.MAIN" />
<categoryandroid:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity
android:name=".HeadpicActivity"
android:label="@string/title_activity_headpic" >
</activity>
</application>
①. 当在AndroidManifest清单文件中,设置多个页面都是默认启动页,会报错吗?如果不报错,到底是 执行哪个页面呢?②. 当在AndroidManifest清单文件中,如果不设置默认启动页,会报错吗?
- Intent intent = new Intent(MainActivity.this , NextActivity.class);- Intent intent = new Intent();- intent.setClass(MainActivity.this , NextActivity.class);
(四)、Activity之间交换数据:
- Serializable的用法- Parcelable的用法
1、传递一般数据的核心代码:
(1)、MainActivity页面:
publicvoid clickButton(View view) {
switch (view.getId()) {
case R.id.button_main_tonext:
Intent intent = new Intent(MainActivity.this, NextActivity.class);
Bundle bundle = new Bundle();
bundle.putString("myname", "hehaitao");
bundle.putInt("age", 16);
intent.putExtras(bundle);
startActivity(intent);
break;
default:
break;
}
}
(2)、NextActivity页面:
@Override
protectedvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
// 接收第一个页面的传值
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String name = bundle.getString("myname");
int age = bundle.getInt("age");
this.setTitle(name + ":" + age);
}protectedvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
// 接收第一个页面的传值
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String name = bundle.getString("myname");
int age = bundle.getInt("age");
this.setTitle(name + ":" + age);
}
protectedvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
// 接收第一个页面的传值
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String name = bundle.getString("myname");
int age = bundle.getInt("age");
this.setTitle(name + ":" + age);
}
2、传递对象数据的核心代码:
(1)、Person对象核心代码:
publicclass Person implementsSerializable{private String userName;
privateintage;
privateintsex;
private List<String> infoList;
public List<String> getInfoList() {
return infoList;
}
publicvoid setInfoList(List<String> infoList) {
this.infoList = infoList;
}
public String getUserName() {
return userName;
}
publicvoid setUserName(String userName) {
this.userName = userName;
}
publicint getAge() {
returnage;
}
publicvoid setAge(int age) {
this.age = age;
}
publicint getSex() {
returnsex;
}
publicvoid setSex(int sex) {
this.sex = sex;
}
}
(2)、MainActivity页面:
publicclass MainActivity extends Activity {
private Person person = null;
@Override
protectedvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");
person = new Person();
person.setUserName("asan");
person.setAge(40);
person.setSex(1);
person.setInfoList(list);
}
publicvoid clickButton(View view) {
switch (view.getId()) {
case R.id.button_main_submit:
Intent intent = new Intent(MainActivity.this, ReceiverActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("person", person);
intent.putExtras(bundle);
startActivity(intent);
break;
}
}
}
二、Activity——调用另一个Activity并返回结果:
(3)、ReceiverActivity 页面:publicclass ReceiverActivity extends Activity {
@Override
protectedvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_receiver);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
// 接收Serializable对象
Person data = (Person) bundle.getSerializable("person");
setTitle(data.getUserName() + ":" + data.getAge() + ":" + data.getInfoList());
}
}
(一)、概念:
(二)、做法:甲页面调用乙页面,当用户在乙页面完成任务后,程序自动返回到甲页面,而甲页面必须能够获取到用户在完成乙页面后传递的数据结果。
(三)、示例代码:与普通的页面交换数据不同的是,要使用startActivityForResult()方法来启动另一个Activity。
1、MainActivity页面:
publicclass MainActivity extends Activity {
private ImageView imageView_main_headpic;
@Override
protectedvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView_main_headpic = (ImageView) findViewById(R.id.imageView_main_headpic);
}
publicvoid clickButton(View view) {
switch (view.getId()) {
case R.id.button_main_selectpic:
Intent intent = new Intent(MainActivity.this, HeadpicActivity.class);
startActivityForResult(intent, 0);
break;
}
}
@Override
protectedvoid onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0 && resultCode == 1) {
Bundle bundle = data.getExtras();
int imgid = bundle.getInt("imgId");
imageView_main_headpic.setImageResource(imgid);
}
}
}
2、HeadpicActivity页面:
publicclass HeadpicActivity extends Activity {
private GridView gridView_headpic_show;
// 定义数据源
privateint[] imgIds = newint[] { R.drawable.img01, R.drawable.img02,
R.drawable.img03, R.drawable.img04, R.drawable.img05,
R.drawable.img06, R.drawable.img07, R.drawable.img08,
R.drawable.img09 };
@Override
protectedvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_headpic);
gridView_headpic_show = (GridView) findViewById(R.id.gridView_headpic_show);
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
for (int i = 0; i < imgIds.length; i++) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("headpic", imgIds[i]);
map.put("picname", "头像—" + i);
list.add(map);
}
SimpleAdapter adapter = new SimpleAdapter(this, list,
R.layout.item_gridview_headpic, new String[] { "picname",
"headpic" }, newint[] {
R.id.text_item_gridview_picname,
R.id.imageView_item_gridview_headpic });
gridView_headpic_show.setAdapter(adapter);
gridView_headpic_show.setOnItemClickListener(new OnItemClickListener() {
@Override
publicvoid onItemClick(AdapterView<?> parent, View view,int position, long id) {
Intent intent = getIntent();
Bundle bundle = new Bundle();
bundle.putInt("imgId", imgIds[position]);
intent.putExtras(bundle);
setResult(1, intent);
finish();
}
});
}
@Override
publicboolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.headpic, menu);
returntrue;
}
}
(二)、Activity生命周期:
1、Activity一生中有七种不同的状态。
2、定义生命周期的作用:
3、生命周期的金字塔图
(三)、实例代码操作:
模仿以下操作,观察输出日志,找寻生命周期方法依次回调的规律:
04-23 03:51:29.750: I/MainActivity(741): ==MainActivity onCreate执行了
04-23 03:51:29.759: I/MainActivity(741): ==MainActivity onStart执行了
04-23 03:51:29.759: I/MainActivity(741): ==MainActivity onResume执行了
04-23 03:52:04.780: I/MainActivity(741): ==MainActivity onPause执行了
04-23 03:52:04.791: I/MainActivity(741): ==MainActivity onStop执行了
04-23 03:52:04.791: I/MainActivity(741): ==MainActivity onDestroy执行了
04-23 03:52:05.200: I/MainActivity(741): ==MainActivity onCreate执行了
04-23 03:52:05.209: I/MainActivity(741): ==MainActivity onStart执行了
04-23 03:52:05.329: I/MainActivity(741): ==MainActivity onResume执行了
【思考:】两个Activity页面,点第一个中的按钮,进入第二个页面,此时点HOME退出程序。随后再次启动app,依次会执行哪些生命周期的回调方法。如果再点击返回,继续会执行哪些生命周期的回调方法?请自己将依次调用的方法写在下面,不要借助机器调试。
(四)、Activty生命周期的应用场景
1、模拟Android音乐播放器,练习Activity生命周期的示例代码:【目的:练习Activity生命周期,要明白不是所有的代码都写在onCreate()方法中,而是需要根据需求写在生命周期的不同的回调方法中。】
publicclass MainActivity extends Activity {
privatestaticfinal String TAG = "MainActivity";
privatestaticinti = 0;
private Button button_main_play;
private Timer timer = null;
privatebooleanflag = false;
// 设置flag标记位的目的是避免程序一开启就执行,而是等点击了按钮后才开始。
@Override
protectedvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_main_play = (Button) findViewById(R.id.button_main_play);
button_main_play.setOnClickListener(new OnClickListener() {
@Override
publicvoid onClick(View v) {
// 点击按钮后执行播放
playMusic();
// 设置flag标记位的目的是避免程序一开启就执行。现在点击了按钮,允许程序在再次执行的时候自动执行
flag = true;
}
});
}
@Override
protectedvoid onStart() {
super.onStart();
}
@Override
protectedvoid onResume() {
super.onResume();
// 默认flag为false,不允许自动执行,而是当点击了播放后才允许执行。
if (flag) {
playMusic();
}
}
@Override
protectedvoid onPause() {
super.onPause();
// 当有电话进入,会回调onPause()方法,这个时候要让播放器停止。
// 定时器timer对象的cancel()方法能取消定时器。
timer.cancel();
}
@Override
protectedvoid onStop() {
super.onStop();
}
@Override
protectedvoid onRestart() {
super.onRestart();
}
@Override
protectedvoid onDestroy() {
super.onDestroy();
// 如果希望程序退出后,下次运行从头开始播放,可以将进度初始化为0.
// 如果点HOME退出,程序没有完全退出,下次播放应该从上次的进度继续执行,所以不应该初始化。
// 所以将初始化写在onDestroy(),而不写在onStop()中。(因为点HOME退出不会回调onDestroy()方法。)
i = 0;
}
publicvoid playMusic() {
// 用定时器输出数字来模拟播放器播放的效果
timer = new Timer();
// 定时器timer对象的sechedule()方法有三个参数,第一个表示定时执行的任务,第二个参数表示延迟时间,第
三个参数表示间隔的时间.timer.schedule(new TimerTask() {
@Override
publicvoid run() {
Log.i(TAG, "==i=" + i);
i++;
}
}, 0, 1000);
}
}
(五)、阅读英文API文档
The entire lifetime:onCreate() --- onDestroy() 完整生命周期The visible lifetime:onStart() --- onStop() 可见生命周期The foreground lifetime: onResume() --- onPause() 前沿生命周期
Activity及其生命周期
一、Activity初步认识:【创建、配置、启动Activity】
(二)、Activity的注册配置:
作为四大组件之一的Activity,必须要在AndroidManifest清单文件中进行注册。如果没有配置,而又在程序中启动了该Activity,将抛出异常(ActivityNotFoundException)。
注册配置的核心代码:
【附加思考】:<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<actionandroid:name="android.intent.action.MAIN" />
<categoryandroid:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity
android:name=".HeadpicActivity"
android:label="@string/title_activity_headpic" >
</activity>
</application>android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<actionandroid:name="android.intent.action.MAIN" />
<categoryandroid:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity
android:name=".HeadpicActivity"
android:label="@string/title_activity_headpic" >
</activity>
</application>
①. 当在AndroidManifest清单文件中,设置多个页面都是默认启动页,会报错吗?如果不报错,到底是 执行哪个页面呢?②. 当在AndroidManifest清单文件中,如果不设置默认启动页,会报错吗?
- Intent intent = new Intent(MainActivity.this , NextActivity.class);- Intent intent = new Intent();- intent.setClass(MainActivity.this , NextActivity.class);
(四)、Activity之间交换数据:
- Serializable的用法- Parcelable的用法
1、传递一般数据的核心代码:
(1)、MainActivity页面:
publicvoid clickButton(View view) {
switch (view.getId()) {
case R.id.button_main_tonext:
Intent intent = new Intent(MainActivity.this, NextActivity.class);
Bundle bundle = new Bundle();
bundle.putString("myname", "hehaitao");
bundle.putInt("age", 16);
intent.putExtras(bundle);
startActivity(intent);
break;
default:
break;
}
}
(2)、NextActivity页面:
@Override
protectedvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
// 接收第一个页面的传值
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String name = bundle.getString("myname");
int age = bundle.getInt("age");
this.setTitle(name + ":" + age);
}protectedvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
// 接收第一个页面的传值
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String name = bundle.getString("myname");
int age = bundle.getInt("age");
this.setTitle(name + ":" + age);
}
protectedvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
// 接收第一个页面的传值
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String name = bundle.getString("myname");
int age = bundle.getInt("age");
this.setTitle(name + ":" + age);
}
2、传递对象数据的核心代码:
(1)、Person对象核心代码:
publicclass Person implementsSerializable{private String userName;
privateintage;
privateintsex;
private List<String> infoList;
public List<String> getInfoList() {
return infoList;
}
publicvoid setInfoList(List<String> infoList) {
this.infoList = infoList;
}
public String getUserName() {
return userName;
}
publicvoid setUserName(String userName) {
this.userName = userName;
}
publicint getAge() {
returnage;
}
publicvoid setAge(int age) {
this.age = age;
}
publicint getSex() {
returnsex;
}
publicvoid setSex(int sex) {
this.sex = sex;
}
}
(2)、MainActivity页面:
publicclass MainActivity extends Activity {
private Person person = null;
@Override
protectedvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");
person = new Person();
person.setUserName("asan");
person.setAge(40);
person.setSex(1);
person.setInfoList(list);
}
publicvoid clickButton(View view) {
switch (view.getId()) {
case R.id.button_main_submit:
Intent intent = new Intent(MainActivity.this, ReceiverActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("person", person);
intent.putExtras(bundle);
startActivity(intent);
break;
}
}
}
二、Activity——调用另一个Activity并返回结果:
(3)、ReceiverActivity 页面:publicclass ReceiverActivity extends Activity {
@Override
protectedvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_receiver);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
// 接收Serializable对象
Person data = (Person) bundle.getSerializable("person");
setTitle(data.getUserName() + ":" + data.getAge() + ":" + data.getInfoList());
}
}
(一)、概念:
(二)、做法:甲页面调用乙页面,当用户在乙页面完成任务后,程序自动返回到甲页面,而甲页面必须能够获取到用户在完成乙页面后传递的数据结果。
(三)、示例代码:与普通的页面交换数据不同的是,要使用startActivityForResult()方法来启动另一个Activity。
1、MainActivity页面:
publicclass MainActivity extends Activity {
private ImageView imageView_main_headpic;
@Override
protectedvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView_main_headpic = (ImageView) findViewById(R.id.imageView_main_headpic);
}
publicvoid clickButton(View view) {
switch (view.getId()) {
case R.id.button_main_selectpic:
Intent intent = new Intent(MainActivity.this, HeadpicActivity.class);
startActivityForResult(intent, 0);
break;
}
}
@Override
protectedvoid onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0 && resultCode == 1) {
Bundle bundle = data.getExtras();
int imgid = bundle.getInt("imgId");
imageView_main_headpic.setImageResource(imgid);
}
}
}
2、HeadpicActivity页面:
publicclass HeadpicActivity extends Activity {
private GridView gridView_headpic_show;
// 定义数据源
privateint[] imgIds = newint[] { R.drawable.img01, R.drawable.img02,
R.drawable.img03, R.drawable.img04, R.drawable.img05,
R.drawable.img06, R.drawable.img07, R.drawable.img08,
R.drawable.img09 };
@Override
protectedvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_headpic);
gridView_headpic_show = (GridView) findViewById(R.id.gridView_headpic_show);
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
for (int i = 0; i < imgIds.length; i++) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("headpic", imgIds[i]);
map.put("picname", "头像—" + i);
list.add(map);
}
SimpleAdapter adapter = new SimpleAdapter(this, list,
R.layout.item_gridview_headpic, new String[] { "picname",
"headpic" }, newint[] {
R.id.text_item_gridview_picname,
R.id.imageView_item_gridview_headpic });
gridView_headpic_show.setAdapter(adapter);
gridView_headpic_show.setOnItemClickListener(new OnItemClickListener() {
@Override
publicvoid onItemClick(AdapterView<?> parent, View view,int position, long id) {
Intent intent = getIntent();
Bundle bundle = new Bundle();
bundle.putInt("imgId", imgIds[position]);
intent.putExtras(bundle);
setResult(1, intent);
finish();
}
});
}
@Override
publicboolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.headpic, menu);
returntrue;
}
}
(二)、Activity生命周期:
1、Activity一生中有七种不同的状态。
2、定义生命周期的作用:
3、生命周期的金字塔图
(三)、实例代码操作:
模仿以下操作,观察输出日志,找寻生命周期方法依次回调的规律:
04-23 03:51:29.750: I/MainActivity(741): ==MainActivity onCreate执行了
04-23 03:51:29.759: I/MainActivity(741): ==MainActivity onStart执行了
04-23 03:51:29.759: I/MainActivity(741): ==MainActivity onResume执行了
04-23 03:52:04.780: I/MainActivity(741): ==MainActivity onPause执行了
04-23 03:52:04.791: I/MainActivity(741): ==MainActivity onStop执行了
04-23 03:52:04.791: I/MainActivity(741): ==MainActivity onDestroy执行了
04-23 03:52:05.200: I/MainActivity(741): ==MainActivity onCreate执行了
04-23 03:52:05.209: I/MainActivity(741): ==MainActivity onStart执行了
04-23 03:52:05.329: I/MainActivity(741): ==MainActivity onResume执行了
【思考:】两个Activity页面,点第一个中的按钮,进入第二个页面,此时点HOME退出程序。随后再次启动app,依次会执行哪些生命周期的回调方法。如果再点击返回,继续会执行哪些生命周期的回调方法?请自己将依次调用的方法写在下面,不要借助机器调试。
(四)、Activty生命周期的应用场景
1、模拟Android音乐播放器,练习Activity生命周期的示例代码:【目的:练习Activity生命周期,要明白不是所有的代码都写在onCreate()方法中,而是需要根据需求写在生命周期的不同的回调方法中。】
publicclass MainActivity extends Activity {
privatestaticfinal String TAG = "MainActivity";
privatestaticinti = 0;
private Button button_main_play;
private Timer timer = null;
privatebooleanflag = false;
// 设置flag标记位的目的是避免程序一开启就执行,而是等点击了按钮后才开始。
@Override
protectedvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_main_play = (Button) findViewById(R.id.button_main_play);
button_main_play.setOnClickListener(new OnClickListener() {
@Override
publicvoid onClick(View v) {
// 点击按钮后执行播放
playMusic();
// 设置flag标记位的目的是避免程序一开启就执行。现在点击了按钮,允许程序在再次执行的时候自动执行
flag = true;
}
});
}
@Override
protectedvoid onStart() {
super.onStart();
}
@Override
protectedvoid onResume() {
super.onResume();
// 默认flag为false,不允许自动执行,而是当点击了播放后才允许执行。
if (flag) {
playMusic();
}
}
@Override
protectedvoid onPause() {
super.onPause();
// 当有电话进入,会回调onPause()方法,这个时候要让播放器停止。
// 定时器timer对象的cancel()方法能取消定时器。
timer.cancel();
}
@Override
protectedvoid onStop() {
super.onStop();
}
@Override
protectedvoid onRestart() {
super.onRestart();
}
@Override
protectedvoid onDestroy() {
super.onDestroy();
// 如果希望程序退出后,下次运行从头开始播放,可以将进度初始化为0.
// 如果点HOME退出,程序没有完全退出,下次播放应该从上次的进度继续执行,所以不应该初始化。
// 所以将初始化写在onDestroy(),而不写在onStop()中。(因为点HOME退出不会回调onDestroy()方法。)
i = 0;
}
publicvoid playMusic() {
// 用定时器输出数字来模拟播放器播放的效果
timer = new Timer();
// 定时器timer对象的sechedule()方法有三个参数,第一个表示定时执行的任务,第二个参数表示延迟时间,第
三个参数表示间隔的时间.timer.schedule(new TimerTask() {
@Override
publicvoid run() {
Log.i(TAG, "==i=" + i);
i++;
}
}, 0, 1000);
}
}
(五)、阅读英文API文档
The entire lifetime:onCreate() --- onDestroy() 完整生命周期The visible lifetime:onStart() --- onStop() 可见生命周期The foreground lifetime: onResume() --- onPause() 前沿生命周期
1、完善注册页面,将选择头像嵌入到注册页面中。2、用定时器模拟手机音乐播放器,要实现当电话进入时,该播放器停止。当电话结束,播放器继续播放。当返回退出,播放器关闭。
标签:
原文地址:http://blog.csdn.net/wuqingyidongren/article/details/51480332