ClasscastException in LauncherActivity - android

i am getting ClasscastException when launching my app the problem is in TaxiTwinApplication app = (TaxiTwinApplication)getApplication(); this is the Activity A which i am trying to call method from other class
public class LauncherActivity extends Activity {
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
Intent intent;
TaxiTwinApplication app = (TaxiTwinApplication)getApplication();
app.register();
switch (TaxiTwinApplication.getUserState()) {
case NOT_SUBSCRIBED:
case SUBSCRIBED:
intent = new Intent(this, MainActivity.class);
intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK);
break;
case PARTICIPANT:
intent = new Intent(this, MyTaxiTwinActivity.class);
intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK);
break;
case OWNER:
intent = new Intent(this, MyTaxiTwinActivity.class);
intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK);
break;
default:
intent = new Intent(this, MainActivity.class);
intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK);
}
startActivity(intent);
finish();
}
}
public class TaxiTwinApplication extends Application {
private static int pendingNotificationsCount = 0;
private static UserState userState = NOT_SUBSCRIBED;
private ServicesManagement servicesManagement;
private LocationListener locationListener;
#Override
public void onCreate() {
super.onCreate();
}
public void unregister() {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.removeUpdates(locationListener);
}
public void register() {
servicesManagement = new ServicesManagement(this);
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
locationUpdate(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 3, this);
}
public void onProviderDisabled(String provider) {
}
};
//every 10 seconds and at least 3 meters
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 3, locationListener);
}
private void locationUpdate(Location location) {
GcmHandler gcmHandler = new GcmHandler(this);
gcmHandler.locationChanged(location);
}
public static int getPendingNotificationsCount() {
return pendingNotificationsCount;
}
public static void setPendingNotificationsCount(int pendingNotifications) {
pendingNotificationsCount = pendingNotifications;
}
public static UserState getUserState() {
return userState;
}
public static void setUserState(UserState userState) {
TaxiTwinApplication.userState = userState;
}
public static void exit(Context context) {
GcmHandler gcmHandler = new GcmHandler(context);
if (userState == UserState.OWNER || userState == UserState.PARTICIPANT) {
gcmHandler.leaveTaxiTwin();
}
gcmHandler.unsubscribe();
TaxiTwinApplication app = (TaxiTwinApplication) context.getApplicationContext();
app.unregister();
DbHelper dbHelper = new DbHelper(context);
dbHelper.deleteTables(dbHelper.getWritableDatabase());
android.os.Process.killProcess(android.os.Process.myPid());
}
}

<application
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:name="com....TaxiTwinApplication">

Related

The requestLocationUpdates to get GPS not work

