@6.01.15 Dennis Thießen: NotificationService hinzugefügt. In der SettingsActivity die Notifications einstellbar gemacht. Die Location von der Map muss jedoch noch getestet werden.

This commit is contained in:
Dennis Thießen
2016-01-06 16:33:47 +01:00
parent 0266439b2b
commit 0aeb4d4889
7 changed files with 368 additions and 153 deletions

View File

@@ -40,7 +40,6 @@ public class MainActivity extends BaseActivity{
private final static String mActivityTitle = "RiskAhead";
private final static String TAG = MainActivity.class.getSimpleName();
private final static String EXTRA_MESSAGE = "org.deke.risk.riskahead.MESSAGE";
public String msg_input;
public static FragmentManager fragmentManager;
@@ -96,133 +95,10 @@ public class MainActivity extends BaseActivity{
map.setCompoundDrawables(null,null, mapIcon, null);
startNotifyTask();
}
Runnable mNotifyTask = new Runnable()
{
@Override
public void run() {
Log.d(this.toString(),"Run Notification Task");
myPosition = session.getLocation();
if((myPosition != null) && (myPosition.latitude != 0.0) && (myPosition.longitude != 0.0)){
String lastNotificationTime = "";
if(session.getLastNotification().equals("")){
lastNotificationTime = getUser().get(SessionManager.KEY_LASTLOGIN_AT);
}else{
lastNotificationTime = session.getLastNotification();
}
Log.d(this.toString(),"Lookup location with position: "+myPosition+" Radius: 15 lastNotifyTime: "+lastNotificationTime);
StringRequest strReq = getStringRequestIncidentsFromAreaAndTime(myPosition.latitude, myPosition.longitude, 15, lastNotificationTime);
String tag_string_req = "req_incidents";
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
mNotifyHandler.postDelayed(mNotifyTask, INTERVAL_NOTIFICATION);
}
};
public void startNotifyTask()
{
mNotifyTask.run();
Log.d("BaseActivity","Start NotfiyTask");
}
public void stopNotifyTask()
{
mNotifyHandler.removeCallbacks(mNotifyTask);
Log.d("BaseActivity", "Stop NotfiyTask");
}
private StringRequest getStringRequestIncidentsFromAreaAndTime(final Double latitude, final Double longitude, final int radius, final String time) {
return new StringRequest(Request.Method.POST, AppConfig.URL_REGISTER, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "Incident notifications: " + response);
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
JSONArray notification = jObj.getJSONArray("msg");
sentNotification(notification);
} else {
String errorMsg = jObj.getString("error_msg");
Log.e(TAG, "Error getting incident notification (server returned error): " + errorMsg);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error getting incident notification: " + error.getMessage());
showMessage(getString(R.string.errormsg_couldnotretrieve));
stopNotifyTask();
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("tag", "getincidentsinareaandtime");
params.put("uid", user.get(SessionManager.KEY_UID));
params.put("token", user.get(SessionManager.TOKEN));
params.put("latitude", Double.toString(latitude));
params.put("longitude", Double.toString(longitude));
params.put("radius", Integer.toString(radius));
params.put("time", "'"+time+"'");
return params;
}
};
}
private void sentNotification(JSONArray notification) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.logo_riskahead_header)
.setContentTitle("New incidents reported in your area!")
.setContentText(notification.length() + " new incidents near your last location. Watch out!");
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Intent resultIntent = new Intent(this, MapsActivity.class);
try {
resultIntent.putExtra(EXTRA_MESSAGE, notification.getJSONObject(notification.length()-1).getDouble("latitude")+":"+notification.getJSONObject(notification.length()-1).getDouble("longitude"));
} catch (JSONException e) {
e.printStackTrace();
}
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MapsActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
int mId = 1;
mNotificationManager.notify(mId, mBuilder.build());
session.setLastNotification(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime()));
}
@Override
protected int getLayoutResourceId() {
@@ -243,7 +119,6 @@ public class MainActivity extends BaseActivity{
@Override
protected void onDestroy(){
super.onDestroy();
stopNotifyTask();
}
@Override

View File

@@ -127,12 +127,23 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(point, DEFAULT_ZOOM_LEVEL));
findViewById(R.id.fab_reportwf_map).setVisibility(View.VISIBLE);
findViewById(R.id.fab_reportwf_map).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
gotoReportActivity(markedLocation.latitude + ":" + markedLocation.longitude);
}
});
if(getIntent().getStringExtra(EXTRA_MESSAGE).equals("NoIncident")){
findViewById(R.id.fab_reportwf_map).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
session.setLocation((long)markedLocation.latitude,(long)markedLocation.longitude);
gotoSettingsActivity();
}
});
}else{
findViewById(R.id.fab_reportwf_map).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
gotoReportActivity(markedLocation.latitude + ":" + markedLocation.longitude);
}
});
}
}
});
}

