意图Intent


我们都知道,在 android中有两种意图对象,分别是显式 Intent和隐式 Intent两种。由于显式 Intent的代码耦合性比较高,往往比例于后面软件的升级和迭代开发,故而常常考虑的是隐式的 Intent
隐式 Intent的比较含蓄,他并不会明确指出将要启动的活动,而是指定一系列更为抽象的 actioncategory等信息,然后由系统去分析 intent的意图,最后找到合适的活动去启动。

【注】需要注意的是,在指定action的时候,每一个隐式Intent都至少有一个category,就是 <category android:name="android.intent.category.DEFAULT" />

1. 显式Intent

Intent intent = new Intent();
intent.setClass(this, Main2Activity.class);
startActivity(intent);

2. 隐式Intent

需要在配置文件中,指定Main2Activity的意图过滤器:

<intent-filter>
   <action android:name="com.example.myapplication.Main2Activity.Test"></action>
   <category android:name="android.intent.category.DEFAULT" />
</intent-filter>

然后,再使用指定action的意图来进行startActivity

Intent intent = new Intent("com.example.myapplication.Main2Activity.Test");
startActivity(intent);

3. 打开指定域名地址网页

使用隐式过滤器来调用手机的模型浏览器,然后指定打开的具体的域名地址,如:

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://www.baidu.com"));
startActivity(intent);

Intent.ACTION_VIEWandroid系统的内置Action

4. 拨打电话

首先再配置文件中添加权限:

<uses-permission android:name="android.permission.CALL_PHONE"/>

然后,使用Intent,即:

Intent intent = new Intent(Intent.ACTION_CALL,Uri.parse("tel:15208149754"));
startActivity(intent);

但是,现在的androidx版本的权限需要动态申请,也就是还需要做一个判断,即改为:

if(checkReadPermission(Manifest.permission.CALL_PHONE)){
    
    
    Intent intent = new Intent(Intent.ACTION_CALL,Uri.parse("tel:15208149754"));
	startActivity(intent);
}

public boolean checkReadPermission(String string_permission) {
    
    
    boolean flag = false;
    if (ContextCompat.checkSelfPermission(this, string_permission) == PackageManager.PERMISSION_GRANTED) {
    
    //已有权限
        flag = true;
    } else {
    
    //申请权限
        ActivityCompat.requestPermissions(this, new String[]{
    
    string_permission}, 0);
    }
    return flag;
}

然后就可以调用打电话的自带程序,这里使用的是Intent.ACTION_CALL

猜你喜欢

转载自blog.csdn.net/qq_26460841/article/details/113447795