Intent详解
16lz
2021-01-26
Intent是什么?以及Android的三个基本组件——Activity,Service和Broadcast Receiver——都是通过Intent机制激活的,不同类型的组件有不同的传递Intent方式,可以通过我的另一篇博客,Intent和pendingIntent机制详解里有?
这里主要讲解下Intent的用法:
示例代码一:
//定义一个IntentIntent intent = new Intent(IntentDemo.this, AnotherActivity2.class);//启动ActivitystartActivity(intent);
这里通过intent直接显示的调用另一个Activity的class来启动另一个Activity。
示例代码二:
//定义一个IntentIntent intent = new Intent(Intent.ACTION_EDIT);//启动ActivitystartActivity(intent);
这里通过在Intent构造函数里加一个action,来启动一个Activity。那怎么找到这个Activity呢?
<?xml version="1.0" encoding="utf-8"?>
通过在AndroidManifest.xml里面配置声明,activity那一项的intent-filter中,增加EDIT的action,启动activity的时候就能找到这个activity启动了。
下面我们再看看其构造函数:
Intent() Create an empty intent. Intent(Intent o) Copy constructor. Intent(String action) Create an intent with a given action. Intent(String action, Uri uri) Create an intent with a given action and for a given data url. Intent(Context packageContext, Class<?> cls) Create an intent for a specific component. Intent(String action, Uri uri, Context packageContext, Class<?> cls) Create an intent for a specific component with a specified action and data.
最后看下Android中BatteryService中关机调用shutdownActivity的一段代码
Intent intent = new Intent(Intent.ACTION_REQUEST_SHUTDOWN); intent.putExtra(Intent.EXTRA_KEY_CONFIRM, false);//传数据 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mContext.startActivityAsUser(intent, UserHandle.CURRENT);
再来看下shutdownActivity的AndroidManifest.xml文件
最后看shutdownActivity的代码:
public class ShutdownActivity extends Activity { private static final String TAG = "ShutdownActivity"; private boolean mReboot; private boolean mConfirm; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); mReboot = Intent.ACTION_REBOOT.equals(intent.getAction());//Intent的action mConfirm = intent.getBooleanExtra(Intent.EXTRA_KEY_CONFIRM, false);//传过来的数据 Slog.i(TAG, "lowbattery or batteryovertempture shutdown:" + "onCreate(): confirm=" + mConfirm + " mReboot:" + mReboot); Thread thr = new Thread("ShutdownActivity") { @Override public void run() { IPowerManager pm = IPowerManager.Stub.asInterface( ServiceManager.getService(Context.POWER_SERVICE)); try { if (mReboot) { pm.reboot(mConfirm, null, false); } else { pm.shutdown(mConfirm, false); } } catch (RemoteException e) { } } }; thr.start(); finish(); // Wait for us to tell the power manager to shutdown. try { thr.join(); } catch (InterruptedException e) { } }}
比如当我们想知道是谁调用了ShutdownActivity 这个activity,我们可以从它的AndroidManifest.xml文件中的intent-filter,比如ACTION_REQUEST_SHUTDOWN,REBOOT,我们可以通过搜这两个action,看看是哪个Intent加个这两个action,再去startActivity了。
更多相关文章
- android Activity启动流程
- 【总结】Mac版Android(安卓)Studio常用快捷键总结
- Android学习笔记_4_单元测试
- 支付宝转账小demo(不需要库)
- 认识 android 中的 LayoutInflater
- Android四大组件中每个组件的作用是什么?它们都可以开启多进程吗?
- Android(安卓)ListView 有时候设置setDividerHeight无效的原因
- SpannableStringBuilder 和 SpannableString(转)
- Android(安卓)Dalvikvm 内存管理理解