Service-監聽手機來電

來源:互聯網
上載者:User

標籤:android   style   blog   http   ar   io   os   java   on   

public class MonitorPhone extends Activity {TelephonyManager tManager;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);//取得TelephoneManager對象tManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);//建立一個通話狀態監聽器PhoneStateListener listener = new PhoneStateListener(){@Overridepublic void onCallStateChanged(int state, String incomingNumber) {switch(state){//無任何狀態case TelephonyManager.CALL_STATE_IDLE:break;case TelephonyManager.CALL_STATE_OFFHOOK:break;//來電鈴響時case TelephonyManager.CALL_STATE_RINGING:OutputStream os = null;try{os = openFileOutput("phoneList", MODE_APPEND);}catch(FileNotFoundException e){e.printStackTrace();}PrintStream ps = new PrintStream(os);ps.println(new Date() + " 來電: " + incomingNumber);ps.close();break;default:break;};super.onCallStateChanged(state, incomingNumber);}};//監聽電話通話狀態的改變tManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);}}

mainfest檔案

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="crazyit.monitorphone"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="8"        android:targetSdkVersion="18" /><uses-permission android:name="android.permission.READ_PHONE_STATE"/>    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name="crazyit.monitorphone.MonitorPhone"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application></manifest>

TelephonyManager是一個管理手機通訊狀態、電話網路資訊的服務類,該類提供了一個listen(PhoneStateListener listener,int events)方法來監聽通話狀態

運行上面的程式,可以在DDMS的File Explorer面板data/data/crazyit.monitorphone/files目錄下看到一個phoneList檔案,將改檔案匯入電腦可以看到來電電話資訊

因為我是用真機測試,所以在DDMS下匯出檔案需要root許可權,否則打不開檔案夾

在DDMS取得開啟檔案夾的許可權:

>adb shell

$ su

# chmod 755 /data

# chmod 755 /data/data

# chmod 755 /data/data/crazyit.monitorphone/

# chmod 755 /data/data/crazyit.monitorphone/files

Service-監聽手機來電

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.