天天看点

Android 显式Intent与隐式Intent

今日内容

  1. Intent用于页面的切换,就拿百度这个页面来说,一直看着搜索框没多少意义,点击搜索之后的页面才是我们上百度的原因。这就是Intent的作用。
  2. 它是什么姑且不论,它分为两类:显式与隐式。

显式Intent

Intent intent=new Intent(Context, aimContext);
startActivty(intent);
           

如果这里有First、Second两个页面,而需求是要在First中打开Second页面,代码如下:

Intent intent=new Intent(First.this,Second.class);
startActivity(intent);
           

隐式Intent

隐式的操作主要是针对AndroidManifest而言。

对于First来说,有

<activity android:name=".First">
<Intent-filter>
<action android:name="android.intent.action.MAIN"/>
<categroy android:name="android.intent.category.LAUNCHER"/>
</intetn-filter>
</activity>
           

而对于Second来说,有

<activity android:name=".Second">
<intent-filter>
<action android:name="com.example.activitytest.ACTION_START"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
           

之后在java文件中写的时候,在显式的基础上稍作改动就可以了。如以下:

Intent intent=new Intent("com.example.activitytest.ACTION_START");
startActivity(intent);

           

可以发现,"com.example.activitytest.ACTION_START"的一致是隐式Intent的特点。这里也必须一样。隐式的方法就是需要对应的的action和category。

Intent intent=new Intent("com.example.activitytest.ACTION_START");
           

表示想要启动可以响应这个action的活动,而恰巧之前在AndroidManifest中给Second设置的action就是这个。即两个action一样。

<category android:name="android.intent.category.DEFAULT"/>
           

这行代码表示附加信息。其他的不用管。但是要有,如果没有这一行,我想"Unfortunately, XXX has stopped" 是谁也不想看到的结果。这里插一句题外话,如果在布局layout写了某一按钮,但是java文件中没有写findViewById,同样也会出现这一句令我无比讨厌的提示语。

最后

添加额外的category方法:addCategroy();