HypoAlarm/HypoAlarm/src/main/java/za/org/treehouse/hypoalarm/GraceReceiver.java

82 lines
3.7 KiB
Java

package za.org.treehouse.hypoalarm;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.telephony.SmsManager;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;
/*
* TODO: translate geographic coordinates into an address?
* import android.location.Address;
* import android.location.Geocoder;
*/
public class GraceReceiver extends BroadcastReceiver {
private static LocationClient locationClient;
private static String phoneNumber;
private static String message;
@Override
public void onReceive(final Context context, Intent intent) {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
Boolean alarmActive = sharedPref.getBoolean(context.getString(R.string.AlarmActivePref), true);
phoneNumber = sharedPref.getString(context.getString(R.string.PhoneNumberPref), null);
message = sharedPref.getString(context.getString(R.string.MessagePref), context.getString(R.string.defaultMessage));
if (alarmActive) {
if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(context) == ConnectionResult.SUCCESS) {
locationClient = new LocationClient(context,
new GooglePlayServicesClient.ConnectionCallbacks() {
@Override
public void onConnected(Bundle bundle) {
Location location = locationClient.getLastLocation();
if (location != null) {
String uri = " http://maps.google.com?q=" + location.getLatitude() + "," + location.getLongitude();
message += uri;
sendText(context);
locationClient.disconnect();
} else {
Log.e("GraceReceiver", "No location data available. Sending text message anyway.");
sendText(context);
}
}
@Override
public void onDisconnected() {
}
},
new GooglePlayServicesClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.e("GraceReceiver", "Failed connection to location manager " + connectionResult.toString() + ". Sending text message anyway.");
sendText(context);
}
}
);
locationClient.connect();
} else {
Log.e("GraceReceiver", "No Google Play Services. Sending text message anyway.");
sendText(context);
}
}
}
private void sendText(Context context) {
SmsManager sms = SmsManager.getDefault();
// TODO uncomment sendTextMessage
//sms.sendTextMessage(phoneNumber, null, message, null, null);
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
Log.d("GraceReceiver", "Sending sms to " + phoneNumber + " with message: " + message);
}
}