Android 将值从BroadcastReceiver传递给活动
我已使用以下代码获取电话号码。我将数字存储在一个静态变量中。当我试图在另一个活动中使用该变量时,它抛出NullPointer异常Android 将值从BroadcastReceiver传递给活动,android,broadcastreceiver,Android,Broadcastreceiver,我已使用以下代码获取电话号码。我将数字存储在一个静态变量中。当我试图在另一个活动中使用该变量时,它抛出NullPointer异常 package com.income; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.telephony.PhoneSta
package com.income;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
public class IncomingCallReceiver extends BroadcastReceiver {
static String info = null;
static String phonenumber;
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
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)) {
phonenumber = bundle
.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
// String d=bundle.getString(TelephonyManager.EXTRA_STATE_IDLE)
Log.i("IncomingCallReceiver", "Incomng Number: " + phonenumber);
info = phonenumber;
}
if (state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_IDLE)) {
Toast.makeText(context, info, Toast.LENGTH_LONG).show();
Intent intent1 = new Intent(context, MissedCall.class);
intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent1);
}
}
}
根据您得到的
NullPointerException
这一事实,这意味着捆绑包是null
,这使得pone号为null
我建议你看看如何获得来电者的电话号码(),就像这篇文章中的做法一样
编辑
我看到的是,你从来没有把电话号码存储在开始活动的意图中,所以你永远不会在所说的活动中得到电话号码。尝试使用
intent1.putExtra(“phoneNumber”,phoneNumber)
现在,broadcastReceiver
中的电话号码不为空,使用intent.getExtras(“电话号码”)从MissedCall.class
中检索它代码>您试图获取数字的位置。检查您的意图。putstring()方法日志是否显示数字?我在MissedCall活动中使用了静态字符串。字符串或=IncomingCallReceiver.info;当我打印或时,它抛出空指针异常。谢谢,我得到电话号码,在广播接收器中打印,然后它被打印。当我在另一个活动中得到它时,它不会。我也使用了它。但同样的例外也发生了。