Android 实现拨打电话

拨打电话有两种方式,一种是显示拨号界面,号码已经输入,用户需要点击拨打才可以完成拨打;一种是直接拨号出去,不需要用户点击拨打按钮。

    /**
     * 直接拨打
     */
    private void startCallOut() {
        Intent intent = new Intent(Intent.ACTION_CALL);
        intent.setData(Uri.parse("tel:10086"));
        startActivity(intent);
    }

    /**
     * 跳转到拨号界面,并且已经键入号码
     */
    private void startCallInput() {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        intent.setData(Uri.parse("tel:10086"));
        startActivity(intent);
    }

需要一个打电话的权限:targetSdk >=23 ,还需要动态申请

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

Intent是Android程序中各组件之间进行交互的一种重要方式,它不仅可以指明当前组件想要执行的动作,还可以在不同组件之间传递数据。

Intent的用法分为显式Intent和隐式Intent:
1.显式

    /**
     * 显式
     */
    private void startExplicit() {
        Intent intent = new Intent(this, SecondActivity.class);
        startActivity(intent);
    }

在AndroidManifest.xml中配置:

<activity android:name=".SecondActivity"/>

2.隐式:
2.1 隐式Intent并不明确指出想要启动哪个一个活动,而是指定一系列更为抽象的action和category;
2.2 只有action和category中的内容同时匹配才可以启动活动,每一个Intent只能指定一个action,但是可以多个category

    /**
     * 隐式
     */
    private void startImplicit() {
        Intent intent = new Intent();
        intent.setAction("com.example.test.ACTION_START");
        startActivity(intent);
    }

在AndroidManifest.xml中配置:

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

Intent对象大致包含Component,Action,Category,Data,Type,Extra,Flag七种属性。

1.指定Component属性的Intent已经明确了它将要启动哪个组件,因此这种Intent也被称之为显式Intent,反之则是隐式Intent。

    /**
     * 显式-component属性
     */
    private void startExplicitComponent() {
        Intent intent = new Intent();
        ComponentName componentName = new ComponentName(IntentActivity.this, SecondActivity.class);
        intent.setComponent(componentName);
        startActivity(intent);
    }

在被打开的组件中可以获取前一个组件的包名和类名以及短类名

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

      ComponentName component = getIntent().getComponent();
      Log.d(TAG, "组件包名:" + component.getPackageName());
      Log.d(TAG, "组件类名:" + component.getClassName());
      Log.d(TAG, "组件类名:" + component.getShortClassName());
}

2.Action和Category的值是一个普通的字符串,Action是抽象的动作,Category是附加的信息。

3.Data和Type属性会相互覆盖,如果需要同时指定,则调用setDataAndType()方法。data标签包含scheme,host,port,path,
pathPrefix,pathPattern标签

4.Extra属性用于多个Action之间的数据交换,Intent的Extra属性应该是Bundle对象,类似Map的键值对。

5.Flag属性为Intent添加额外的控制旗标

猜你喜欢

转载自blog.csdn.net/scau_zhangpeng/article/details/70768695