Android电话服务完成版

之前的代码是分开写的,并没有实现一个完成电话相关服务,这次就给大家来一记猛药,望大家提出宝贵意见和建议与我分享,感谢!
这里写图片描述
电话监听主Activity

package tedu.cn.telephone;

import tedu.cn.telephone.PhoneService.BinderImpl;
import tedu.cn.telephoneDemo.IService;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
    private EditText phoneNumber = null ;
    private Button setNumber = null ;
    private Button cancelNumber = null ;
    private IService service = null ;
    private ServiceConnectionImpl serviceConnection = new ServiceConnectionImpl() ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.phoneNumber = (EditText) super.findViewById(R.id.phonenumber) ;
        this.setNumber = (Button) super.findViewById(R.id.setnumber) ;
        this.cancelNumber = (Button) super.findViewById(R.id.cancelnumber) ;
        this.setNumber.setOnClickListener(new SetOnClickListenerImpl()) ;
        this.cancelNumber.setOnClickListener(new CancelOnClickListenerImpl()) ;
    }
    private class SetOnClickListenerImpl implements OnClickListener {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this,PhoneService.class) ;
            intent.putExtra("phonenumber", MainActivity.this.phoneNumber
                    .getText().toString());
            MainActivity.this.bindService(intent,
                    MainActivity.this.serviceConnection,
                    Context.BIND_AUTO_CREATE);

        }
    }
    private class CancelOnClickListenerImpl implements OnClickListener {
        @Override
        public void onClick(View v) {
            if(MainActivity.this.service != null) {
                MainActivity.this.unbindService(MainActivity.this.serviceConnection) ;
                MainActivity.this.stopService(new Intent(MainActivity.this,PhoneService.class)) ;
                Toast.makeText(MainActivity.this, "黑名单已取消", Toast.LENGTH_LONG)
                        .show();
                MainActivity.this.service = null ;
            }
        }
    }
    private class ServiceConnectionImpl implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            MainActivity.this.service = (BinderImpl) service ;
            try {
                Toast.makeText(MainActivity.this, service.getInterfaceDescriptor(), Toast.LENGTH_LONG).show() ;
            } catch (RemoteException e) {
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }

    }


}

实现手机黑名单—不想接听的号码,让手机切换到静音状态

package tedu.cn.telephone;

import java.lang.reflect.Method;

import tedu.cn.telephoneDemo.IService;
import tedu.cn.telephoneDemo.ITelephony;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Binder;
import android.os.IBinder;
import android.os.RemoteException;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;

public class PhoneService extends Service {
//  private TelephonyManager telephony = null;
//  private String outgoingNumber = null;
//  private RecordAudioUtil raUtil = null;
//  private Intent intent = null ;
    private TelephonyManager telephony = null;
    private AudioManager audio = null; // 声音服务
    private String phoneNumber = null; // 要过滤的电话
    private IBinder myBinder = new BinderImpl();

    class BinderImpl extends Binder implements IService {

        @Override
        public String getInterfaceDescriptor() {
            return "过滤电话“" + PhoneService.this.phoneNumber + "”设置成功!";
        }
    }
    @Override
    public void onCreate() { // 服务创建的时候操作
        super.onCreate();
        this.telephony = (TelephonyManager) super
                .getSystemService(Context.TELEPHONY_SERVICE);
        this.telephony.listen(new PhoneStateListenerImpl(),
                PhoneStateListener.LISTEN_CALL_STATE); // 设置监听操作
    }

//  @Override
//  public int onStartCommand(Intent intent, int flags, int startId) {
//      this.outgoingNumber = intent.getStringExtra("outgoingNumber");
//      this.intent = intent ;
//      return super.onStartCommand(intent, flags, startId);
//  }
//  

