Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android 電話服務(完成版)

Android 電話服務(完成版)

編輯:關於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 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() ;//撥打電話
}

布局文件

<code class="hljs xml"><relativelayout android:layout_height="match_parent" android:layout_width="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" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">

    <edittext android:ems="10" android:id="@+id/phonenumber" android:layout_alignparentleft="true" android:layout_alignparentright="true" android:layout_alignparenttop="true" android:layout_height="wrap_content" android:layout_margintop="55dp" android:layout_width="wrap_content">

        <requestfocus>
    </requestfocus></edittext><button android:id="@+id/cancelnumber" android:layout_alignbaseline="@+id/setnumber" android:layout_alignbottom="@+id/setnumber" android:layout_alignright="@+id/phonenumber" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="cancel"></button></relativelayout></code><button android:id="@+id/setnumber" android:layout_alignleft="@+id/phonenumber" android:layout_below="@+id/phonenumber" android:layout_height="wrap_content" android:layout_margintop="54dp" android:layout_width="wrap_content" android:text="set"><code class="hljs xml">


</code></button>

清單配置文件

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

    <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:label="@string/app_name" android:name="tedu.cn.telephone.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN">

                <category android:name="android.intent.category.LAUNCHER">
            </category></action></intent-filter>
        </activity>
        <activity android:label="@string/app_name" android:name="tedu.cn.telephone.MySMSListener">
        </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">
            </action></action></action></intent-filter>
        </receiver>
    </service></application>


電話過濾成功圖

這裡寫圖片描述
再次點擊,沒有反應,因為已經將5554過濾了
這裡寫圖片描述
取消過濾
這裡寫圖片描述
大家可以嘗試下,咯咯!

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved