当我们在运营商开启来电显示的时候:获取电话号码就易如反掌;
public class GetPhoneNumService extends Service {
private TelephonyManager telephonyManager;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Toast.makeText(getApplicationContext(), "Incoming number ",1).show();
MyPhoneStateListener phoneListener=new MyPhoneStateListener(getApplicationContext()); //我们派生的类
telephonyManager = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
telephonyManager.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);
}
class MyPhoneStateListener extends PhoneStateListener {
Context context;
public MyPhoneStateListener(Context context) {
super();
this.context = context;
}
@Override
public void onCallStateChanged(int state,String incomingNumber){
Toast.makeText(context, "Incoming number "+incomingNumber,1).show(); //incomingNumber就是来电号码
}
}
}
别忘了加上权限:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
但是,当我们没有开启来电显示的时候呢?
这个时候,因为运营商没有将手机号码,发给我们,所以是获取不到了(这个没有亲身实践,只是从网上查到的;因为本人的手机都是有来显的,悲剧!!!)