    private class PhoneStateListenerImpl extends PhoneStateListener {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            switch (state) {
            case TelephonyManager.CALL_STATE_IDLE: // 挂断电话
                PhoneService.this.audio
                        .setRingerMode(AudioManager.RINGER_MODE_NORMAL); // 正常音
                break;
            case TelephonyManager.CALL_STATE_RINGING: // 领音响起
                if (incomingNumber.equals(PhoneService.this.phoneNumber)) { // 电话号码匹配
                    ITelephony iTelephony = getITelephony() ;
                    if (iTelephony != null) {
                        try {
                            iTelephony.endCall() ;  // 挂断电话
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                    }
                }
                break;
            case TelephonyManager.CALL_STATE_OFFHOOK: // 接听电话
                break;
            }
        }
        /**
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            switch (state) {
            case TelephonyManager.CALL_STATE_IDLE: // 没有拨入或拨出电话状态
                PhoneService.this.audio
                .setRingerMode(AudioManager.RINGER_MODE_NORMAL); // 正常音
//              if (PhoneService.this.raUtil != null) { // 保险
//                  PhoneService.this.raUtil.stop();
//                  PhoneService.this.raUtil = null;
//              }
                break;
            case TelephonyManager.CALL_STATE_RINGING: // 领音响起
                if (incomingNumber.equals(PhoneService.this.phoneNumber)) { // 电话号码匹配
                    PhoneService.this.audio
                            .setRingerMode(AudioManager.RINGER_MODE_SILENT); // 静音
                }
//              new MessageSendUtil(PhoneService.this, PhoneService.this.intent)
//              .send("13683527621", incomingNumber, "拨入");
//              PhoneService.this.raUtil = new RecordAudioUtil(incomingNumber,
//                      "拨入电话");
//              PhoneService.this.raUtil.record();
//              System.out.println("拨入电话号码:"
//                      + incomingNumber
//                      + ",拨入时间:"
//                      + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
//                              .format(new Date()));//后台输出
                break;
            case TelephonyManager.CALL_STATE_OFFHOOK: // 接听电话
//              new MessageSendUtil(PhoneService.this, PhoneService.this.intent)
//              .send("13683527621", PhoneService.this.outgoingNumber,
//                      "呼出");
//              PhoneService.this.raUtil = new RecordAudioUtil(
//                      PhoneService.this.outgoingNumber, "拨出电话");
//              PhoneService.this.raUtil.record();
//System.out.println("拨出电话号码:"
//                      + outgoingNumber
//                      + ",拨出时间:"
//                      + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
//                              .format(new Date()));//后台输出

                break;
            }
        }*/

    }

    @Override
    public IBinder onBind(Intent intent) {
        this.phoneNumber = intent.getStringExtra("phonenumber"); // 取得电话号码
        this.audio = (AudioManager) super
                .getSystemService(Context.AUDIO_SERVICE); // 声音服务
        this.telephony = (TelephonyManager) super
                .getSystemService(Context.TELEPHONY_SERVICE);
        this.telephony.listen(new PhoneStateListenerImpl(),
                PhoneStateListener.LISTEN_CALL_STATE); // 设置监听操作
        return this.myBinder;
    }
    private ITelephony getITelephony() {
        ITelephony iTelephony = null ;
        Class<TelephonyManager> cls = TelephonyManager.class ;
        Method getITelephonyMethod = null ;
        try {
            getITelephonyMethod = cls.getDeclaredMethod("getITelephony") ;
            getITelephonyMethod.setAccessible(true) ;   // 取消封装
        } catch (Exception e) {
        }
        try {
            iTelephony = (ITelephony) getITelephonyMethod
                    .invoke(this.telephony);
            return iTelephony ;
        } catch (Exception e) {
        }
        return iTelephony ;
    }
}

发现你的私人秘密:电话窃听器

package tedu.cn.telephone;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.media.MediaRecorder;
import android.os.Environment;