I am new to Android and try to have one example to get GPS location.
I surf through the web and have following code.
The program will crash once I click the button to get a GPS.
I found it seems something wrong when I call locationManager.requestLocationUpdates(commandStr, 1000, 0, locationListener);
I trace it into requestLocationUpdates and found it crashed at Looper class
public final class Looper {
Looper(boolean quitAllowed) {
throw new RuntimeException("Stub!");
}
public static void prepare() {
throw new RuntimeException("Stub!");
}
public static void prepareMainLooper() {
throw new RuntimeException("Stub!");
}
public static Looper getMainLooper() {
throw new RuntimeException("Stub!");
}
public static void loop() {
throw new RuntimeException("Stub!");
}
Following are the complete code, ,dose anyone know which part of program is wrong
public class MainActivity extends AppCompatActivity {
private TextView tvLocation;
private Button btGetLocation;
private LocationManager locationManager;
private String commandStr;
private static final int MY_PERMISSION_ACCESS_COARSE_LOCATION = 11;
public LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
tvLocation.setText("經度" + location.getLongitude() + "\n緯度" + location.getLatitude());
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
commandStr = LocationManager.GPS_PROVIDER;
// LocationManager.GPS_PROVIDER //使用GPS定位
// LocationManager.NETWORK_PROVIDER //使用網路定位
tvLocation = (TextView) findViewById(R.id.textView);
btGetLocation = (Button) findViewById(R.id.button);
btGetLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// LocationManager可以用來獲取當前的位置,追蹤設備的移動路線
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
MY_PERMISSION_ACCESS_COARSE_LOCATION);
return;
}
locationManager.requestLocationUpdates(commandStr, 1000, 0, locationListener);
// 事件的條件設定為時間間隔1秒,距離改變0米,設定監聽位置變化
Location location = locationManager.getLastKnownLocation(commandStr);
if (location != null)
tvLocation.setText("經度"+location.getLongitude()+"\n緯度"+location.getLatitude());
else
tvLocation.setText("定位中");
// location.getLongitude() //取得經度
// location.getLatitude() //取得緯度
// location.getAltitude() //取得海拔高度
}
});
}
}
Here some code example:
public class Activity extends AppCompatActivity{
//variables for GPS data
private LocationManager locationManager;
private Location location;
private int minTime = 1000 //=1s
private int minDistance = 5 //=5m
private List<String> providers;
private final ActivityLocationListener locationListener = new ActivityLocationListener();
#Override
protected void onCreate(){
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout_file);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
providers = locationManager.getProviders(true);
//this will print you the available providers in your LogCat
//in some virtual devices network is not available
Log.d(NoteMapActivity.this.getClass().getSimpleName(), "available providers:\n" + providers);
}
public void onButtClick(View view){
this.requestLocationUpdates();
}
public void requestLocationUpdates(){
locationManager = (LocationManager) getSystemService(LOCATON_SERVICE);
//with this following code you will call onLocationChanged()
if (providers.contains("gps")){
//"permisson check"
try {
locationManager.requestLocationUpdates("gps", minTime, minDistance, locationListener);
} catch (SecurityException ex){
Log.e(getClass().getSimpleName(), "no permisson: " + ex.toString());
}
//if gps is not available you can use "network" or "passive" instead, maybe with if-else conditions
}
//create a class inside of this one!
class ActivityLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location location) {
currentLocation = location;
Log.d(NoteMapActivity.this.getClass().getSimpleName(), "received location:\n" + currentLocation.getLatitude() + ", " + currentLocation.getLongitude());
addCurrentLocationMarkerToMap();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
}

How to lock my screen and my app will continue running

