开发者

how do i retrieve the incoming phone call's number while ringing and store it in a variable in android?

I am fairly new to android and I would like my app to be able to r开发者_StackOverflow社区etrieve the phone number of caller while ringing and store it. How can I do this?


You need to use a BroadcastReceiver. It should look something like this:

public class CallReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
    if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
        Intent i = new Intent(context, IncomingCallPopup.class);
        i.putExtras(intent);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        context.startActivity(i);

    }
}


Need to Extend BroadcastReceiver

public class CallReceiver extends BroadcastReceiver {
   
    @Override
    public final void onReceive(Context context, Intent intent){

            try {
                String state =intent.getStringExtra(TelephonyManager.EXTRA_STATE);             

                 String number=intent.getExtras().getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
                        
                    }

                 catch (Exception e) {
                        Log.e(TAG," Exception "+e);
                    }
            }
    }


you should register broadcast receiver and get the phone state and get incoming phone call number as:

public class CallReceiver extends BroadcastReceiver {
    String state,number,message;
    @Override
    public void onReceive(Context context, Intent intent) {
        state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
        if(state.equals(TelephonyManager.EXTRA_STATE_RINGING)){
            number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
            message = "phone is ringing";
            Toast.makeText(context, "Incoming Call From:"+number, Toast.LENGTH_SHORT).show();
        }
        if ((state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK))){
            Toast.makeText(context, "Call Received", Toast.LENGTH_SHORT).show();
        }
        if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)){
            message += "phone is idled";
            Toast.makeText(context, "Idled", Toast.LENGTH_SHORT).show();
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