How to detect incoming call with the help of Broadcast Receiver?

冷暖自知 提交于 2019-12-02 05:17:26

问题


I'm trying to recognize incoming calls in thru a broadcast receiver. I'm UNABLE to do so! Infact, I'm unable to 'trigger' the broadcast!

Here's my code:

activate.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                Toast.makeText(getApplicationContext(),"Clicked",1).show();
                final String BROADCAST_ACTION_NAME = ".BroadcastMM";
                Intent intent = new Intent();  
                intent.setAction(BROADCAST_ACTION_NAME);        
                sendBroadcast(intent); 


            }                                           
            }

I dunno if this 'sendBroadcast' is ever triggered! In my Broadcast Receiver file:

public void onReceive(Context context, Intent intent)
    {
        if(intent.getAction()=="android.intent.action.PHONE_STATE"){
        Toast.makeText(c,"BroadCast fired!",1).show();}
        Bundle extras = intent.getExtras();
        String state = extras.getString(TelephonyManager.EXTRA_STATE);
        if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
            Toast.makeText(context, "Ringing", 1).show();
        }
}       

My manifest file:

<receiver android:name=".BroadcastMM" >
            <intent-filter>
                <action android:name="android.intent.action.PHONE_STATE" >
                </action>
            </intent-filter>
        </receiver>

 <uses-permission android:name="android.permission.READ_PHONE_STATE" />

Is there some logic I'm missing? I'm very new to Android, so please help me out.


回答1:


intent.getAction()=="android.intent.action.PHONE_STATE"

should be

TelephonyManager.ACTION_PHONE_STATE_CHANGED.equals(intent.getAction());

Since this is how you compare Strings (with equals()).

Also, the code you use to broadcast, should never broadcast - there is no ".BroadcastMM" action. Try making an explicit one instead:

 Intent intent = new Intent(v.getContext(),BroadcastMM.class);  
 sendBroadcast(intent);

It is also likely that you can't broadcast android.intent.action.PHONE_STATE, so your if won't be executed if you make an explicit Intent.

If you really want to check that your BroadcastReceiver is working, put printouts/Toasts outside all ifs. Then once you establish that the BroadcastReceiver responds, do your check. Keep in mind though, that since you only listen for one Intent-Filter, the if checking if the Intent is a PHONE_STATE Intent is a bit redundant.



来源:https://stackoverflow.com/questions/15257649/how-to-detect-incoming-call-with-the-help-of-broadcast-receiver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!