1. Intent的概念及使用
概念
Android中提供了一种Intent机制来协助应用程序间、组件之间的交互与通信,Intent负责对应用中一次操作的动作、动作涉及数据、附加数据进行描述,Android则根据此Intent的描述,负责找到对应的组件,将Intent传递给调用的组件,并完成组件的调用。
Intent不仅可用于应用程序之间,也可用于应用程序内部的组件(如Activity、Service)之间的交互。
SDK给出了Intent作用的表现形式为:
(1)通过startActivity()或 startActivityForResult()启动一个Activity。
(2)通过startService()启动一个服务Service,或者通过 bindService()和后台服务进行交互。
(3)通过sendBroadcast()、sendOrderedBroadcast()、sendStickyBroadcast()函数在Android系统中发布广播消息。
2.Activity的启动和跳转
在Android系统中,应用程序一般都有多个Activity
Intent可以帮助实现不同Activity之间的切换和数据传递。
Activity的跳转启动的情况有三种。
跳转方式
1:使用Intent来显式启动Activity,首先要创建一个Intent对象,并为它指定当前的应用程序上下文以及要启动的Activity这两个参数,然后把这个Intent对象作为参数传递给startActivity这个方法。
1 Intent intent = new Intent(IntentDemo.this, ActivityToStart.class);2 startActivity(intent);
2:使用Intent来显式启动Activity,并且传递数据给第二个界面。
Intent intent = new Intent();intent.setClass(MainActivity.this, ThirdActivity.class);Bundle bundle = new Bundle();bundle.putString("name", "张三");bundle.putInt("age", 20);intent.putExtra("data", bundle);startActivity(intent);
3:使用Intent来显式启动Activity,并且传递数据给第二个界面,第二个界面会传递数据回给第一个界面。
Intent intent = new Intent();intent.setClass(MainActivity.this, ThirdActivity.class);Bundle bundle = new Bundle();bundle.putString("name", "张三");bundle.putInt("age", 20);intent.putExtra("data", bundle);startActivityForResult(intent, 3);
3:@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {super.onActivityResult(requestCode, resultCode, data);Toast.makeText(this, "从第" + requestCode + "个Activity返回。", Toast.LENGTH_LONG).show();String string=data.getStringExtra(“name");Toast.makeText(this, string,Toast.LENGTH_LONG).show();