Android得到呼入的手机号码

最近开发项目中需要监听当前手机的状态(空闲,来电,接通),在来电时需要获取来电的手机号码。

写了一个服务一直运行在后台来对手机的状态进行监听,代码如下。

监听手机状态的Service:

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;

public class PhoneService extends Service {

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		TelephonyManager manager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        manager.listen(new PhoneListener() , PhoneStateListener.LISTEN_CALL_STATE);
	}

}

监听手机的状态PhoneListener:

import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;

public class PhoneListener extends PhoneStateListener {

	/**
	 * state	当前手机的状态
	 * incomingNumber	呼入的手机号码
	 */
	
	@Override
	public void onCallStateChanged(int state, String incomingNumber) {
		// TODO Auto-generated method stub
		super.onCallStateChanged(state, incomingNumber);

		switch (state) {
		case TelephonyManager.CALL_STATE_IDLE://空闲或者挂断

			break;

		case TelephonyManager.CALL_STATE_OFFHOOK://接通

			break;
		case TelephonyManager.CALL_STATE_RINGING://来电响铃
			Log.d("TAG", "得到的来电号码是:" + incomingNumber);
			break;
		}
	}
}

MainActivity:

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

public class MainActivity extends Activity {

	private Context context;
	public static final String ACTION = "recordingFlag";
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        context = getApplicationContext();
        
        //启动后台监听服务
        Intent intent = new Intent();
        intent.setAction(ACTION);
        intent.setPackage(getPackageName());
        context.startService(intent);
    }

}

manifest配置文件:

<!-- 注册服务 -->
        <service android:name="com.example.service.PhoneService">
            <intent-filter>
                <action android:name="recordingFlag"/>
            </intent-filter>
        </service>

最后,不要忘记添加读取手机状态的权限:

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



发布了13 篇原创文章 · 获赞 2 · 访问量 1万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览