View File

@@ -35,6 +35,7 @@ import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
@@ -48,31 +49,95 @@ public class SettingsFragment extends PreferenceFragment {
private EditTextPreference prefSurname;
private EditTextPreference prefName;
private EditTextPreference prefEmail;
private Preference btnRequestPW;
private SwitchPreference prefNotifications;
private ListPreference prefRadius;
private ListPreference prefFrequency;
private SwitchPreference prefGPSENabled;
private Preference prefLocation;
private Preference btnRequestPW;
HashMap<String,String> user;
public SessionManager session;
public HashMap<String, String> user;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
session = new SessionManager(getActivity().getApplicationContext());
user = session.getUserDetails();
addPreferencesFromResource(R.xml.settings);
initAccountPrefs();
prefNotifications = (SwitchPreference) getPreferenceManager().findPreference("notifyEnable");
prefRadius = (ListPreference) getPreferenceManager().findPreference("notifyRadius");
prefFrequency = (ListPreference) getPreferenceManager().findPreference("notifyFrequency");
prefGPSENabled = (SwitchPreference) getPreferenceManager().findPreference("notifyEnableGPS");
prefLocation = (Preference) getPreferenceManager().findPreference("notifyChooseLocation");
prefNotifications.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String newStringValue = newValue.toString();
session.setNotificationEnabled(Boolean.valueOf(newStringValue));
return true;
}
});
prefRadius.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String newStringValue = newValue.toString();
session.setNotificationRadius(Integer.valueOf(newStringValue));
((ListPreference)preference).setValue(newValue.toString());
((ListPreference)preference).setSummary(prefRadius.getEntry());
return true;
}
});
prefFrequency.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String newStringValue = newValue.toString();
session.setNotificationPollFreq(Integer.valueOf(newStringValue));
((ListPreference)preference).setValue(newValue.toString());
((ListPreference)preference).setSummary(prefFrequency.getEntry());
return true;
}
});
prefGPSENabled.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener(){
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String newStringValue = newValue.toString();
session.setGPSForNotificationsEnabled(Boolean.valueOf(newStringValue));
return true;
}
});
prefLocation.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
((SettingsActivity)getActivity()).gotoMapActivity("NoIncident");
return true;
}
});
updatePrefs();
}
private void initAccountPrefs() {
prefUsername = (EditTextPreference) getPreferenceManager().findPreference("usernamePref");
prefSurname = (EditTextPreference) getPreferenceManager().findPreference("surnamePref");
prefName = (EditTextPreference) getPreferenceManager().findPreference("namePref");
prefEmail = (EditTextPreference) getPreferenceManager().findPreference("emailPref");
btnRequestPW = (Preference) getPreferenceManager().findPreference("resetPassword");
prefRadius = (ListPreference) getPreferenceManager().findPreference("notifyRadius");
prefNotifications = (SwitchPreference) getPreferenceManager().findPreference("notifyEnable");
prefFrequency = (ListPreference) getPreferenceManager().findPreference("notifyFrequency");
prefUsername.getEditText().addTextChangedListener(new TextValidator(prefUsername.getEditText(), getActivity().getApplicationContext()) {
@Override
@@ -129,19 +194,15 @@ public class SettingsFragment extends PreferenceFragment {
}
});
updatePrefs();
if(!user.get(SessionManager.PROVIDER_TYPE).equals("local")){
btnRequestPW.setEnabled(false);
}else{
btnRequestPW.setEnabled(true);
}
}
private void updatePrefs() {
user = ((SettingsActivity) getActivity()).getUser();
user = session.getUserDetails();
prefUsername.setText(user.get(SessionManager.KEY_USERNAME));
prefSurname.setText(user.get(SessionManager.KEY_SURNAME));
@@ -152,6 +213,20 @@ public class SettingsFragment extends PreferenceFragment {
prefSurname.setSummary(user.get(SessionManager.KEY_SURNAME));
prefName.setSummary(user.get(SessionManager.KEY_NAME));
prefEmail.setSummary(user.get(SessionManager.KEY_EMAIL));
prefNotifications.setChecked(session.getNotificationEnabled());
prefFrequency.setValue(Integer.toString(session.getNotificationPollFreq()));
prefFrequency.setSummary(prefFrequency.getEntry());
prefRadius.setValue(Integer.toString(session.getNotificationRadius()));
prefRadius.setSummary(prefRadius.getEntry());
prefGPSENabled.setChecked(session.isGPSForNotificationsEnabled());
if(session.isGPSForNotificationsEnabled()){
btnRequestPW.setEnabled(false);
}else{
btnRequestPW.setEnabled(true);
}
}
private void requestPasswordReset() {

View File

@@ -1,5 +1,6 @@
package org.deke.risk.riskahead.helper;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
@@ -75,9 +76,6 @@ public abstract class BaseActivity extends AppCompatActivity {
public Drawer navDrawer = null;
public Toolbar mToolbar;
public Handler mNotifyHandler = new Handler();
public final static int INTERVAL_NOTIFICATION = 1000 * 60; //20 seconds
public LocationManager locationManager;
public LatLng myPosition;
@@ -116,20 +114,30 @@ public abstract class BaseActivity extends AppCompatActivity {
LocationManager.NETWORK_PROVIDER, 5000, 10, locationListener);
overridePendingTransition(R.anim.fade_in_anim, R.anim.fade_out_anim);
if(!isMyNotificationServiceRunning()){
Log.d(TAG,"onCreate: NotificationService not running. Starting service...");
startService(new Intent(this, NotificationService.class));
}else{
Log.d(TAG,"onCreate: NotificationService already running. Not starting more services.");
}
}
private class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location loc) {
String longitude = "Longitude: " + loc.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " + loc.getLatitude();
Log.v(TAG, latitude);
myPosition = new LatLng(loc.getLatitude(),loc.getLongitude());
session.setLocation(Double.doubleToRawLongBits(loc.getLatitude()),Double.doubleToRawLongBits(loc.getLongitude()));
if(session.isGPSForNotificationsEnabled()) {
Log.d(TAG,"Save GPS as new location...");
session.setLocation(Double.doubleToRawLongBits(loc.getLatitude()), Double.doubleToRawLongBits(loc.getLongitude()));
}else{
Log.d(TAG,"Don't Save GPS as new location because GPS for notifications is disabled...");
}
}
@Override
@@ -426,4 +434,14 @@ public abstract class BaseActivity extends AppCompatActivity {
if (pDialog.isShowing())
pDialog.dismiss();
}
private boolean isMyNotificationServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (NotificationService.class.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
}

View File

@@ -0,0 +1,187 @@
package org.deke.risk.riskahead.helper;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.*;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.android.gms.maps.model.LatLng;
import org.deke.risk.riskahead.MapsActivity;
import org.deke.risk.riskahead.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
/**
* Created by denni on 06.01.2016.
*/
public class NotificationService extends Service {
private final static String TAG = NotificationService.class.getSimpleName();
private final static String EXTRA_MESSAGE = "org.deke.risk.riskahead.MESSAGE";
Handler mNotifyHandler = new Handler();
NotificationManager mNotificationManager;
private LatLng myPosition;
private boolean notifyEnabled = true;
private int radius = 15;
private int pollFrequency = 10;
public SessionManager session;
public HashMap<String, String> user;
public NotificationService() {
super();
}
@Override
public void onCreate(){
Log.d(TAG,"Service Created. Starting notification task...");
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
session = new SessionManager(getApplicationContext());
user = session.getUserDetails();
mNotifyTask.run();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
Runnable mNotifyTask = new Runnable() {
@Override
public void run() {
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
myPosition = session.getLocation();
radius = session.getNotificationRadius();
pollFrequency = session.getNotificationPollFreq() * 1000; //TODO add minutes
notifyEnabled = session.getNotificationEnabled();
Log.d(this.toString(), "Run Notification Task. Notifications enabled = "+notifyEnabled);
if ((myPosition != null) && (myPosition.latitude != 0.0) && (myPosition.longitude != 0.0)) {
String lastNotificationTime = "";
if (session.getLastNotification().equals("")) {
lastNotificationTime = user.get(SessionManager.KEY_LASTLOGIN_AT);
} else {
lastNotificationTime = session.getLastNotification();
}
Log.d(this.toString(), "Lookup location with position: " + myPosition + " Radius: "+radius+" PollFrequency: "+pollFrequency+" lastNotifyTime: " + lastNotificationTime);
StringRequest strReq = getStringRequestIncidentsFromAreaAndTime(myPosition.latitude, myPosition.longitude, radius, lastNotificationTime);
String tag_string_req = "req_incidents";
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
mNotifyHandler.postDelayed(mNotifyTask, pollFrequency);
}
};
private StringRequest getStringRequestIncidentsFromAreaAndTime(final Double latitude, final Double longitude, final int radius, final String time) {
return new StringRequest(Request.Method.POST, AppConfig.URL_REGISTER, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "Incident notifications: " + response);
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
JSONArray notification = jObj.getJSONArray("msg");
sentNotification(notification);
} else {
String errorMsg = jObj.getString("error_msg");
Log.e(TAG, "Error getting incident notification (server returned error): " + errorMsg);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error getting incident notification: " + error.getMessage());
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("tag", "getincidentsinareaandtime");
params.put("uid", user.get(SessionManager.KEY_UID));
params.put("token", user.get(SessionManager.TOKEN));
params.put("latitude", Double.toString(latitude));
params.put("longitude", Double.toString(longitude));
params.put("radius", Integer.toString(radius));
params.put("time", "'"+time+"'");
return params;
}
};
}
private void sentNotification(JSONArray notification) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.logo_riskahead_header)
.setContentTitle("New incidents reported in your area!")
.setContentText(notification.length() + " new incidents near your last location. Watch out!");
Intent resultIntent = new Intent(this, MapsActivity.class);
try {
resultIntent.putExtra(EXTRA_MESSAGE, notification.getJSONObject(notification.length()-1).getDouble("latitude")+":"+notification.getJSONObject(notification.length()-1).getDouble("longitude"));
} catch (JSONException e) {
e.printStackTrace();
}
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MapsActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
int mId = 1;
mNotificationManager.notify(mId, mBuilder.build());
session.setLastNotification(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime()));
}
}

