下面是一个监听手机来电的例子
注意下面使用到的电话监听器PhoneStateListener
首先在AndroidManifest.xml文件中加入权限
<!-- 添加访问手机状态的权限 -->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
package WangLi.Service.MonitorPhone;
import java.io.FileNotFoundException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Date;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
public class MonitorPhone extends Activity
{
TelephonyManager tManager;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 取得TelephonyManager对象
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);
}
}
这样就会把来电写入一个文件中,可以在DDMS中查看data->data->WangLi.Service.MonitorPhone->files->phoneList