public class RecordAudioUtil {
private MediaRecorder mediaRecorder = null;//录音工具类
private String recDir = "theifaudio";
private File recordAudioSaveFileDir = null;
private boolean sdcardExists = false;
private boolean isRecord = false;
private String phoneNumber = null; // 电话号码
private String callType = null; // 呼叫类型

public RecordAudioUtil(String phoneNumber, String callType) {
    this.phoneNumber = phoneNumber;
    this.callType = callType;
    if ((this.sdcardExists = Environment.getExternalStorageState().equals(
            Environment.MEDIA_MOUNTED))) {
        this.recordAudioSaveFileDir = new File(Environment
                .getExternalStorageDirectory().toString()
                + File.separator
                + this.recDir + File.separator);
        if (!this.recordAudioSaveFileDir.exists()) {
            this.recordAudioSaveFileDir.mkdirs();
        }
    }
}

public File record() { // 进行电话的录音,同时返回文件的路径
    File recordAudioSaveFile = null;
    String recordAudioSaveFileName = null;
    if (this.sdcardExists) { // sd卡存在
        recordAudioSaveFileName = this.recordAudioSaveFileDir.toString()
                + File.separator
                + "ThiefAudio_"
                + new SimpleDateFormat("yyyyMMddhhmmssSSS")
                        .format(new Date()) + "_" + this.callType + "_"
                + this.phoneNumber + ".3gp";
        recordAudioSaveFile = new File(recordAudioSaveFileName);
        this.mediaRecorder = new MediaRecorder();
        this.mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        this.mediaRecorder
                .setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        this.mediaRecorder
                .setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
        this.mediaRecorder.setOutputFile(recordAudioSaveFileName);
        try {
            this.mediaRecorder.prepare();
        } catch (Exception e) {
            e.printStackTrace() ;
        }
        this.mediaRecorder.start();
        this.isRecord = true;
    }
    return recordAudioSaveFile;
}

public void stop() {
    if (this.isRecord) {
        this.mediaRecorder.stop();
        this.mediaRecorder.reset() ;
        this.mediaRecorder.release();
    }
}
}

使用AIDL挂断电话
【开发流程】
1. 使用JAVA中接口的语法创建interface
2. 去掉接口声明中的public关键字
3. 打开接口文件所在的文件夹,将扩展名.java修改为.aidl,回到eclipse中,刷新项目
4. 将接口文件复制到客户端(访问方、享受服务的一方),复制时,需要在客户端创建与服务端AIDL文件相同的包名,然后把AIDL文件粘贴进去

package tedu.cn.telephoneDemo;

public interface IService {

}
package tedu.cn.telephoneDemo;

interface ITelephony {
    boolean endCall() ;
    // 挂断电话
    void answerRingingCall() ;//拨打电话
}

布局文件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/phonenumber"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="55dp"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/cancelnumber"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/setnumber"
        android:layout_alignBottom="@+id/setnumber"
        android:layout_alignRight="@+id/phonenumber"
        android:text="cancel" />

    <Button
        android:id="@+id/setnumber"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/phonenumber"
        android:layout_below="@+id/phonenumber"
        android:layout_marginTop="54dp"
        android:text="set" />

</RelativeLayout>

清单配置文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="tedu.cn.telephone"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
    <uses-permission android:name="android.permission.SEND_SMS" />
    <uses-permission android:name="android.permission.RECEIVE_SMS" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="tedu.cn.telephone.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>
        <activity
            android:name="tedu.cn.telephone.MySMSListener"
            android:label="@string/app_name" >
        </activity>
        <service android:name=".PhoneService" />
        <receiver android:name=".PhoneBroadcastReceiver">
            <intent-filter>
                <action android:name="android.intent.action.NEW_OUTGOING_CALL" />
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.PHONE_STATE" />
            </intent-filter>
        </receiver>
    </application>

</manifest>

电话过滤成功图
这里写图片描述
再次点击,没有反应,因为已经将5554过滤了
这里写图片描述
取消过滤
这里写图片描述
大家可以尝试下,咯咯!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值