当用户切断来自特定号码

时间:2016-09-30 09:00:26

标签: android broadcastreceiver

我想在用户切断来自特定号码的来电时打开新的activity。 我知道我必须使用TelephonyManagerPhoneStateListener来听取不同类型的通话状态。 我也试过下面的例子,但它打开activity不止一次,我想只打开一次。请帮助我

public class Demos extends BroadcastReceiver{

public void onReceive(final Context context, Intent intent) {

    if (!intent.getAction().equals("android.intent.action.PHONE_STATE")) 
         return;        
    else
    {
         final TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);    
         PhoneStateListener callStateListener = new PhoneStateListener() 
         {
             public void onCallStateChanged(int state, String incomingNumber) 
                     {       
                 if((state == TelephonyManager.CALL_STATE_RINGING))
                 {  }
                 if((state==TelephonyManager.CALL_STATE_OFFHOOK))
                 {  }
                 if(!(state == TelephonyManager.CALL_STATE_RINGING) && (state==TelephonyManager.CALL_STATE_IDLE) )
                 {
                     if(incomingNumber.equalsIgnoreCase("XXX-XXX-XXXX"))
                     {  Intent i=new Intent(context,Activity_two.class);
                            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            context.startActivity(i);
                                telephonyManager.listen(null,  PhoneStateListener.LISTEN_NONE); }
                 }
                    }
         }; telephonyManager.listen(callStateListener,PhoneStateListener.LISTEN_CALL_STATE)  
    }
}

1 个答案:

答案 0 :(得分:0)

您可以尝试以下代码以及电话号码检查

        final TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
        telephony.listen(new PhoneStateListener(){
            @Override
            public void onCallStateChanged(int state, String incomingNumber) {
                super.onCallStateChanged(state, incomingNumber);
                Log.e("CALL STATE", state + "");
                if(!(state == TelephonyManager.CALL_STATE_RINGING) && (state==TelephonyManager.CALL_STATE_IDLE) )
                {
                    Intent i=new Intent(context, yourActivity.class);
                    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(i);
                }
            }
        },PhoneStateListener.LISTEN_CALL_STATE);