系出名门Android(4) - 活动(Activity),服务(Service),广播(Broadcast),广播接收器(BroadcastReceiver)
介绍
在 Android 中使用 Activity, Service, Broadcast, BroadcastReceiver
活动(Activity) - 用于表现功能
服务(Service) - 相当于后台运行的 Activity
广播(Broadcast) - 用于发送广播
广播接收器(BroadcastReceiver) - 用于接收广播
Intent - 用于连接以上各个组件,并在其间传递消息
1、演示 Activity 的基本用法,一个 Activity 启动另一个 Activity,启动另一个 Activity 时为其传递参数,被启动的 Activity 返回参数给启动者的 Activity
Main.java
package com.webabcd.activity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Main extends Activity {
TextView txt;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);
txt = (TextView) this.findViewById(R.id.txt);
txt.setText("Activity 1");
Button btn = (Button) this.findViewById(R.id.btn);
btn.setText("启动另一个Activity");
btn.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
// 实例化 Intent,指定需要启动的 Activity
Intent intent = new Intent();
intent.setClass(Main.this, MyActivity.class);
// 实例化 Bundle,设置需要传递的参数
Bundle bundle = new Bundle();
bundle.putString("name", "webabcd");
bundle.putDouble("salary", 100.13);
// 将需要传递的参数赋值给 Intent 对象
intent.putExtras(bundle);
// startActivity(intent); // 启动指定的 Intent(不等待返回结果)
// Main.this.finish();
// 启动指定的 Intent,并等待返回结果
// 其中第二个参数如果大于等于零,则返回结果时会回调 onActivityResult() 方法
startActivityForResult(intent, 0);
}
});
Log.d("MyDebug", "onCreate");
}
// 被启动的 Activity 返回结果时的回调函数
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK){
Bundle bundle = data.getExtras();
String name = bundle.getString("name");
double salary = bundle.getDouble("salary");
txt.setText("Activity 1" + "\n名字:" + name + "\n薪水:" + String.valueOf(salary));
}
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
Log.d("MyDebug", "onStart");
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
Log.d("MyDebug", "onStop");
}
@Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
Log.d("MyDebug", "onRestart");
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Log.d("MyDebug", "onPause");
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.d("MyDebug", "onResume");
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.d("MyDebug", "onDestroy");
}
}