向系统注册回调(Callback)函数的方法--获取电话状态更新和短信接收通知

来源:互联网 发布:mac化妆刷 编辑:程序博客网 时间:2024/06/05 08:54

下面的实例展示了向系统注册回调(Callback)函数的方法;实例中当电话状态发生改变时,应用程序将会得到系统的通知,Callback函数得以调用。相信这将是我们手机应用中经常需要用到的。

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 androidtest 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();
    }
}