Android 识别来电号码

识别来电号码




学习内容: 你将学会如何使用PhoneStateIntentReceiver来识别来电号码 . 可能出现的情况是, 当有来电时会使音乐播放关闭.

难度: 2 of 5

界面效果:

很不幸,没有




描述:
我们会创建一个PhoneStateIntentReceiver,PhoneState 状态改变时它会发送消息 Handler. 请看一看 详细注释 的例子实现(实际上注册发生在onCreate()-方法):
同志们啊,恕我注释就不翻了哈。

Java:
package org.anddev.android.reactonincomingcall;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.Phone;
import android.telephony.PhoneStateIntentReceiver;
import android.util.Log;

public class ReactOnIncomingCall extends Activity {
/** Used to recognize Messages from the
* myPhoneStateChangedHandler. */
final int PHONECALLSTATE_RECONGNIZE_ID = 0x539;

/** Will notify us on changes to the PhoneState*/
PhoneStateIntentReceiver myPsir = null;

/** This Handler will react on the messages the
* we made our PhoneStateIntentReceiver myPsir
* notify us on. */
Handler myPhoneStateChangedHandler = new Handler(){

@Override
public void handleMessage(Message msg) {

// Recognize the Message by its what-ID
if(msg.what == PHONECALLSTATE_RECONGNIZE_ID){

/* Our PhoneStateIntentReceiver myPsir
* now contains some recent data, we can grab. */
Phone.State myState = myPsir.getPhoneState();

// Put the Info to the logger for debugging
Log.d("PhoneCallStateNotified", myState.toString());

if(myState == Phone.State.RINGING){
// Celebrate =D
}
}
}
};

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
// Set some simple layout
super.onCreate(icicle);
setContentView(R.layout.main);


/* Create a new PhoneStateIntentReceiver
* that will pass messages to the handler h
* as it receives Intents we make it notify
* us below*/
this.myPsir = new PhoneStateIntentReceiver(this, myPhoneStateChangedHandler);

/* As we want to get notified on changes
* to the Phones-State we tell our
* PhoneStateIntentReceiver myPsir,
* that we wan to get notified with the ID
* (PHONECALLSTATE_RECONGNIZE_ID) we pass to him
*/
this.myPsir.notifyPhoneCallState(PHONECALLSTATE_RECONGNIZE_ID);

/* Register the Intent with the system. */
this.myPsir.registerIntent();
}
}

你可能感兴趣的:(android,OS,音乐)