I have an app that records users location and draws a polyline.I want to know how to do that when the user locks his screen.I've implemented a foreground service so the user can do whatever he wants in his phone but it doesn't work if the user turns the screen off.Any ideas?I've seen the wake lock but they are only for not letting the screen turned off.
UPDATE
Here is the foreground service that runs when the user presses a button from the activity
public class MyForeGroundService extends Service implements LocationListener {
private static final String TAG_FOREGROUND_SERVICE = "FOREGROUND_SERVICE";
public static final String ACTION_START_FOREGROUND_SERVICE = "ACTION_START_FOREGROUND_SERVICE";
public static final String ACTION_STOP_FOREGROUND_SERVICE = "ACTION_STOP_FOREGROUND_SERVICE";
public static final String ACTION_PAUSE = "ACTION_PAUSE";
public static final String ACTION_PLAY = "ACTION_PLAY";
public static PolylineOptions line;
private LocationManager locationManager;
public static int steps = 0;
public MyForeGroundService() {
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
super.onCreate();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
3000,
1, this);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
String action = intent.getAction();
switch (action) {
case ACTION_START_FOREGROUND_SERVICE:
startForegroundService();
break;
case ACTION_STOP_FOREGROUND_SERVICE:
stopForegroundService();
break;
case ACTION_PLAY:
Intent openMap= new Intent(this,Map.class);
startActivity(openMap);
break;
case ACTION_PAUSE:
break;
}
}
return super.onStartCommand(intent, flags, startId);
}
/* Used to build and start foreground service. */
private void startForegroundService() {
Log.d(TAG_FOREGROUND_SERVICE, "Start foreground service.");
// Create notification default intent.
Intent intent = new Intent(this,Map.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
// Create notification builder.
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
//Go back to Map activity if user press at the notification
builder.setContentIntent(pendingIntent)
.setContentTitle("gEKOning...")
.setContentText("Tap to open gEKOn app");
builder.setWhen(System.currentTimeMillis());
builder.setSmallIcon(R.mipmap.ic_launcher);
Bitmap largeIconBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.strava);
builder.setLargeIcon(largeIconBitmap);
// Make the notification max priority.
builder.setPriority(Notification.PRIORITY_MAX);
// Make head-up notification.
builder.setFullScreenIntent(pendingIntent, true);
// Build the notification.
Notification notification = builder.build();
// Start foreground service.
startForeground(1, notification);
}
private void stopForegroundService() {
Log.d(TAG_FOREGROUND_SERVICE, "Stop foreground service.");
// Stop foreground service and remove the notification.
stopForeground(true);
// Stop the foreground service.
stopSelf();
}
#Override
public void onLocationChanged(Location location) {
String locationProvider = LocationManager.NETWORK_PROVIDER;
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
location = locationManager.getLastKnownLocation(locationProvider);
try {
line.add(new LatLng(location.getLatitude(), location.getLongitude()));
GMap.addMarker(new MarkerOptions().position(new LatLng(location.getLatitude(), location.getLongitude())).title(""));
GMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 16.0f));
steps++;
} catch (NullPointerException e) {
//Toast.makeText(this.getBaseContext(), "gyhg" + e.toString(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
you can create a background service that it works when user lock screen or close your app from background
you must create service with this way:
first create a Service class like this:
public class LocationService extends Service implements GoogleApiClient.ConnectionCallbacks {
public static double latitude;
public static double longitude;
private int retryGPS = 0;
private int retryNetwork = 0;
private Handler handler;
private Runnable runnable;
private GoogleApiClient mGoogleApiClient;
private LocationManager mLocationManager;
private LocationListener[] mLocationListeners = new LocationListener[]{
new LocationListener(LocationManager.GPS_PROVIDER),
};
private static final int LOCATION_INTERVAL = 0;
private static final float LOCATION_DISTANCE = 1;
private static final String TAG = "LocationService";
#Override
public void onCreate() {
buildGoogleApiClient();
initializeLocationManager();
locationRequest();
handler = new Handler();
runnable = new Runnable() {
#Override
public void run() {
sendLocation();
}
};
sendLocation();
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.build();
}
private void initializeLocationManager() {
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
private void locationRequest() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
}
private void sendLocation() {
//TODO: you can use location here
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(final Intent intent, int flags, int startId) {
if (!mGoogleApiClient.isConnected())
mGoogleApiClient.connect();
return START_STICKY;
}
#Override
public void onConnected(Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
} else {
try {
Thread.sleep(3000);
onConnected(null);
} catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onDestroy() {
handler.removeCallbacks(runnable);
if (mLocationManager != null) {
for (LocationListener mLocationListener : mLocationListeners) {
try {
mLocationManager.removeUpdates(mLocationListener);
} catch (Exception e) {
e.printStackTrace();
}
}
}
super.onDestroy();
}
private class LocationListener implements android.location.LocationListener, ActivityCompat.OnRequestPermissionsResultCallback {
Location mLastLocation;
public LocationListener(String provider) {
Log.d(TAG, "LocationListener: " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(final Location location) {
mLastLocation.set(location);
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.d(TAG, "onLocationChanged: { latitude: " + latitude + " ,longitude: " + longitude + " , accuracy: " + location.getAccuracy() + " }");
}
#Override
public void onProviderDisabled(String provider) {
Log.d(TAG, "onProviderDisabled: " + provider);
}
#Override
public void onProviderEnabled(String provider) {
Log.d(TAG, "onProviderEnabled: " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(TAG, "onStatusChanged: " + status);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
}
}
}
then register service in manifest:
<service
android:name=".service.LocationService"
android:enabled="true"
android:process=":process" />
then start service from any activity or fragment :
public static void mStopService(Context context) {
context.stopService(new Intent(context, LocationService.class));
}
public static void mStartService(Context context) {
context.startService(new Intent(context, LocationService.class));
}

Fragment BroadCast receiver not working

I'm making an app where I need to get constant location updates from a Service on a fragment, the problem is that the fragment is not getting the updates and I'm not sure what is the problem, here is the service:
public class GPService extends Service
{
private LocationManager locMan;
private Boolean locationChanged;
private Handler handler = new Handler();
static final int REQUEST_LOCATION = 1;
public static Location curLocation;
public static boolean isService = true;
public LocalBroadcastManager broadcast;
LocationListener gpsListener = new LocationListener() {
public void onLocationChanged(Location location) {
if (curLocation == null) {
curLocation = location;
locationChanged = true;
Intent intent= new Intent("GPSLocationUpdates");
intent.putExtra("latitud",curLocation.getLatitude());
intent.putExtra("latitud",curLocation.getLongitude());
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
}else if (curLocation.getLatitude() == location.getLatitude() && curLocation.getLongitude() == location.getLongitude()){
locationChanged = false;
return;
}else
locationChanged = true;
curLocation = location;
if (locationChanged)
locMan.removeUpdates(gpsListener);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status,Bundle extras) {
}
};
#Override
public void onCreate() {
super.onCreate();
curLocation = getBestLocation();
if (curLocation == null)
Toast.makeText(getBaseContext(),"Unable to get your location", Toast.LENGTH_SHORT).show();
else{
//Toast.makeText(getBaseContext(), curLocation.toString(), Toast.LENGTH_LONG).show();
}
isService = true;
broadcast= LocalBroadcastManager.getInstance(this);
}
final String TAG="LocationService";
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onLowMemory() {
super.onLowMemory();
}
#Override
public void onStart(Intent i, int startId){
handler.postDelayed(GpsFinder,1);
}
#Override
public void onDestroy() {
handler.removeCallbacks(GpsFinder);
handler = null;
Toast.makeText(this, "Stop services", Toast.LENGTH_SHORT).show();
isService = false;
}
public IBinder onBind(Intent arg0) {
return null;
}
public Runnable GpsFinder = new Runnable(){
public void run(){
Location tempLoc = getBestLocation();
if(tempLoc!=null)
curLocation = tempLoc;
tempLoc = null;
handler.postDelayed(GpsFinder,1000);
}
};
private Location getBestLocation() {
Location gpslocation = null;
Location networkLocation = null;
if(locMan==null){
locMan = (LocationManager) getApplicationContext() .getSystemService(Context.LOCATION_SERVICE);
}
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) {
//ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
}
else {
if(locMan.isProviderEnabled(LocationManager.GPS_PROVIDER)){
locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000, 1, gpsListener);
gpslocation = locMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Intent intent= new Intent("GPSLocationUpdates");
intent.putExtra("latitud",gpslocation.getLatitude());
intent.putExtra("longitud",gpslocation.getLongitude());
Log.wtf("COORDENATES TO SEND",gpslocation.getLatitude()+" "+gpslocation.getLongitude());
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
}
if(locMan.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,1000, 1, gpsListener);
networkLocation = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Intent intent= new Intent("GPSLocationUpdates");
Log.wtf("LAS COORDENADAS a enviar SON",networkLocation.getLatitude()+" "+networkLocation.getLongitude());
intent.putExtra("latitud",networkLocation.getLatitude());
intent.putExtra("longitud",networkLocation.getLongitude());
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
}
}
The service is initiated in the activity like this
startService(new Intent(this, GPService.class));
In the fragment this is how I create it and register it
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
receiver= new GPSReceiver();
//this.getActivity().registerReceiver(receiver, new IntentFilter());
db=Database.getInstance(this.getContext());
}
#Override
public void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter("GPSLocationUpdates");
getActivity().registerReceiver(receiver,filter);
}
#Override
public void onPause() {
getActivity().unregisterReceiver(receiver);
super.onPause();
}
Finally this is the reciever in the Fragment, I can't get it to get the info from the service, any ideas? I don't know what I'm doing wrong.
private class GPSReceiver extends BroadcastReceiver {
private LatLng changed;
public GPSReceiver()
{
changed= new LatLng(0,0);
}
#Override
public void onReceive(Context context, Intent intent) {
Log.wtf("RECIEVE", "IT IS IN BROADCAST");
if (intent.getAction().equals("GPSLocationUpdates"))
{
Log.wtf("RECIEVE1", "INTENT ARRIVES");
double lat= intent.getDoubleExtra("latitud",1);
double longi= intent.getDoubleExtra("longitud",1);
changed= new LatLng(lat,longi);
}
// String text = intent.getStringExtra("position");
}
public LatLng getChanged()
{
return changed;
}
}
The service seems to be working fine, I can see the coordinates in the console being send.
You're not registering you BroadcastReceiver to the LocalBroadcastManager. You're registering it to the global broadcast manager, but sending on the local.
Change:
#Override
public void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter("GPSLocationUpdates");
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(receiver,filter);
}
#Override
public void onPause() {
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(receiver);
super.onPause();
}

Current Location failed GoogleMap

I want to check if the GPS is on if it is should show the current location. If not it should ask to turn it on. If user click cancel or dont turn the coordinates will be set as basic. Unfortunetly allways choose the basic. Even if the GPS is of (i dont get the message to turn on GPS)
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
locationManagerr = (LocationManager) getSystemService(LOCATION_SERVICE);
currentLocation=new Location("location");
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.INTERNET}
, 10);
}
}else
getLocation();
log.i(TAG,"latitude "+currentLocation.getLatitude());
}
private Location getLocation(){
locationListener= new LocationListener() {
#Override
public void onLocationChanged(Location location) {
currentLocation=location;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(LocationFinder.this);
alertDialogBuilder.setMessage("GPS is off. Want to turn on GPS?")
.setCancelable(false)
.setPositiveButton("Turn On",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent callGPSSettingIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(callGPSSettingIntent);
}
});
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
currentLocation=setStartCoordinate();
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
};
return currentLocation;
}
private Location setStartCoordinate(){
Location primaryLocalization= new Location("Basic");
primaryLocalization.setLongitude(0);
primaryLocalization.setLatitude(0);
return primaryLocalization;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case 10:
try{
getLocation();
log.i(TAG,"latitude "+currentLocation.getLatitude());
}
catch (SecurityException ex){log.i(TAG,"security error");}
break;
default:
break;
}
}
This requires a lot of case handling and I am providing a complete implementation of the all the features you requested with brief explanations below.
1. Provide location permission in the manifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
2. Add location dependency in app's build.gradle
compile 'com.google.android.gms:play-services-location:9.2.1'
3. extend BroadcastReceiver and create GPSStatusReceiver
public class GPSStatusReceiver extends BroadcastReceiver {
private GpsStatusChangeListener mCallback;
private Context mContext;
public GPSStatusReceiver(Context context, GpsStatusChangeListener callback) {
mCallback = callback;
mContext = context;
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.location.PROVIDERS_CHANGED");
intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
context.registerReceiver(this, intentFilter);
}
public void unRegisterReceiver(){
Log.d("ali", "unRegisterReceiver");
mContext.unregisterReceiver(this);
}
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
Log.d("ali", "in PROVIDERS_CHANGED");
mCallback.onGpsStatusChange();
}
}
public interface GpsStatusChangeListener{
void onGpsStatusChange();
}
}
4. Create a class GPSLocation
public class GPSLocation implements
ConnectionCallbacks,
OnConnectionFailedListener,
LocationListener,
GPSStatusReceiver.GpsStatusChangeListener {
public static final int REQUEST_CHECK_SETTINGS = 100;
public static final int LOCATION_PERMISSION_REQUEST_CODE = 200;
private static final int PERMISSION_GRANTED = 0;
private static final int PERMISSION_DENIED = 1;
private static final int PERMISSION_BLOCKED = 2;
private GoogleApiClient mGoogleApiClient;
private Location mCurrentLocation;
private LocationCallback mCallback;
private Activity mActivity;
private Context mContext;
private LocationRequest mLocationRequest;
private GPSStatusReceiver mGPSStatusReceiver;
private long intervalMillis = 10000;
private long fastestIntervalMillis = 5000;
private int accuracy = LocationRequest.PRIORITY_HIGH_ACCURACY;
private boolean isInitialized = false;
private boolean isLocationEnabled = false;
private boolean isPermissionLocked = false;
public GPSLocation(Activity activity, LocationCallback callback) {
mActivity = activity;
mContext = activity.getApplicationContext();
mCallback = callback;
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(mContext)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
createLocationRequest();
mGPSStatusReceiver = new GPSStatusReceiver(mContext, this);
}
public void init(){
isInitialized = true;
if(mGoogleApiClient != null) {
if (mGoogleApiClient.isConnected()) {
requestPermission();
} else {
connect();
}
}
}
public void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(intervalMillis);
mLocationRequest.setFastestInterval(fastestIntervalMillis);
mLocationRequest.setPriority(accuracy);
}
public LocationRequest getLocationRequest() {
return mLocationRequest;
}
public void connect(){
if(mGoogleApiClient != null && isInitialized) {
mGoogleApiClient.connect();
}
}
public void disconnect(){
if(mGoogleApiClient != null && isInitialized) {
mGoogleApiClient.disconnect();
}
}
private void getLastKnownLocation(){
if(!mGoogleApiClient.isConnected()){
Log.d("ali", "getLastKnownLocation restart ");
mGoogleApiClient.connect();
}
else {
if (checkLocationPermission(mContext) && isLocationEnabled) {
Log.d("ali", "getLastKnownLocation read ");
if(mCurrentLocation == null) {
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
mCallback.onLastKnowLocationFetch(mCurrentLocation);
}
startLocationUpdates();
}else{
Log.d("ali", "getLastKnownLocation get permission ");
requestPermission();
}
}
Log.d("ali", "mCurrentLocation " + mCurrentLocation);
}
public void startLocationUpdates() {
if(checkLocationPermission(mContext)
&& mGoogleApiClient != null
&& mGoogleApiClient.isConnected()
&& isLocationEnabled) {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
}
public void stopLocationUpdates() {
if(mGoogleApiClient != null
&& mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.d("ali", "onConnected");
requestPermission();
}
#Override
public void onConnectionSuspended(int i) {
Log.d("ali", "onConnectionSuspended");
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.d("ali", "onConnectionFailed");
}
#Override
public void onLocationChanged(Location location) {
Log.d("ali", "onLocationChanged : " + location);
mCallback.onLocationUpdate(location);
}
#Override
public void onGpsStatusChange() {
Log.d("ali", "onGpsStatusChange");
if(isInitialized && !isPermissionLocked) {
if (!isLocationEnabled(mContext)) {
isLocationEnabled = false;
isPermissionLocked = true;
stopLocationUpdates();
requestPermission();
}
}
}
private void requestPermission(){
if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
String[] appPerm = new String[]{Manifest.permission.ACCESS_FINE_LOCATION};
ActivityCompat.requestPermissions(mActivity, appPerm, LOCATION_PERMISSION_REQUEST_CODE);
}else{
getLocationSetting();
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == GPSLocation.REQUEST_CHECK_SETTINGS) {
if (resultCode == Activity.RESULT_OK) {
getLastKnownLocation();
}else{
Toast.makeText(mContext, "Permission Denied", Toast.LENGTH_SHORT).show();
mCallback.onLocationSettingsError();
}
}
}
private void getLocationSetting(){
LocationSettingsRequest.Builder builder =
new LocationSettingsRequest
.Builder()
.addLocationRequest(mLocationRequest);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>(){
#Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
final LocationSettingsStates locationSettingsStates = result.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
Log.d("ali", "SUCCESS");
isLocationEnabled = true;
isPermissionLocked = false;
getLastKnownLocation();
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
Log.d("ali", "RESOLUTION_REQUIRED");
try {
status.startResolutionForResult(
mActivity,
REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
mCallback.onLocationSettingsError();
}finally {
isPermissionLocked = false;
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
Log.d("ali", "SETTINGS_CHANGE_UNAVAILABLE");
Toast.makeText(mContext, "Location Unavailable", Toast.LENGTH_SHORT).show();
mCallback.onLocationSettingsError();
isPermissionLocked = false;
break;
}
}
});
}
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
int permState;
switch (requestCode) {
case LOCATION_PERMISSION_REQUEST_CODE:
if (grantResults.length > 0) {
if(grantResults[0] != PackageManager.PERMISSION_GRANTED) {
if(!ActivityCompat.shouldShowRequestPermissionRationale(
mActivity,
Manifest.permission.ACCESS_FINE_LOCATION)){
permState = PERMISSION_BLOCKED;
}else{permState = PERMISSION_DENIED;}
}else {permState = PERMISSION_GRANTED;}
}
else{permState = PERMISSION_DENIED;}
switch (permState){
case PERMISSION_BLOCKED:
Toast.makeText(mContext,"Please give gps location permission to use the app.",Toast.LENGTH_LONG).show();
startInstalledAppDetailsActivity(mContext);
mCallback.onLocationPermissionDenied();
break;
case PERMISSION_DENIED:
Toast.makeText(mContext,"Permission Denied, app cannot access the gps location.", Toast.LENGTH_LONG).show();
break;
case PERMISSION_GRANTED:
getLocationSetting();
break;
}
break;
}
}
public static boolean isLocationEnabled(Context context){
LocationManager locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
boolean gpsEnabled = false;
boolean networkEnabled = false;
try {
gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch(Exception ex) {}
try {
networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception ex) {}
return gpsEnabled && networkEnabled;
}
public static void startInstalledAppDetailsActivity(final Context context) {
if (context == null) {
return;
}
final Intent i = new Intent();
i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
i.addCategory(Intent.CATEGORY_DEFAULT);
i.setData(Uri.parse("package:" + context.getPackageName()));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
context.startActivity(i);
}
public static boolean checkLocationPermission(Context context) {
String permission = "android.permission.ACCESS_FINE_LOCATION";
int res = context.checkCallingOrSelfPermission(permission);
return (res == PackageManager.PERMISSION_GRANTED);
}
public interface LocationCallback {
void onLastKnowLocationFetch(Location location);
void onLocationUpdate(Location location);
void onLocationPermissionDenied();
void onLocationSettingsError();
}
public void close() {
mGPSStatusReceiver.unRegisterReceiver();
}
}
5. In the activity use the below code
public class MainActivity extends AppCompatActivity implements GPSLocation.LocationCallback {
private GPSLocation mGPSLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGPSLocation = new GPSLocation(this, this);
mGPSLocation.init();
}
#Override
public void onLastKnowLocationFetch(Location location) {
if(location != null) {
Log.d("ali ", "onLastKnowLocationFetch " + location);
}
}
#Override
public void onLocationUpdate(Location location) {
if(location != null) {
Log.d("ali ", "onLocationUpdate " + location);
}
}
#Override
public void onLocationPermissionDenied() {
}
#Override
public void onLocationSettingsError() {
}
#Override
protected void onStart() {
mGPSLocation.connect();
super.onStart();
}
#Override
public void onResume() {
super.onResume();
mGPSLocation.startLocationUpdates();
}
#Override
protected void onPause() {
super.onPause();
mGPSLocation.stopLocationUpdates();
}
#Override
protected void onStop() {
mGPSLocation.disconnect();
super.onStop();
}
#Override
protected void onDestroy() {
mGPSLocation.close();
super.onDestroy();
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == GPSLocation.LOCATION_PERMISSION_REQUEST_CODE) {
mGPSLocation.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GPSLocation.REQUEST_CHECK_SETTINGS) {
mGPSLocation.onActivityResult(requestCode, resultCode, data);
}
}
}
The following code checks, if location is enabled or not. If not it shows alert dialog to enable location service.
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
}catch (Exception ex){}
try{
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}catch (Exception ex){}
if(!gps_enabled && !network_enabled){
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setMessage(getResources().getString(R.string.gps_network_not_enabled));
dialog.setPositiveButton(getResources().getString(R.string.open_location_settings), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
Startup.this.startActivity(myIntent);
}
});
dialog.setNegativeButton(getString(R.string.Cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
}
});
dialog.show();
}
add below code in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Add this override method for me its worked fine--
#Override
public void onLocationChanged(Location location) {
getLocation("onLocationChanged");
}

