根据www.mars-droid.com:Andriod开发视频教学,先跳过书本《Beginning Android 2》的几个章,我是这两个资源一起看,需要进行一下同步。先初步了解一下应用具有多个Activity的处理情况。
视频中自然不会如同书本讲的仔细,胜在快速明了,反正也只是工具,所以这次主要重点在于如何操作。Intent用于在一个应用中多个Activity的调用和数据传递,也可用于调用其他服务(应用)。
1、Button触发
在《Android学习笔记(六):xml和widget》中,我们通过Android XML以及实现View.OnClickListener接口的方式来处理button触发调用,这里我们采用后一种方式,并做了稍稍改动。
public class Activity01 extends Activity { private Button mybutton = null; public void onCreate(Bundle savedInstanceState) { ... ... mybutton.setOnClickListener(new MyButtonListener()); } class MyButtonListener implements View.OnClickListener{ public void onClick(View v) { ... ... /* 在此,我们将调用另一个Activity */ } } }
2、编写另一个Activity
我们编写一个简单的Activity类OtherActivity,其中只有一个TextView。
public class OtherActivity extends Activity{ private TextView myTextView = null; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.other); myTextView = (TextView)findViewById(R.id.myTextView); } }
编写一个Activity,必须在AndroidManifest.xml中进行注册:
<?xml version="1.0" encoding="utf-8"?> <manifest ... ...> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".Activity01" android:label="@string/app_name"> ... ... </activity> <activity android:name=".OtherActivity" android:label="@string/other" /><!-- 在res/values/strings.xml中增加other的定义 <string name="other">It/'s other activity!</string> --> </application> </manifest>
3、通过Intent,在Activity01中调起OtherActivity,并向OtherActivity传递某个信息
在MyButtonListener中的onClick:
Intent intent = new Intent(); intent.putExtra("param_str", "Info from Activity01"); //向另一个Activity传递<name,value>,value采用string的格式,也可以是其他 intent.setClass(Activity01.this, OtherActivity.class);//指出是哪个Activity,setClass(对象,类),对于嵌套类,为了提供良好的阅读方式并避免奇异,我们都指明是哪个类 Activity01.this.startActivity(intent); //启动另外的Activity,作为View的方法,可以直接使用startActivity,由于嵌套类,这样些可以清晰一些。
4、在Otherctivity中接受传递的信息
Intent intent = getIntent();
String value = intent.getStringExtra("param_str");
5、intent也可以调用其他的应用,例如发送短信
Uri uri = Uri.parse("smsto:0000123456"); Intent intent = new Intent(Intent.ACTION_SENDTO,uri);//Intent(String action,Uri uri)对uri进行某个操作,ACTION_SENDTO:Send a message to someone specified by the data. intent.putExtra("sms_body", "This is my text info from Activity01."); //传递SMS的文本内容 Activity01.this.startActivity(intent); //启动另外的Activity,并不限于是否是同一个应用。系统收到相关消息,将调起相关应用