我在检查“if”中的变量时遇到问题。我从SharedPreferences和SmsMessage的phoneNumber获得了一个userPhoneNumber变量。
我将使用两个变量显示Toast并且它们是相同的,但是if不起作用。问题在哪里?
我的BroadcastReceiver类:
public class IncomingSms extends BroadcastReceiver {
String userPhoneNumber = "";
String senderNum= "";
String message= "";
final String TAG="LocationService";
GPSTracker gps;
double latitude = 0.0;
double longitude = 0.0;
// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();
public void onReceive(Context context, Intent intent) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
userPhoneNumber = settings.getString("userPhoneNumber", "");
Log.e(TAG, "userPhoneNumber:"+userPhoneNumber);
int duration = Toast.LENGTH_LONG;
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress().toString();
senderNum = phoneNumber;
message = currentMessage.getDisplayMessageBody();
turnOn(context);
} // end for loop
} // bundle is null
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}
Log.i("SmsReceiver", "senderNum: " + senderNum + "userPhoneNumber: "+ userPhoneNumber + "; message: " + message);
}
public void turnOn (Context context){
Intent i = new Intent(context, MyService.class);
gps = new GPSTracker(context);
Toast.makeText(context,"Method turnOn!\nsenderNum: "+senderNum + "\n userPhoneNumber: " + userPhoneNumber, Toast.LENGTH_LONG).show();
if (senderNum == userPhoneNumber) {
Toast.makeText(context,"works in IF", Toast.LENGTH_LONG).show();
if(gps.canGetLocation()){
latitude = gps.getLatitude();
longitude = gps.getLongitude();
i.putExtra("Latitude", latitude);
i.putExtra("Longitude", longitude);
context.startService(i);
}else
{
gps.showSettingsAlert();
}
}
gps.stopUsingGPS();
}
答案 0 :(得分:0)
senderNum它是一个字符串,表示你的if应该是:
if (senderNum.equals(userPhoneNumber))
答案 1 :(得分:0)
您正在比较senderNum
和userPhoneNumber
是否引用同一个对象。你需要改变
if (senderNum == userPhoneNumber)
到
if (senderNum.equals(userPhoneNumber))
答案 2 :(得分:0)
我认为问题出在这种情况。 要比较字符串值,您应该使用equals()函数。 ==测试对象引用,.equals()测试字符串值。
试
if (senderNum.equals(userPhoneNumber)) {
//code
}
请参阅this