監聽服務程序
package com.telphone.com;
import java.io.IOException;
import android.app.Service;
import android.content.Intent;
import android.media.MediaRecorder;
import android.net.sip.SipAudioCall.Listener;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
public class MonitorPhone extends Service {
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
System.out.println("啓動監聽電話服務");
TelephonyManager pm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
pm.listen(new myListener(), PhoneStateListener.LISTEN_CALL_STATE);
super.onCreate();
}
private class myListener extends PhoneStateListener
{
private MediaRecorder record;
@Override
public void onCallStateChanged(int state, String incomingNumber) {
try {
switch (state) {
case TelephonyManager.CALL_STATE_IDLE: //電話閒置狀態
if (record != null) {
record.stop();
record.reset();
record.release();
record = null;
}
break;
case TelephonyManager.CALL_STATE_RINGING://振鈴狀態
record = new MediaRecorder();
record.setAudioSource(MediaRecorder.AudioSource.MIC);//麥克風
record.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
record.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
record.setOutputFile("/sdcard/"+System.currentTimeMillis()+".3gp");
record.prepare();
break;
case TelephonyManager.CALL_STATE_OFFHOOK: //通話狀態
record.start();
break;
default:
break;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.onCallStateChanged(state, incomingNumber);
}
}
@Override
public void onDestroy() {
System.out.println("銷燬監聽電話服務");
super.onDestroy();
}
}
在main 中開啓服務
package com.telphone.com;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, MonitorPhone.class);
startService(intent);
}
}
清單文件中配置服務以及增長監聽電話須要的權限
權限
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
服務在application節點下
<service android:name=".MonitorPhone"></service>