lundi 29 juin 2015

"if" in method on the BroadcastReceiver service will not work

I have a problem with checking variables in the "if". I get a userPhoneNumber variable from SharedPreferences and phoneNumber of SmsMessage.

I will displaying Toast with both variables and they are the same, but the if didn't work. Where is the problem?

My BroadcastReceiver class:

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();
}

Aucun commentaire:

Enregistrer un commentaire