Android Studio notification on location changed Service - java

I made an app that suggests nearest Hospitals and Police Stations using Google API.
Now I want to make a new feature: to get notifications when i enter a new city. I know i have to create a Service (my app should work in background) and implement the functionality there. I have found how to get location updates in background here(Get GPS location via a service in Android).
I don't know what to modify to get notifications when I change location too (Like: You are now in city B) and how to call this new feature in MainActivity class
this is my sendMessage() mehtod (for notifications):
//notifications
public void sendMessage (String message , Intent intent){
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 , intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = "some_channel_id";
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle(getString(R.string.app_name))
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setBadgeIconType(NotificationCompat.BADGE_ICON_SMALL)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
assert notificationManager != null;
notificationManager.createNotificationChannel(channel);
}
assert notificationManager != null;
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
also this is the Service I want to modify:
public class LocationService extends Service {
private static final String TAG = "MyLocationService";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 1000;
private static final float LOCATION_DISTANCE = 10f;
private class LocationListener implements android.location.LocationListener {
Location mLastLocation;
public LocationListener(String provider) {
// Log.e(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location) {
Log.e(TAG, "onLocationChanged: " + location);
mLastLocation.set(location);
}
#Override
public void onProviderDisabled(String provider) {
// Log.e(TAG, "onProviderDisabled: " + provider);
}
#Override
public void onProviderEnabled(String provider) {
// Log.e(TAG, "onProviderEnabled: " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// Log.e(TAG, "onStatusChanged: " + provider);
}
}
/*
LocationListener[] mLocationListeners = new LocationListener[]{
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
*/
LocationListener[] mLocationListeners = new LocationListener[]{
new LocationListener(LocationManager.PASSIVE_PROVIDER)
};
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public void onCreate() {
// Log.e(TAG, "onCreate");
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.PASSIVE_PROVIDER,
LOCATION_INTERVAL,
LOCATION_DISTANCE,
mLocationListeners[0]
);
} catch (java.lang.SecurityException ex) {
// Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
// Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
/*try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
LOCATION_INTERVAL,
LOCATION_DISTANCE,
mLocationListeners[1]
);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}*/
}
#Override
public void onDestroy() {
//Log.e(TAG, "onDestroy");
super.onDestroy();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
// Log.i(TAG, "fail to remove location listener, ignore", ex);
}
}
}
}
private void initializeLocationManager() {
Log.e(TAG, "initializeLocationManager - LOCATION_INTERVAL: "+ LOCATION_INTERVAL + " LOCATION_DISTANCE: " + LOCATION_DISTANCE);
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
}

Related

Foreground service is sometimes restarting and sometimes never starts when app is removed from open apps