Why is my app showing high battery uses?

I am using google fused location api but still its showing high battery use. I am developing an app where I need to fetch user current location after that I don't need the fetch the location. Am an fetching the current location as below
public class MyLocationManager implements GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener {
private static MyLocationManager locationManager;
private static LocationClient locationclient;
public static final int LAT_KNOW_NLOCATION = 1005;
public static final int CURRENT_LOCATION = 1006;
public static final int CRON_LOCATION_UPDATE = 1007;
private static String LOCATION_CLIENT_NOT_FOUND_MESSAGE = "Error... Location client not found!";
private static Context context;
private static Activity currentActivity;
private static ProgressDialog progressDialog;
private static ILocationUpdator iLocationUpdator;
private static final int UPDATE_INTERVAL = 1000 * 30;
private static LocationManager androidLocationManager;
private static int CURRENTLY_LOOKING_FOR = 0;
private MyLocationManager(Context context) {
locationclient = new LocationClient(context, this, this);
MyLocationManager.context = context;
androidLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
}
public static synchronized MyLocationManager getLocationManagerInstance(Context context, ILocationUpdator iLocationUpdator, Activity activity) {
currentActivity = activity;
if (locationManager == null) {
locationManager = new MyLocationManager(context);
}
progressDialog = new ProgressDialog(currentActivity);
progressDialog.setCancelable(false);
progressDialog.setMessage("Please wait looking for current location");
MyLocationManager.iLocationUpdator = iLocationUpdator;
return locationManager;
}
public void getCurrentLocation() {
CURRENTLY_LOOKING_FOR = MyLocationManager.CURRENT_LOCATION;
callForLocationUpdate();
}
public void getlastKnownLocation() {
CURRENTLY_LOOKING_FOR = MyLocationManager.LAT_KNOW_NLOCATION;
callForLocationUpdate();
}
public void getCronLocationUpdate() {
CURRENTLY_LOOKING_FOR = MyLocationManager.CRON_LOCATION_UPDATE;
callForLocationUpdate();
}
private void callForLocationUpdate() {
System.out.println("callForLocationUpdate " + isProviderEnabled());
if (isProviderEnabled()) {
getReliventLocation(CURRENTLY_LOOKING_FOR);
}
else {
DialogUtility.showCallbackMessage("Please turn on GPS/Location service.", currentActivity, new AlertDialogCallBack() {
#Override
public void onSubmit() {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
currentActivity.startActivity(intent);
}
#Override
public void onCancel() {
}
#Override
public void onSubmitWithEditText(String text) {
}
});
}
}
private boolean isProviderEnabled() {
boolean gps_enabled = androidLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean network_enabled = androidLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (gps_enabled && network_enabled) {
return true;
}
else {
return false;
}
}
private void getReliventLocation(int lookingFor) {
Location location = null;
if (locationclient != null) {
currentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
progressDialog.show();
}
});
if (!locationclient.isConnected()) {
locationclient.connect();
}
else {
LocationRequest locationrequest = LocationRequest.create();
locationrequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
sendLocationUpdate(location, this);
}
};
switch (lookingFor) {
case MyLocationManager.LAT_KNOW_NLOCATION:
location = locationclient.getLastLocation();
sendLocationUpdate(location, null);
break;
case MyLocationManager.CURRENT_LOCATION:
locationrequest.setInterval(UPDATE_INTERVAL);
locationclient.requestLocationUpdates(locationrequest, locationListener);
break;
case MyLocationManager.CRON_LOCATION_UPDATE:
Intent mIntentService = new Intent(context, LocationService.class);
PendingIntent mPendingIntent = PendingIntent.getService(context, 1, mIntentService, 0);
locationrequest.setInterval(100);
locationclient.requestLocationUpdates(locationrequest, mPendingIntent);
break;
}
}
}
else {
showErrorMessage(LOCATION_CLIENT_NOT_FOUND_MESSAGE);
}
}
private void sendLocationUpdate(Location location, LocationListener locationListener) {
if (location != null) {
double lat = location.getLatitude();
double lon = location.getLongitude();
iLocationUpdator.getLocation(new LatLng(lat, lon), 0, "success..");
}
else {
iLocationUpdator.getLocation(new LatLng(0.0, 0.0), 1, "Some error occured..");
}
if (progressDialog != null) {
progressDialog.dismiss();
}
if (CURRENTLY_LOOKING_FOR == MyLocationManager.CURRENT_LOCATION) {
locationclient.removeLocationUpdates(locationListener);
}
}
private static void showErrorMessage(String message) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (iLocationUpdator != null)
iLocationUpdator.getLocation(new LatLng(0.0, 0.0), 1, "Connection Result...Error!");
if (progressDialog != null) {
progressDialog.dismiss();
}
}
#Override
public void onConnected(Bundle bundle) {
getReliventLocation(CURRENTLY_LOOKING_FOR);
}
#Override
public void onDisconnected() {
if (iLocationUpdator != null)
iLocationUpdator.getLocation(new LatLng(0.0, 0.0), 1, "Connection Disconnected...Error!");
if (progressDialog != null) {
progressDialog.dismiss();
}
}
}
Please point out what I am doing wrong.
I am unfamiliar with android location services, however I think you would be able to diagnose your battery usage using this free tool provided by AT&T.
Application Resource Optimizer:
https://developer.att.com/application-resource-optimizer
It looks like you might be polling for current location updates, each of these will effect battery life. ATT ARO can help identify this.

Categories

Resources