<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.callstatuslistener"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<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="com.example.callstatuslistener.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".PhoneStatusServices"></service>
</application>
</manifest>
package com.example.callstatuslistener;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//开启服务
Intent intent=new Intent(this,PhoneStatusServices.class);
startService(intent);
}
}
package com.example.callstatuslistener;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
public class PhoneStatusServices extends Service {
@Override
public void onCreate() {
super.onCreate();
System.out.println("服务被创建了");
//监视用户电话状态
TelephonyManager tm=(TelephonyManager) getSystemService(TELEPHONY_SERVICE);
//监听手机通话状态的变化
tm.listen(new MyPhoneStateListener(), PhoneStateListener.LISTEN_CALL_STATE);
}
class MyPhoneStateListener extends PhoneStateListener{
@Override
public void onCallStateChanged(int state, String incomingNumber) {
// TODO Auto-generated method stub
switch (state) {
case TelephonyManager.CALL_STATE_IDLE://空闲状态,无通话无响铃
break;
case TelephonyManager.CALL_STATE_RINGING://响铃状态
System.out.println("发现来电号码"+incomingNumber);
//下面可以进行电话拦截
break;
case TelephonyManager.CALL_STATE_OFFHOOK://通话状态
break;
default:
break;
}
super.onCallStateChanged(state, incomingNumber);
}
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
System.out.println("服务被销毁了");
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}