我如何将来电号码传递给主要活动?

时间:2013-01-26 12:29:50

标签: android android-intent broadcastreceiver

我创建了一个简单的应用程序来获取来电号码,工作并用吐司显示我的号码,但我想将此变量传递给我的主要活动进行处理...示例当呼叫管理员号码时发送短信。我试试这段代码但我的用户界面中没有数据显示......有什么想法吗?请帮忙吗?

   public class IncomingCallReceiver extends BroadcastReceiver {


    @Override
    public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();

            if(null == bundle)
                    return;

            Log.i("IncomingCallReceiver",bundle.toString());

            String state = bundle.getString(TelephonyManager.EXTRA_STATE);

            Log.i("IncomingCallReceiver","State: "+ state);

            if(state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_RINGING))
            {
                    String phonenumber = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);

                    Log.i("IncomingCallReceiver","Incomng Number: " + phonenumber);

                    String info = "Detect Calls sample application\nIncoming number: " + phonenumber;



                    Intent intentsend=new Intent("update");//Send data to update UI
                    intentsend.putExtra( "data","Admin call..."+info);
                    context.sendBroadcast(intentsend);

                    Toast.makeText(context, info, Toast.LENGTH_LONG).show();
            }

我的主要活动是......

     @Override
public void onResume() {
    super.onResume();

     updateReceiver=new BroadcastReceiver() {
          @Override
          public void onReceive(Context context, Intent intentsend) {
              //get extras, do some stuff
            String data = intentsend.getStringExtra("data");

            textphone.setText(data);

          }
      };
      IntentFilter updateIntentFilter=new IntentFilter("update");
      registerReceiver(updateReceiver, updateIntentFilter);
}

2 个答案:

答案 0 :(得分:0)

我认为当手机响铃时您的活动不可见,因为手机应用程序会弹出,您的活动会处于暂停状态。

你不能在接收器里面做逻辑吗?或者可能在服务中?

答案 1 :(得分:0)

1)将此接收器声明为ur活动的内部类。如下所示,如果onReceive获得同样的意图,你也会添加一个条件

       class  updateReceiver extends BroadcastReceiver() {
          @Override
          public void onReceive(Context context, Intent intentsend) {
              //get extras, do some stuff
            String data = intentsend.getStringExtra("data");

            textphone.setText(data);

          }
      };