I am implementing location tracker from Android app by using foreground service.
The expectation is the foreground service should run even
when app is removed from recent open apps.
When app is in open/foreground.
When app is in background i.e. app is still open but went to background
The case 2 & 3 are working fine but case 1 is working weirdly.
In case 1, sometimes foreground service is getting restarted (notification is going off and coming back) after few seconds i.e. 1 to 3 seconds.
In some other times it is never restarted.
I want the foreground service to never go off. In short, I want it like whatsapp location tracking. The whatsapp tracking icon never goes off when the app is closed.
Please give any pointers on what else I am missing
Activity class
public void enableTracking(String planId, JSONArray trackList, CallbackContext callbackContext) {
Log.i(TAG,"In enableTracking");
Intent intent = new
Intent(cordova.getActivity().getApplicationContext(),LocationTracker.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
cordova.getActivity().startForegroundService(intent);
callbackContext.success("Location Tracking is enabled");
} else {
callbackContext.error("Build version is less than OREO");
}
}
public void disableTracking(CallbackContext callbackContext) {
Log.i(TAG,"In disableTracking");
Intent intent = new Intent(cordova.getActivity().getApplicationContext(),LocationTracker.class);
cordova.getActivity().stopService(intent);
callbackContext.success("Location Tracking is disabled");
}
Service class
public class LocationTracker extends Service {
private final IBinder mBinder = new MyBinder();
private static final String CHANNEL_ID = "2";
private static final String TAG = "LocationTracker";
private FusedLocationProviderClient mFusedLocationClient;
RequestQueue mRequestQueue;
public LocationTracker() {
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Override
public void onTaskRemoved(Intent rootIntent) {
Log.i(TAG, "onTaskRemoved");
super.onTaskRemoved(rootIntent);
}
#Override
public void onCreate() {
super.onCreate();
buildNotification();
// logic to start location tracking
}
#Override
public void onDestroy() {
super.onDestroy();
// logic to stop tracking
}
private void fetchAndSendLocation() {
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
if (ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Log.e(TAG, "No permission to fetch location");
return;
}
// mFusedLocationClient.getCurrentLocation()
Task fetchLocTask = mFusedLocationClient.getLastLocation();
fetchLocTask.addOnSuccessListener(new OnSuccessListener() {
#Override
public void onSuccess(Object o) {
Location loc = (Location) o;
if (loc != null) {
Log.i(TAG, "Lat " + loc.getLatitude() + " lon " + loc.getLongitude() + " date " + (new Date()).toString());
postLocation(loc);
}
}
});
}
private void buildNotification() {
String stop = "stop";
PendingIntent broadcastIntent = PendingIntent.getBroadcast(
this, 0, new Intent(stop), PendingIntent.FLAG_UPDATE_CURRENT);
// Create the persistent notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle(getString(R.string.app_name))
.setContentText("Location tracking is working")
.setOngoing(true)
.setContentIntent(broadcastIntent);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, getString(R.string.app_name),
NotificationManager.IMPORTANCE_DEFAULT);
channel.setShowBadge(false);
channel.setDescription("Location tracking is in progress");
channel.setSound(null, null);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.createNotificationChannel(channel);
}
startForeground(1, builder.build());
}
public class MyBinder extends Binder {
public LocationTracker getService() {
return LocationTracker.this;
}
}
}
AndroidManifest.xml
<service android:enabled="true" android:exported="true" android:foregroundServiceType="location" android:name=".LocationTracker" />
Using LocationManager as in code below has solved this similar situation for me.
public class MyLocationService extends Service {
private static final String TAG = "MyLocationService";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 1000;
private static final float LOCATION_DISTANCE = 10f;
private class LocationListener implements android.location.LocationListener {
Location mLastLocation;
public LocationListener(String provider) {
Log.e(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location) {
Log.e(TAG, "onLocationChanged: " + location);
mLastLocation.set(location);
}
#Override
public void onProviderDisabled(String provider) {
Log.e(TAG, "onProviderDisabled: " + provider);
}
#Override
public void onProviderEnabled(String provider) {
Log.e(TAG, "onProviderEnabled: " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.e(TAG, "onStatusChanged: " + provider);
}
}
LocationListener[] mLocationListeners = new LocationListener[]{
new LocationListener(LocationManager.PASSIVE_PROVIDER)
};
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public void onCreate() {
Log.e(TAG, "onCreate");
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.PASSIVE_PROVIDER,
LOCATION_INTERVAL,
LOCATION_DISTANCE,
mLocationListeners[0]
);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
}
#Override
public void onDestroy() {
Log.e(TAG, "onDestroy");
super.onDestroy();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listener, ignore", ex);
}
}
}
}
private void initializeLocationManager() {
Log.e(TAG, "initializeLocationManager - LOCATION_INTERVAL: "+ LOCATION_INTERVAL + " LOCATION_DISTANCE: " + LOCATION_DISTANCE);
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
}
You could modify this to suit your need.

Unable to send data to Firebase in a back ground service

