在Android中,Intent是一种重要的组件,它不仅仅是为了启动其他的Activity或者Service,也可以用来传递数据。Intent在应用间、Activity间、Service间传递消息时非常有用。
以下是一些使用场景和示例代码:
启动另一个Activity
Intent intent = new Intent(this, TargetActivity.class);
startActivity(intent);
启动一个Service
Intent intent = new Intent(this, TargetService.class);
startService(intent);
打电话
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(“tel:123456789”));
startActivity(intent);
发送短信
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.putExtra(“sms_body”, “The SMS text”);
intent.setType(“vnd.android-dir/mms-sms”);
startActivity(intent);
打开网页
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(“http://www.google.com”));
startActivity(intent);
传递数据到另一个Activity
Intent intent = new Intent(this, TargetActivity.class);
intent.putExtra(“key”, “value”);
startActivity(intent);
在接收方Activity中,你可以通过以下代码获取传递过来的数据:
Intent intent = getIntent();
String value = intent.getStringExtra(“key”);
启动相机
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CODE);
选择联系人
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
startActivityForResult(intent, REQUEST_CODE);
通过Intent启动另一个应用
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(“market://details?id=com.example.app”));
startActivity(intent);
通过Intent发送电子邮件
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType(“text/plain”);
intent.putExtra(Intent.EXTRA_EMAIL, “recipient@example.com”);
intent.putExtra(Intent.EXTRA_SUBJECT, “Subject”);
intent.putExtra(Intent.EXTRA_TEXT, “Email Body”);
startActivity(Intent.createChooser(intent, “Send mail…”));
以上就是一些常见的Intent使用场景和示例代码。