Android 入门篇检测手机打电话状态

1
在玩游戏的时候或者做其它的时候,我们常常会突然接受某个人的电话等等,这时候我们就得判定手机状态进行特殊处理。在做这个例子主要制作一个简单的手机拨号状态判断。在此先理解思路。

1 我们得先在注册表注册事件。

2 还需要一个用来监听状态改变处理的类。

下面是操作的流程:
在AndroidMainfest配置进行注册并把它放在两个Application之间。PhoneTest必须和下面一个类名字相同。

  <receiver android:name=".PhoneTest">
            <intent-filter>
                <action android:name="android.intent.action.PHONE_STATE" />
            intent-filter>
        receiver>

接着:新建一个Java类用来监听,这里边通过实现BroadcastReceiver的重载进行实现监听 。

package com.ss.babybus.myapplication;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.provider.Settings;
import android.telecom.TelecomManager;
import android.telephony.TelephonyManager;
import android.widget.Toast;

/**
 * Created by ysl on 2017/4/28.
 */
public class PhoneTest extends BroadcastReceiver {
    @Override
    public  void onReceive(Context context, Intent intent) {
       try
       {
           System.out.println("Receive Begin Test");
           String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE) ;
           String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
          if (state.equals(TelephonyManager.EXTRA_STATE_IDLE))
          {
              Toast.makeText(context,"If Ring Off  Call Idle State",Toast.LENGTH_SHORT).show();
          }
           if (state.equals(TelephonyManager.EXTRA_STATE_RINGING))
          {
              Toast.makeText(context,"We Receive Phone State",Toast.LENGTH_SHORT).show();
              Toast.makeText(context,"Ringing State Number is -"+incomingNumber,Toast.LENGTH_SHORT).show();
          }
           if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK))
           {
               Toast.makeText(context,"Ringing State Number is -"+incomingNumber,Toast.LENGTH_SHORT).show();
               Toast.makeText(context,"Call Ring Out State",Toast.LENGTH_SHORT).show();
           }
       }
       catch (Exception e)
       {e.printStackTrace();}
    }
}

3.在此还需要配置一下获取手机读取权限。所以在AndroidMainfest.xml里面添加如下权限。记住得在Application之外。代码如下。

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

4.打包运行在手机,打电话就可以测试有数据输出喽前提你先要打开这个app在后台。


代码包如下http://pan.baidu.com/s/1qYNOONU

你可能感兴趣的:(Android)