How to make a phone call in android and come back to my activity when the call is done?

后端 未结 20 2490
北恋
北恋 2020-11-22 12:59

I am launching an activity to make a phone call, but when I pressed the \'end call\' button, it does not go back to my activity. Can you please tell me how can I launch a c

20条回答
  •  情书的邮戳
    2020-11-22 13:39

    Steps:

    1)Add the required permissions in the Manifest.xml file.

    
    
    
    
    

    2)Create a listener for the phone state changes.

    public class EndCallListener extends PhoneStateListener {
    @Override
    public void onCallStateChanged(int state, String incomingNumber) {
        if(TelephonyManager.CALL_STATE_RINGING == state) {
        }
        if(TelephonyManager.CALL_STATE_OFFHOOK == state) {
            //wait for phone to go offhook (probably set a boolean flag) so you know your app initiated the call.
        }
        if(TelephonyManager.CALL_STATE_IDLE == state) {
            //when this state occurs, and your flag is set, restart your app
        Intent i = context.getPackageManager().getLaunchIntentForPackage(
                                context.getPackageName());
        //For resuming the application from the previous state
        i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    
        //Uncomment the following if you want to restart the application instead of bring to front.
        //i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(i);
        }
    }
    }
    

    3)Initialize the listener in your OnCreate

    EndCallListener callListener = new EndCallListener();
    TelephonyManager mTM = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
    mTM.listen(callListener, PhoneStateListener.LISTEN_CALL_STATE);
    

    but if you want to resume your application last state or to bring it back from the back stack, then replace FLAG_ACTIVITY_CLEAR_TOP with FLAG_ACTIVITY_SINGLE_TOP

    Reference this Answer

提交回复
热议问题