View File

@@ -10,6 +10,8 @@ import com.google.android.gms.maps.model.LatLng;
import java.util.HashMap;
public class SessionManager {
private static String TAG = SessionManager.class.getSimpleName();
SharedPreferences status;
@@ -41,6 +43,10 @@ public class SessionManager {
public static final String KEY_LOCATION_LNG = "location_longitude";
public static final String KEY_LAST_NOTIFICATION = "lastNotificationTime";
public static final String KEY_NOTIFY_ENABLED = "notifyEnabled" ;
public static final String KEY_NOTIFY_RADIUS = "notifyRadius";
public static final String KEY_NOTIFY_POLLINGFREQ = "notifyPollingfreq";
public static final String KEY_NOTIFY_GPS = "notifyGPSEnabled";
@@ -71,6 +77,15 @@ public class SessionManager {
return new LatLng(Double.longBitsToDouble(status.getLong(KEY_LOCATION_LAT, 0)), Double.longBitsToDouble(status.getLong(KEY_LOCATION_LNG, 0)));
}
public void setGPSForNotificationsEnabled(boolean isEnabled){
statusEditor.putBoolean(KEY_NOTIFY_GPS, isEnabled);
statusEditor.apply();
}
public boolean isGPSForNotificationsEnabled(){
return status.getBoolean(KEY_NOTIFY_GPS, false);
}
public void setLastNotification(String time){
statusEditor.putString(KEY_LAST_NOTIFICATION, time);
statusEditor.apply();
@@ -80,6 +95,34 @@ public class SessionManager {
return status.getString(KEY_LAST_NOTIFICATION, "");
}
public void setNotificationEnabled(boolean isEnabled){
statusEditor.putBoolean(KEY_NOTIFY_ENABLED, isEnabled);
statusEditor.apply();
}
public void setNotificationRadius(int radius){
statusEditor.putInt(KEY_NOTIFY_RADIUS, radius);
statusEditor.apply();
}
public void setNotificationPollFreq(int pollingFreqInMinutes){
statusEditor.putInt(KEY_NOTIFY_POLLINGFREQ, pollingFreqInMinutes);
statusEditor.apply();
}
public Boolean getNotificationEnabled(){
return status.getBoolean(KEY_NOTIFY_ENABLED, true);
}
public int getNotificationRadius(){
return status.getInt(KEY_NOTIFY_RADIUS, 5);
}
public int getNotificationPollFreq(){
return status.getInt(KEY_NOTIFY_POLLINGFREQ, 5);
}
public void addUser(String uid, String username, String name, String surname, String email, String status, String provider_type, String created_at, String updated_at, String lastlogin_at, String token) {
userDataEditor.putString(KEY_UID, uid); //UID
@@ -99,9 +142,6 @@ public class SessionManager {
Log.d(TAG, "New user written to sharedPreferences: " + uid);
}
/**
* Getting user data from database
* */
public HashMap<String, String> getUserDetails() {
HashMap<String, String> user = new HashMap<>();
@@ -122,7 +162,6 @@ public class SessionManager {
return user;
}
public void removeUser(){
userdata.edit().clear().apply();
}

View File

@@ -42,7 +42,7 @@
android:title="Notifications">
<SwitchPreference
android:key="notfiyEnable"
android:key="notifyEnable"
android:title="Show Notifications"
android:summary="Enable notifications in your area" />
@@ -62,6 +62,16 @@
android:summary="Decide how often notification updates should be received from server"
android:dialogTitle="Poll Frequency" />
<SwitchPreference
android:key="notifyEnableGPS"
android:title="Enable GPS"
android:summary="Get your last know location with GPS (GPS has to be activated in your device settings)" />
<Preference
android:key="notifyChooseLocation"
android:title="Choose your location"
android:summary="Your Location (Latitude/Longitude):" />
</PreferenceCategory>
</PreferenceScreen>