Android8.0电话监听服务

1创建Service

package com.shiliu.callrecording;

import android.annotation.SuppressLint;

import android.annotation.TargetApi;

import android.app.Notification;

import android.app.NotificationChannel;

import android.app.NotificationManager;

import android.app.PendingIntent;

import android.app.Service;

import android.content.Context;

import android.content.Intent;

import android.content.ServiceConnection;

import android.graphics.Color;

import android.media.FaceDetector;

import android.media.MediaPlayer;

import android.media.MediaRecorder;

import android.os.Binder;

import android.os.Build;

import android.os.Environment;

import android.os.IBinder;

import android.support.annotation.RequiresApi;

import android.support.v4.app.NotificationCompat;

import android.support.v4.app.TaskStackBuilder;

import android.telephony.PhoneStateListener;

import android.telephony.TelephonyManager;

import android.util.Log;

import android.widget.Toast;

import com.vondear.rxtool.view.RxToast;

import java.io.File;

import java.io.IOException;

import java.text.SimpleDateFormat;

import java.util.Date;

import static android.support.v4.app.NotificationCompat.PRIORITY_MAX;

/**

* Created by Easzz on 2015/12/6.

*/

public class RecorderServiceextends Service {

private MediaRecorderrecorder;//录音的一个实例

    //通过binder实现调用者client与Service之间的通信

    private NotificationCompat.Builderbuilder;

private NotificationManagernotificationManager;

private boolean isFirst =true;

public RecorderService() {

}

@Override

    public void onCreate() {

super.onCreate();

//如果API在26以上即版本为O则调用startForefround()方法启动服务

//        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {

        setForegroundService();

//        }else {

//

//        }

    }

/**

    * 通过通知启动服务

    */

    public void setForegroundService() {

//设定的通知渠道名称

        String channelName = getString(R.string.channel_name);

final String CHANNEL_ID ="com.appname.notification.channel";

//设置通知的重要程度

        int importance = NotificationManager.IMPORTANCE_LOW;

Intent mIntent =new Intent(this, MainActivity.class);

PendingIntent pendingIntent = PendingIntent.getActivity(this,0, mIntent,0);

//在创建的通知渠道上发送通知

        builder =new NotificationCompat.Builder(this, CHANNEL_ID);

builder.setSmallIcon(R.mipmap.ic_launcher)//设置通知图标

                .setContentTitle("电话监听")//设置通知标题

                .setContentText("警告您的电话正在接受监听")//设置通知内容

                .setAutoCancel(true)//用户触摸时,自动关闭

                .setContentIntent(pendingIntent)

.setOngoing(true);//设置处于运行状态

        //向系统注册通知渠道,注册后不能改变重要性以及其他通知行为

        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

//构建通知渠道

        NotificationChannel channel =null;

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {

channel =new NotificationChannel(CHANNEL_ID, channelName, importance);

channel.setDescription("录音");

notificationManager.createNotificationChannel(channel);

}

//将服务置于启动状态 NOTIFICATION_ID指的是创建的通知的ID

        startForeground(11,builder.build());

}

@Override

    public int onStartCommand(Intent intent,int flags,int startId) {

TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);

////                        //启动监听.传入一个listener和监听的事件,

        tm.listen(new MyListener(), PhoneStateListener.LISTEN_CALL_STATE);

return START_STICKY;

}

@Override

    public void onDestroy() {

super.onDestroy();

Log.e("TAG","service onDestroy");

notificationManager.cancel(11);

}

@Override

    public IBinder onBind(Intent intent) {

return null;

}

class MyListenerextends PhoneStateListener {

//在电话状态改变的时候调用

        @Override

        public void onCallStateChanged(int state, String incomingNumber) {

super.onCallStateChanged(state, incomingNumber);

switch (state) {

case TelephonyManager.CALL_STATE_IDLE:

//空闲状态

//                    RxToast.showToast("通话中");

                    if (isFirst) {

Toast.makeText(RecorderService.this,"开始录音", Toast.LENGTH_SHORT).show();

isFirst =false;

}else {

Toast.makeText(RecorderService.this,"挂断电话", Toast.LENGTH_SHORT).show();

}

if (recorder !=null) {

recorder.stop();//停止录音

                        recorder.release();//释放资源

                        recorder =null;

}

break;

case TelephonyManager.CALL_STATE_RINGING:

Log.e("TAG","拨入电话,铃声响起");

Toast.makeText(RecorderService.this,"拨入电话,铃声响起", Toast.LENGTH_SHORT).show();

//                    //响铃状态  需要在响铃状态的时候初始化录音服务

                    if (recorder ==null) {

recorder =new MediaRecorder();//初始化录音对象

                        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);//设置录音的输入源(麦克)

                        recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);//设置音频格式(3gp)

                        createRecorderFile();//创建保存录音的文件夹

                        recorder.setOutputFile("sdcard/recorder" +"/" + getCurrentTime() +".3gp");//设置录音保存的文件

                        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);//设置音频编码

                        try {

recorder.prepare();//准备录音

                        }catch (IOException e) {

e.printStackTrace();

}

}

break;

case TelephonyManager.CALL_STATE_OFFHOOK:

Toast.makeText(RecorderService.this,"启动录音", Toast.LENGTH_SHORT).show();

//摘机状态(接听)

                    if (recorder !=null) {

recorder.start();//接听的时候开始录音

                        Log.e("TAG","开始录音");

}else {

recorder =new MediaRecorder();//初始化录音对象

                        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);//设置录音的输入源(麦克)

                        recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);//设置音频格式(3gp)

                        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

createRecorderFile();//创建保存录音的文件夹

                        recorder.setOutputFile("sdcard/recorder" +"/" + getCurrentTime() +".3gp");//设置录音保存的文件

                        try {

recorder.prepare();//准备录音

                        }catch (IOException e) {

e.printStackTrace();

}

recorder.start();//接听的时候开始录音

                        Log.e("TAG","录音失败");

}

break;

}

}

//创建保存录音的目录

        private void createRecorderFile() {

String absolutePath = Environment.getExternalStorageDirectory().getAbsolutePath();

String filePath = absolutePath +"/recorder";

File file =new File(filePath);

if (!file.exists()) {

file.mkdir();

}

}

//获取当前时间,以其为名来保存录音

        private String getCurrentTime() {

SimpleDateFormat format =new SimpleDateFormat("yyyyMMddHHmmss");

Date date =new Date();

String str = format.format(date);

return str;

}

}

}


//在需要的地方启动服务

public void btn(View view) {

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

startForegroundService(intent);

}else {

startService(intent);

}

}

下章是录音文件的读取和播放

推荐阅读更多精彩内容