首页 > 代码库 > Service-监听手机来电

Service-监听手机来电

public class MonitorPhone extends Activity {

	TelephonyManager tManager;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		//取得TelephoneManager对象
		tManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
		//创建一个通话状态监听器
		PhoneStateListener listener = new PhoneStateListener(){
			@Override
			public void onCallStateChanged(int state, String incomingNumber) {
				switch(state){
				//无任何状态
				case TelephonyManager.CALL_STATE_IDLE:
					break;
				case TelephonyManager.CALL_STATE_OFFHOOK:
					break;
				//来电铃响时
				case TelephonyManager.CALL_STATE_RINGING:
					OutputStream os = null;
					try{
						os = openFileOutput("phoneList", MODE_APPEND);
					}catch(FileNotFoundException e){
						e.printStackTrace();
					}
					PrintStream ps = new PrintStream(os);
					ps.println(new Date() + " 来电: " + incomingNumber);
					ps.close();
					break;
					default:
						break;
				};
				
				super.onCallStateChanged(state, incomingNumber);
			}
		};
		//监听电话通话状态的改变
		tManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
	}
}

mainfest文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="crazyit.monitorphone"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
	<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="crazyit.monitorphone.MonitorPhone"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

TelephonyManager是一个管理手机通讯状态、电话网路信息的服务类,该类提供了一个listen(PhoneStateListener listener,int events)方法来监听通话状态

运行上面的程序,可以在DDMS的File Explorer面板data/data/crazyit.monitorphone/files目录下看到一个phoneList文件,将改文件导入电脑可以看到来电电话信息

因为我是用真机测试,所以在DDMS下导出文件需要root权限,否则打不开文件夹

在DDMS取得打开文件夹的权限:

>adb shell

$ su

# chmod 755 /data

# chmod 755 /data/data

# chmod 755 /data/data/crazyit.monitorphone/

# chmod 755 /data/data/crazyit.monitorphone/files

Service-监听手机来电