Sending data to the Firebase but unable to send, my service crash but application still running and when I remove the Firebase code, service runs correctly.
I just want to upload the data to the Firebase with the current location. Every thing is working perfect but Firebase is not sending data to the database but it works with the same code in the activity.
Starting service,
public class location_service extends Service
{
private static final String TAG = "BOOMBOOMTESTGPS";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 50000;
private static final float LOCATION_DISTANCE = 10f;
DatabaseReference databasecustomer;
private class LocationListener implements android.location.LocationListener
{
Location mLastLocation;
public LocationListener(String provider)
{
Log.e(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location)
{
Log.e("onLocationChanged: " ,"");
mLastLocation.set(location);
String lats= "s";
String lngs= "s";
databasecustomer= FirebaseDatabase.getInstance().getReference("Labor");
String id= databasecustomer.push().getKey();
send_request send_request=new send_request(id,lats,lngs);
databasecustomer.child(id).setValue(send_request);
Toast.makeText(getApplicationContext(),"This is my toast message"+id,Toast.LENGTH_LONG).show();
}
#Override
public void onProviderDisabled(String provider)
{
Log.e(TAG, "onProviderDisabled: " + provider);
}
#Override
public void onProviderEnabled(String provider)
{
Log.e(TAG, "onProviderEnabled: " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
Log.e(TAG, "onStatusChanged: " + provider);
}
}
LocationListener[] mLocationListeners = new LocationListener[] {
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
#Override
public IBinder onBind(Intent arg0)
{
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public void onCreate()
{
Log.e(TAG, "onCreate");
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}
}
#Override
public void onDestroy()
{
Log.e(TAG, "onDestroy");
super.onDestroy();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listners, ignore", ex);
}
}
}
}
private void initializeLocationManager() {
Log.e(TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
}
It may be because of the security of database in firebase, change the rule of your database to
{
"rules": {
".read": true,
".write": true
}
}
make sure that your android studio is connected to firebase and to firebase database

How can I get my location without adding Map fragment on Activity in android?

I got location permission and made service , however I don't know how to get My Location from service without adding Map fragment.
I need to get my location and set Text on my TextView. //I don't need to get fragment at this activity
do I need to use post method in TextView? and How can I get Location from Service?
Please Help me! thanks
this is my MainActivity.java extends PermissionActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
switch (compoundButton.getId()) {
case R.id.locationSwitch:
Constants.checkFineLocationPermission(MainActivity.this);
if(compoundButton.isChecked()){
Intent intent = new Intent(MainActivity.this, LocationService.class);
startService(intent);
}else {
Intent intent = new Intent(MainActivity.this, LocationService.class);
stopService(intent);
}
break;
}
}
and this is PermissionActivity.
public void onRequestPermissionsResult(int requestCode, String permissions[],int[] grantResults){
switch (requestCode){
case MY_PERMISSIONS_REQUEST_FINE_LOCATION:{
if(grantResults.length>0 && grantResults[0]== PackageManager.PERMISSION_GRANTED){
Intent intent = new Intent(getApplicationContext(),getClass());
startActivity(intent);
finish();
}else{
// Log.d("Permission always denyed");
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
.setData(Uri.parse("package:"+ getApplicationContext().getPackageName()));
startActivity(intent);
}
return;
}
}
}
and this is service
private class LocationListener implements android.location.LocationListener
{
Location mLastLocation;
public LocationListener(String provider)
{
Log.e(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location)
{
Log.e(TAG, "onLocationChanged: " + location);
mLastLocation.set(location);
}
#Override
public void onProviderDisabled(String provider)
{
Log.e(TAG, "onProviderDisabled: " + provider);
}
#Override
public void onProviderEnabled(String provider)
{
Log.e(TAG, "onProviderEnabled: " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
Log.e(TAG, "onStatusChanged: " + provider);
}
}
LocationListener[] mLocationListeners = new LocationListener[] {
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
#Override
public IBinder onBind(Intent arg0)
{
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public void onCreate()
{
Log.e(TAG, "onCreate");
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}
}
#Override
public void onDestroy()
{
Log.e(TAG, "onDestroy");
super.onDestroy();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listners, ignore", ex);
}
}
}
}
private void initializeLocationManager() {
Log.e(TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
}
You should use Google Fused Location Service. It's provides most accurate position. Take a tutorial here and here. So basically just put this stuff into service.

How to send UID value from GPS service to next class public void onLocationChanged Android

We are working on logistics app on Android. App will start independent GPS service that is sending location on change to web server (Apache). GPS service starts with UID and Android Studio log shows that GPS service has this UID working. The problem is that lat and long values are coming to server corretly but UID is simple "0". How can we make GPS service to send UID correctly to server?
Here is the code as it is working right now:
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import java.util.HashMap;
public class MyService extends Service
{
private static final String TAG = "BOOMBOOMTESTGPS";
private LocationManager mLocationManager = null;
private static String UID = null;
private static final int LOCATION_INTERVAL = 5000;
private static final float LOCATION_DISTANCE = 10f; // 10f
private class LocationListener implements android.location.LocationListener // private // public
{
Location mLastLocation;
//public String UID;
public LocationListener(String provider)
{
Log.e(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location)
{
Log.e(TAG, "onLocationChanged: " + location);
mLastLocation.set(location);
//Intent intent = new Intent(this, MyService.class);
HashMap<String, String> data = new HashMap<String, String>();
data.put("id", UID); // SIIN SOOVIN KÄTTE SAADA VÄÄRTUST!!!!
//data.put("id2", iddata);
data.put("lat", Double.toString(location.getLatitude()));
data.put("lng", Double.toString(location.getLongitude()));
AsyncHttpPost asyncHttpPost = new AsyncHttpPost(data);
asyncHttpPost.setListener(new AsyncHttpPost.Listener(){
#Override
public void onResult(String result) {
// do something, using return value from network
}
});
asyncHttpPost.execute("https://www.isekallur.ee/android/read_gps2.php");
Log.e(TAG, "DATA: " + data);
}
// private void postText(){
//}
#Override
public void onProviderDisabled(String provider)
{
Log.e(TAG, "onProviderDisabled: " + provider);
}
#Override
public void onProviderEnabled(String provider)
{
Log.e(TAG, "onProviderEnabled: " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
Log.e(TAG, "onStatusChanged: " + provider);
}
}
LocationListener[] mLocationListeners = new LocationListener[] {
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
#Override
public IBinder onBind(Intent intent)
{
return null;
}
/*#Override
protected void onHandleIntent(Intent intent) {
String myID = intent.getExtras().getString("USER_ID");
}*/
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
String iddata =(String) intent.getExtras().get("USER_ID");
final String UID = intent.getStringExtra("USER_ID");
//doSomething2(UID);
Log.e(TAG, "UID: " + UID + " - " + iddata);
//postID(UID);
return START_STICKY; // START_STICKY_COMPATIBILITY // START_STICKY
}
/*private void postID(String UID){
Log.e(TAG, "UID2: " + UID);
}*/
#Override
public void onCreate()
{
Log.e(TAG, "onCreate");
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}
}
#Override
public void onDestroy()
{
Log.e(TAG, "onDestroy");
super.onDestroy();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listners, ignore", ex);
}
}
}
}
private void initializeLocationManager() {
Log.e(TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
}

Intent not being registered through Broadcast Listener

I have been trying for a long time to figure out how to send data from the service class to the mainactivity class. I am using broadcast receivers right now to do it. The issue is that they aren't being received in the MainActivity class.
public class MyService extends Service {
//all my code for the service which takes the users gps location.
private static final String TAG = "Hello";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 10;//change this for time
private static final float LOCATION_DISTANCE = 0f;//change this to get it every distance
private static final String MY_ACTION = "MY_ACTION";
private final Handler handler = new Handler();
Intent intent;
private class LocationListener implements android.location.LocationListener {
Location mLastLocation;
public LocationListener(String provider) {
//Log.e(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location) {
//Log.e(TAG, "onLocationChanged: " + location.toString());
mLastLocation.set(location);
}
#Override
public void onProviderDisabled(String provider) {
Log.e(TAG, "onProviderDisabled: " + provider);
}
#Override
public void onProviderEnabled(String provider) {
Log.e(TAG, "onProviderEnabled: " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.e(TAG, "onStatusChanged: " + provider);
}
}
//different possible uses for locations
LocationListener[] mLocationListeners = new LocationListener[]{
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
#Override
public IBinder onBind(Intent arg0) {
return null;
}
//the start of the activity sends data every 5 seconds
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 1000); // 1 second
return START_STICKY;
}
#Override
public void onCreate() {
Log.e(TAG, "onCreate");
//initializes locationManager
initializeLocationManager();
try {
Toast.makeText(MyService.this, "It Works", Toast.LENGTH_SHORT).show();
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}
}
private void initializeLocationManager() {
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
DisplayLoggingInfo();
handler.postDelayed(this, 5000); // 5 seconds delay
}
};
private void DisplayLoggingInfo() {
Log.d(TAG, "entered DisplayLoggingInfo");
intent = new Intent();
initializeLocationManager();
try {
Toast.makeText(MyService.this, "It Works", Toast.LENGTH_SHORT).show();
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
intent.putExtra("Latitude", mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLatitude());
intent.putExtra("Longitude", mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLongitude());
sendBroadcast(intent);
Log.i(TAG,"intent sent");
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}
}
}
The data is sent. When I try to access it from MainActivity, though, it doesn't seem to get it.
public class MainActivity extends AppCompatActivity {
public SimpleLocation location;
Intent intent;
double latitude;
double longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
//Sets views for Android
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
startService(new Intent(this, MyService.class));
intent = new Intent(this, MyService.class);
LocalBroadcastManager.getInstance(this).registerReceiver(
broadcastReceiver, new IntentFilter());
Toast.makeText(MainActivity.this, "" + latitude, Toast.LENGTH_SHORT).show();
}
//sets up broadcast Reciever
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Double latitude = intent.getDoubleExtra("Latitude", 0);
Double longitude = intent.getDoubleExtra("Longitude", 0);
Log.d("hello", "It came this far");
Log.d("hello", " " + latitude);
Log.d("hello", " " + longitude);
TextView txtDateTime = (TextView) findViewById(R.id.textView);
txtDateTime.setText(latitude.toString());
}
};
#Override
public void onResume() {
super.onResume();
startService(intent);
registerReceiver(broadcastReceiver, new IntentFilter());
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
stopService(intent);
}
}
Does anyone know what I am doing wrong?
First,you should add an action to your intent be sent,assume is location,then replace
intent.putExtra("Latitude", mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLatitude());
intent.putExtra("Longitude", mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLongitude());
sendBroadcast(intent);
with
intent.setAction("location");
intent.putExtra("Latitude", mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLatitude());
intent.putExtra("Longitude", mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLongitude());
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
And replace
LocalBroadcastManager.getInstance(this).registerReceiver(
broadcastReceiver, new IntentFilter());
with
IntentFilter filter = new IntentFilter("location");
LocalBroadcastManager.getInstance(this).registerReceiver(
broadcastReceiver, filter);
And you should register receiver before start service,so replace
#Override
public void onResume() {
super.onResume();
startService(intent);
registerReceiver(broadcastReceiver, new IntentFilter());
}
with
#Override
public void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, new IntentFilter());
startService(intent);
}
And since you have register in onResume,so you can remove
LocalBroadcastManager.getInstance(this).registerReceiver(
broadcastReceiver, new IntentFilter());
from your onCreate method.
You need to add some actions in intent filter when you register the receiver and at the time of send broadcast you need to set this action to your intent.

Categories

Resources