Service don't run like it should on real device - java

Problem is when I run service on emulator(android 4.0.3), then all is working(data is sent once per hour), but when i run it on my phone it's start sending data every minute. I can't figure out why, hope someone can help me with this.
The service is sending data to http://gprsbtn.herokuapp.com/coordinates where it's going to database.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.aravov.gprsbtn"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.aravov.gprsbtn.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="MyService"></service>
<receiver android:name=".AlarmReciever"/>
</application>
</manifest>
MainActivity.java
package com.aravov.gprsbtn;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
final String LOG_TAG = "myLogs";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void btnClc(View v) {
startService(new Intent(this, MyService.class));
Toast.makeText(this, "Service started", Toast.LENGTH_SHORT).show();
}
public void btnClc2(View v) {
stopService(new Intent(this, MyService.class));
}
}
GPSTracker.java
package com.aravov.gprsbtn;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
MyService.java
package com.aravov.gprsbtn;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.json.JSONObject;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class MyService extends Service {
PendingIntent pendingIntent;
AlarmManager alarmManager;
BroadcastReceiver mReceiver;
final String LOG_TAG = "myLogs";
public void onCreate() {
super.onCreate();
Log.d(LOG_TAG, "onCreate");
}
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(LOG_TAG, "onStartCommand");
someTask();
sendNotif();
return super.onStartCommand(intent, flags, startId);
}
public void sendNotif() {
Notification notification = new Notification(R.drawable.ic_stat_gprsbtn, "Text in status bar",
System.currentTimeMillis());
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, "Notification's title", "Notification's text", pendingIntent);
startForeground(1992, notification);
}
public void onDestroy() {
stop();
super.onDestroy();
Log.d(LOG_TAG, "onDestroy");
}
public IBinder onBind(Intent intent) {
Log.d(LOG_TAG, "onBind");
return null;
}
void someTask() {
mReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
action();
}
};
registerReceiver(mReceiver, new IntentFilter("gprs.post"));
pendingIntent = PendingIntent.getBroadcast( this, 0, new Intent("gprs.post"),0 );
alarmManager = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));
// timer here <<< 1000 * 60 = 1 minute
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 1000, 1000 * 60 * 60 , pendingIntent);
}
public void action() {
GPSTracker gps = new GPSTracker(MyService.this);
//final double latitude = gps.getLatitude();
//final double longitude = gps.getLongitude();
final String lat = Double.toString(gps.latitude);
final String lon = Double.toString(gps.longitude);
// check if GPS enabled
if(gps.canGetLocation())
{
//posting
Thread t = new Thread(){
public void run(){
postData(lat, lon);
}
};
t.start();
}
else
{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
public void postData(String latitude, String longitude) {
try {
HttpParams p = new BasicHttpParams();
HttpClient client = new DefaultHttpClient(p);
HttpPost post = new HttpPost("http://gprsbtn.herokuapp.com/coordinates");
JSONObject params = new JSONObject();
params.put("latitude",latitude);
params.put("longitude",longitude);
StringEntity ent = new StringEntity(params.toString());
post.setEntity(ent);
post.setHeader("Content-type", "application/json");
client.execute(post);
Log.d(LOG_TAG, "onDataSent");
} catch (Exception e) {
e.printStackTrace();
}
}
// stop the alarm receiver
public void stop() {
try {
unregisterReceiver(mReceiver);
Toast.makeText(this, "Service stoped", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
}
}
}

Related

java.lang.ClassCastException: com.example.BellasHBG.LocationService cannot be cast to com.google.android.gms.location.LocationListener

I'm getting
java.lang.ClassCastException: com.example.BellasHBG.LocationService cannot be cast to com.google.android.gms.location.LocationListener
but I don't know how to resolve. Removing keyword abstract does not fix the problem. This is new to me, and I'm not that knowledgeable of java so any help is appreciated. The error seems top be occurring in LocationService on the following line: LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mlocationRequest, (com.google.android.gms.location.LocationListener) this);
The intent is to get location updates and send a notification to the app user if the location sells this particular bakery product.
Below are my MainActivity, LocationService and AndroidManifest.xml
MainActivity
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.view.KeyEvent;
import android.webkit.WebViewClient;
import android.widget.TextView;
import com.google.android.gms.location.LocationRequest;
//import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private WebView webView = null;
public static boolean orignotifsetting = false;
//PendingIntent pendingIntent;
private Alarm alarm;
MyToolBox mtools = new MyToolBox();
LocationIntentService mLocationIntentService = new LocationIntentService();
public LocationManager mlocManager;
//LocationListener mlocListener = new MyLocationListener();
//LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//public static GoogleApiClient mGoogleApiClient;
private Location mCurrentLocation;
LocationRequest mLocationRequest;
PendingIntent resultPendingIntent;
public Intent resultIntent = new Intent();
LocationServiceImpl mLocationService = new LocationServiceImpl();
public static boolean prevNotificationsSetting;
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.i("myTag", "in onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//set the default values first time run but don't overwrite them if they have been set
// ----------------------------------------------------------------| - true will leave them alone, false will clear them every time
PreferenceManager.setDefaultValues(this, R.xml.pref_notification, true);
this.webView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
//myWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
//myWebView.setWebViewClient(new WebViewClient());
WebViewClientImpl webViewClient = new WebViewClientImpl(this);
webView.setWebViewClient(webViewClient);
webView.loadUrl("https://www.bellashbg.com");
mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && this.webView.canGoBack()) {
this.webView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public void onResume() {
Log.i("myTag", "in onResume");
super.onResume();
Intent msgIntent = new Intent(MainActivity.this, LocationService.class);
if ((mtools.notificationsSetting(this)) & (prevNotificationsSetting == false)) {
prevNotificationsSetting = true;
startService(msgIntent);
}
else {
if ((!mtools.notificationsSetting(this)) & (prevNotificationsSetting == true)) {
// mLocationService.stopLocationUpdates();
prevNotificationsSetting = false;
boolean result = stopService(msgIntent);
if (result){
Log.d("MainActivity", "stopService true");
}
else {
Log.d("MainActivity", "stopService false");
}
//mLocationService.stopLocationUpdates();
//android.os.Process.killProcess(android.os.Process.myPid());
}
}
}
#Override
public void onPause() {
Log.i("myTag", "in onPause");
super.onPause();
}
#Override
public void onStop() {
Log.i("myTag", "in onStop");
super.onStop();
}
public void onDestroy() {
Log.i("myTag", "in onDestroy");
super.onDestroy();
//if (mSensorManager!=null){mSensorManager.unregisterListener(listener);}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.i("myTag", "in onCreateOptionsMenu");
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.settings_menu, menu);
return super.onCreateOptionsMenu(menu); // cmnted 10/25/2015
//super.onCreateOptionsMenu(menu);
//return true;
// return true; stack overflow 6439085 says to return true to pop up menu
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.i("myTag", "in onOptionsItemSelected");
//LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); //added 11/12/2015 to remove updates
switch (item.getItemId()) {
case R.id.settings:
Intent settingsintent = new Intent(MainActivity.this, SettingsActivity.class);
MainActivity.this.startActivity(settingsintent);
break;
case R.id.help:
break;
case R.id.about:
break;
}
return true;
}
// Get the notifications status bar setting
public boolean notificationsSettingNotificationBar() {
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean notificationsNewMessageNotificationBar = SP.getBoolean("notifications_new_message_notification_bar", true);
return notificationsNewMessageNotificationBar;
}
// Get the notifications ringtone
public String notificationsSettingRingtone() {
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String notificationsNewMessageRingtone = SP.getString("notifications_new_message_ringtone", "NULL");
return notificationsNewMessageRingtone;
}
// Get the notifications vibrate setting
public boolean notificationsNewMessageSetting() {
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean notificationNewMessageVibrate = SP.getBoolean("notifications_new_message_vibrate", true);
return notificationNewMessageVibrate;
}
private TextView latituteField;
private Context mContext;
}
LocationService
package com.example.BellasHBG;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import androidx.core.app.NotificationCompat;
import androidx.core.app.TaskStackBuilder;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
//import com.google.android.gms.location.LocationListener;
//import android.support.v7.app.AppCompatActivity;
//import android.support.v4.app.NotificationCompat;
//import android.support.v4.app.TaskStackBuilder;
//import com.google.android.gms.common.ConnectionResult;
//import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
//import com.google.android.gms.location.LocationListener;
//import com.google.android.gms.location.LocationRequest;
//import com.google.android.gms.location.LocationServices;
/**
* Created by craigmartensen on 4/7/16.
*/
public abstract class LocationService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 60000 * 1; // 1000 milliseconds in 1 second
public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS / 5;
public static final long LOCATION_DISTANCE_IN_METERS = 3;
MyToolBox mtools = new MyToolBox();
public static GoogleApiClient mGoogleApiClient;
//public static GoogleSignInClient mSignInClient;
public static GoogleSignInAccount mSignInClient;
LocationRequest mlocationRequest;
private boolean isRemoving = false;
#Override
public IBinder onBind(Intent intent)
{
return null;
}
#SuppressWarnings("static-access")
#Override
public void onCreate() {
isRemoving = false;
mGoogleApiClient = new GoogleApiClient.Builder(getApplicationContext())
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
//alarm.SetAlarm(this);
//return START_STICKY;
super.onStartCommand(intent, flags, startId);
//Toast.makeText(this, "onHandleIntent", Toast.LENGTH_SHORT).show();
//mGoogleApiClient.connect();
Log.d("onStartCommand", "Service Started");
return Service.START_STICKY;
}
#Override
public void onConnected(Bundle connectionHint) {
if (isRemoving) {
stopLocationUpdates();
}
else {
isRemoving = false;
mlocationRequest = new LocationRequest();
mlocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mlocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mlocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mlocationRequest.setSmallestDisplacement(LOCATION_DISTANCE_IN_METERS);
Intent locationIntent = new Intent(getApplicationContext(), LocationIntentService.class);
locationIntent.putExtra("ID", "FusedLcation");
PendingIntent locationPendingIntent = PendingIntent.getService(getApplicationContext(), 0, locationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mlocationRequest, locationPendingIntent);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mlocationRequest, (com.google.android.gms.location.LocationListener) this);
}
}
public void onLocationChanged(Location loc)
{
Log.d("onLocationChanged", "Entering method");
//Toast.makeText(this, "onLocationChanged", Toast.LENGTH_SHORT).show();
mGoogleApiClient = new GoogleApiClient.Builder(getApplicationContext())
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
//Toast.makeText(getApplicationContext(), "entering onLocationChanged", Toast.LENGTH_SHORT).show();
String myText;
double mlat = loc.getLatitude();
double mlong = loc.getLongitude();
DBHelper myDBHelper = new DBHelper(this);
// use the following line if you just want to know if the location is found ie, sells Bellas
//boolean soldHere = myDBHelper.doesLocationSellBellas("my_table",41.685471,-73.975393);
// the following line retrieves the name of the location that sells bellas, null if it's not found
//String locName = myDBHelper.getLocationName("my_table", 41.685471, -73.975393);
String locName = myDBHelper.getLocationName(DBHelper.LOCATION_TABLE_NAME, mlat, mlong);
// set up for notification in the notification status bar
if (locName != null) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Bella's sold here");
// .setStyle(new NotificationCompat.BigTextStyle().bigText("Bella's sold here"));
// .setSubText(todaysjolt);
// .setDefaults(Notification.DEFAULT_SOUND)
//.setContentText("Bella's sold here");
// Gets an instance of the NotificationManager service
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Builds the notification and issues it.
mBuilder.setContentText(locName);
mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(locName));
// new 10/14/2015 - set up to allow user to go to website from notification
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, MainActivity.class);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(MainActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
// end new 10/14/2015
mNotifyMgr.notify(000, mBuilder.build());
Toast.makeText(getApplicationContext(), "You are at " + locName, Toast.LENGTH_SHORT).show();
//LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
}
protected void startLocationUpdates() {
if (mtools.notificationsSetting(this)) {
MainActivity.orignotifsetting = true;
//LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
public void stopLocationUpdates() {
if(!mGoogleApiClient.isConnected()){
isRemoving = true; //added
mGoogleApiClient.connect();
}
else {
//if (mGoogleApiClient != null) {
// if (!mGoogleApiClient.isConnected()) {
PendingIntent locationPendingIntent = PendingIntent.getService(this, 0, new Intent(this, LocationIntentService.class), PendingIntent.FLAG_UPDATE_CURRENT);
//LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, locationPendingIntent); //moved below 1/28/2016
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, (com.google.android.gms.location.LocationListener) com.example.BellasHBG.LocationService.this);
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
stopSelf(); // stop the service
}
//}
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Toast.makeText(this, "Connection Failed", Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionSuspended(int i) {
Log.d("LocationUpdateService", "Connection Suspended");
}
#Override
public void onDestroy(){
stopLocationUpdates();
//reportarGPS.interrupt();
//reportarGPS = null;
//LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, (com.google.android.gms.location.LocationListener) this);
//mGoogleApiClient.disconnect();
//mGoogleApiClient = null;
//mHandler.removeCallbacksAndMessages(null);
//Thread.currentThread().interrupt();
super.onDestroy();
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.BellasHBG">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
<uses-sdk android:minSdkVersion="15" android:targetSdkVersion="21"/>
<application
android:allowBackup="true"
android:icon="#drawable/bellas_logo_48x36"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.BellasHBG"
android:usesCleartextTraffic="true">
<activity
android:name="com.example.BellasHBG.SettingsActivity"
android:label="#string/action_settings"/>
<activity
android:name="com.example.BellasHBG.CreateNotificationOnBar"
android:label="create_notification_on_bar"/>
<activity
android:name="com.example.BellasHBG.CustomPreference"
android:label="custom_preference"/>
<activity
android:name=".MainActivity"
android:label="Bella's Home Baked Goods" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="com.example.BellasHBG.Alarm" />
<service android:enabled='true' android:name="com.example.BellasHBG.LocationService" />
</application>
</manifest>
Please uncomment the import for com.google.android.gms.location.LocationListener on LocationService and give a try again.

why my app crashes when i install my app on smartphone?

I have created an app which determines the speed of car using GPS/Network Provider.
Here is what I tried, the code is fine there is no errors but app crashes when I run it.
AndroidGPSTrackingActivity:
package com.example.muhammadshahid.smartsm;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class AndroidGPSTrackingActivity extends AppCompatActivity {
Button btnShowLocation;
// GPSTracker class
GPSTracker gps;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_android_gpstracking);
// show location button click event
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// create class object
gps = new GPSTracker(AndroidGPSTrackingActivity.this);
// check if GPS enabled
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// \n is for new line
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
});
}
}
GPSTracker:
package com.example.muhammadshahid.smartsm;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
/**
* Created by Muhammad Shahid on 2/23/2017.
*/
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
// check self permission
if (Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission
(mContext, android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission
(mContext, android.Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
}
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS() {
if ( Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission
( mContext, android.Manifest.permission.ACCESS_FINE_LOCATION )
!= PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission
( mContext, android.Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED)
{
//requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE_ASK_PERMISSIONS);
}
locationManager.removeUpdates(GPSTracker.this);
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will launch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
Activity_tracker_xml File:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_android_gpstracking"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.muhammadshahid.smartsm.AndroidGPSTrackingActivity">
<Button
android:text="ShowLocation"
android:id="#+id/btnShowLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="203dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Minifest.xml File:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.muhammadshahid.smartsm">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".AndroidGPSTrackingActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
setContentView(R.layout.activity_android_gpstracking);
btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
//add this line you missing the button declaration

Android GPS tracker returns 0.0 always

I am using the classic GPS tracker code to retrieve my current location, but I always get 0 as a return for both lat and lon, even though I try to change positions its still always 0. please note that I have used the following code in previews apps and it worked.
manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.apostolis.map1sttest">
<!-- Permition list bellow !-->
<uses-permission android:name="android.permission.INTERNET" /> <!-- internet -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <!-- internet 3g/4g enabled-->
<uses-permission android:name="android.permission.GET_ACCOUNTS" /> <!-- Google accounts -->
<uses-permission android:name="android.permission.NETWORK" /> <!-- internet -->
<uses-permission android:name="android.permission.USE_CREDENTIALS" /> <!-- Google acconts -->
<uses-permission android:name="android.permission.READ_PHONE_STATE"/> <!-- phone info -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <!-- GPS -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <!-- GPS -->
<uses-feature android:name="android.hardware.location.gps" /> <!-- GPS (needed for android 5.0+) -->
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
GPStracker.java
package com.example.apostolis.map1sttest;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.widget.Toast;
/**
* Created by Apostolis on 10/27/2016.
*/
public class GPStracker extends Service implements LocationListener {
private final Context context;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude;
double longituzzde;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 100;
protected LocationManager locationManager;
public GPStracker(Context context){
this.context = context;
getLocation();
}
public Location getLocation(){
try {
locationManager = (LocationManager)context.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(locationManager.NETWORK_PROVIDER);
if(!isGPSEnabled && !isGPSEnabled) {
} else {
this.canGetLocation = true;
if(isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if(isGPSEnabled) {
if(location == null) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if(locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
public void stopUsingGPS(){
if(locationManager != null) {
locationManager.removeUpdates(GPStracker.this);
}
}
public double getLatitude() {
if(location != null) {
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude(){
if(location != null) {
longitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("GPS SETTINGS");
alertDialog.setMessage("GPS is not enabled.Go to Settings menu and enable it?");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
}) ;
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
this.location = location;
getLatitude();
getLongitude();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
MainActivity.java
package com.example.apostolis.map1sttest;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
GPStracker gps;
private String lat,lon;
Button btnGetLocation;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private double mCurrentLatitude,mCurrentLongitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnGetLocation = (Button) findViewById(R.id.btgps);
//creating onClick listener for GPS.
btnGetLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
gps = new GPStracker(MainActivity.this);
if (gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
lat = Double.toString(latitude);
lon = Double.toString(longitude);
Toast.makeText(MainActivity.this,
"Your Location is: Lat: " + lat.toString() + " Lon:" + lon.toString(), Toast.LENGTH_LONG).show();
} else {
gps.showSettingsAlert();
}
}
});
};
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onConnected(#Nullable 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) {
// 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 location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, (com.google.android.gms.location.LocationListener) this);
} else {
mCurrentLatitude = location.getLatitude();
mCurrentLongitude = location.getLongitude();
Toast.makeText(this, mCurrentLongitude + " * ********"+mCurrentLatitude, Toast.LENGTH_LONG).show();
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.apostolis.map1sttest.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
<Button
android:text="Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:id="#+id/btgps" />
</RelativeLayout>
implement GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener
in your activity and past below code in override methods
#Override
public void onConnected(#Nullable 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) {
// 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 location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, (com.google.android.gms.location.LocationListener) this);
} else {
Toast.makeText(this, location.getLatitude() + " * ********"+location.getLongitude(), Toast.LENGTH_LONG).show();
}
}
create variables
private LocationRequest mLocationRequest;
protected GoogleApiClient mGoogleApiClient;
add this inside your onCreate method
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.addApi(Places.GEO_DATA_API)
.build();
and add this inside your onResume
if (!mGoogleApiClient.isConnected() && !mGoogleApiClient.isConnecting()) {
Log.e("Google API", "Connecting");
mGoogleApiClient.connect();
}

How can I use AlarmReceiver to ping GPS location every 10 minutes?

I'm really sorry ahead of time, but this question is pretty lengthy.
I have a functioning GPSTracker class that contains the means of pinging GPS Location for a device. In my MainActivity, I have a button that uses the GPS tracker to display the location in a toast. I'm trying to convert this button into an automatic action to be repeated every X minutes, let's go with 10.(Right now the alarm receiver is setup for 10 seconds)
Even when the app is in the background. So I set up an AlarmReceiver to try to do this, but I can't quite get it working.
Here's my GPSTracker class:
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
public class GPSTracker extends Service implements LocationListener {
private final Context context;
boolean isGPSEnabled = false;
boolean canGetLocation = false;
boolean isNetworkEnabled = false;
Location location;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.context = context.getApplicationContext();
getLocation();
}
public Location getLocation(){
try {
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isGPSEnabled && !isNetworkEnabled) {
}else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if(locationManager != null){
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location !=null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if(isGPSEnabled){
if(location == null){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if(locationManager !=null){
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
public void stopUsingGPS() {
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude() {
if(location!= null){
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude() {
if(location !=null){
longitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation(){
return this.canGetLocation;
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("GPS is settings");
alertDialog.setMessage("GPS isn't enabled. Do you want to go to settings menu?");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
dialog.cancel();
}
});
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
And here's my MainActivity:
package com.example.gwyn.locationnabtest;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends ActionBarActivity {
Button btnShowLocation;
Button btnStartService;
Button btnStopService;
GPSTracker gps;
//GoogleMap mMap;
private PendingIntent pendingIntent;
private AlarmManager manager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnShowLocation = (Button) findViewById(R.id.show_location);
btnShowLocation.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
FragmentActivity activity = (FragmentActivity)view.getContext();
FragmentManager manager = activity.getSupportFragmentManager();
//MapFragment myMap = (MapFragment) (MainActivity.getFragmentManager()).findFragmentById((R.id.mapFragment));
// Test, remove me.
// mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapFragment)).getMap();
gps = new GPSTracker(MainActivity.this);
if(gps.canGetLocation()) {
// Location Achieved.
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// Draw Marker for Current Location on Fragment
// Currently Crashing App
// mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("Marker"));
// Toast a popup of the location data.
Toast.makeText(getApplicationContext(), "Your Location is -\nLat:" + latitude + "\nLong:" + longitude, Toast.LENGTH_LONG).show();
} else {
gps.showSettingsAlert();
}
}
});
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
btnStartService = (Button) findViewById(R.id.start_service);
btnStartService.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
int interval = 10000;
// 10 Second Interval. Good for testing, but turn this off.
manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
Toast.makeText(getApplicationContext(), "Service Started", Toast.LENGTH_SHORT).show();
//startService(new Intent(getBaseContext(), MyServices.class));
}
});
btnStopService = (Button) findViewById(R.id.stop_service);
btnStopService.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Cancel pending intents
manager.cancel(pendingIntent);
Toast.makeText(getApplicationContext(), "Pending Intents Cancelled", Toast.LENGTH_SHORT).show();
}
});
}
}
To highlight specifically, this is the part in MainActivity that works to display the GPS:
public void onClick(View view) {
FragmentActivity activity = (FragmentActivity)view.getContext();
FragmentManager manager = activity.getSupportFragmentManager();
//MapFragment myMap = (MapFragment) (MainActivity.getFragmentManager()).findFragmentById((R.id.mapFragment));
// Test, remove me.
// mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapFragment)).getMap();
gps = new GPSTracker(MainActivity.this);
if(gps.canGetLocation()) {
// Location Achieved.
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// Draw Marker for Current Location on Fragment
// Currently Crashing App
// mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("Marker"));
// Toast a popup of the location data.
Toast.makeText(getApplicationContext(), "Your Location is -\nLat:" + latitude + "\nLong:" + longitude, Toast.LENGTH_LONG).show();
} else {
gps.showSettingsAlert();
}
}
My AlarmReceiver is as follows, and produces an error when creating the GPSTracker:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class AlarmReceiver extends BroadcastReceiver {
GPSTracker gps;
#Override
public void onReceive(Context arg0, Intent arg1) {
// Here's where we'd grab location and store it into DB.
//gps = new GPSTracker(AlarmReceiver.this);
// if(gps.canGetLocation()) {
// double latitude = gps.getLatitude();
// double longitude = gps.getLongitude();
// Draw Marker for Current Location on Fragment
// Toast a popup of the location data.
// Toast.makeText(arg0, "Your Location is -\nLat:" + latitude + "\nLong:" + longitude, Toast.LENGTH_LONG).show();
// } else {
// gps.showSettingsAlert();
// }
// Toast that the alarm ran.
Toast.makeText(arg0, "Location Pinged.", Toast.LENGTH_SHORT).show();
}
More specifically, a part of the problem is the way I'm calling for the new gps Tracker object here:
//gps = new GPSTracker(AlarmReceiver.this);
I'm not sure how to achieve the original result while using the alarmreceiver instead of a button, which is the main source of my problem. Does anyone know exactly what I can tinker with here to get the alarm receiver to properly use the GPSTracker Class?
DO not use GPSTracker. Its broken in over a dozen ways. Forget it exists. If you want a better version, you can use http://gabesechansoftware.com/location-tracking/ That link also explains why GPSTracker is broken by design and why it should never be used. It basically kinda works if used in optimal circumstances, and gives you horrible data in all the others.
Secondly, if you're using GPS and not network- you need to give it time to get a location sync. This can take seconds to minutes (or hours, if the user is in a basement or something) so the immediate forms of getting a location won't work- you have to wait for it to actually sync the location.
I suggest you not look for libraries to solve this and actually try to understand how the base APIs work. Until you do, you're going to have troubles with anything you use as there's lots of corner cases here and its not a trivial thing to do.

Gps doesn't work on Android 4.2.2

I work an application which return a position of the user and it gets information from GPS.
and send position to email Following code is there, it is working perfectly on Android 2.3 but on Android 4.2.2 it doesn't work. on Android 4.2.2 device and emulator doesn't work. This
code for GPS Tracker:
package com.example.safetymobile;
//package com.example.gpstracking;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager .NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
GPS :
package com.example.safetymobile;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
public class GPS extends Activity {
String NotifyWay="";
CheckBox chk,chk1;
EditText edt,edt1;
Button btn;
GPSTracker gps;
public int time = 0;
public Timer t = new Timer();
int interval = 1;
int counter = 0;
int counterend = 2;
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+1:00"));
Date currentLocalTime = cal.getTime();
Date stopt = cal.getTime();
int StopTime = 0;
#SuppressLint("SimpleDateFormat")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gps);
#SuppressWarnings("unused")
DateFormat date = new SimpleDateFormat("HH:mm a");
//chk=(CheckBox)findViewById(R.id.notiEmail);
//chk1=(CheckBox)findViewById(R.id.notisms);
edt=(EditText)findViewById(R.id.interval);
edt1=(EditText)findViewById(R.id.timeStop);
//email
/*chk.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
if(NotifyWay.equals(""))
{
NotifyWay="Email";
}
else
{
NotifyWay="Email";
chk1.setChecked(false);
//Toast.makeText(getApplicationContext(), "You can choose one way only", Toast.LENGTH_LONG).show();
}
}
});*/
/*chk1.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
if(NotifyWay.equals(""))
{
NotifyWay="SMS";
}
else
{
NotifyWay="SMS";
chk.setChecked(false);
//Toast.makeText(getApplicationContext(), "You can choose one way only", Toast.LENGTH_LONG).show();
}
}
});*/
btn=(Button)findViewById(R.id.DoneAdd);
btn.setOnClickListener(new OnClickListener(){
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
int val=Integer.parseInt(edt.getText().toString());
StopTime=Integer.parseInt(edt1.getText().toString());
interval=val*60000;
SQLiteDatabase db;
db = openOrCreateDatabase("Saftey.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);
db.setVersion(1);
db.setLocale(Locale.getDefault());
db.setLockingEnabled(true);
final String CREATE_TABLE_setting =
"CREATE TABLE GPS ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "valTime INTEGER,"
+ "stopTime INTEGER);";
db.execSQL(CREATE_TABLE_setting);
ContentValues values1 = new ContentValues();
values1.put("valTime", interval);
values1.put("stopTime", StopTime);
db.insert("Setting", null, values1);
//Convert Minute To Milliseconds
stopt.setHours(currentLocalTime.getHours() + StopTime);
tt();
Intent intent = new Intent(GPS.this, Change_setting.class);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_gps, menu);
return true;
}
public void tt()
{
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#SuppressWarnings("deprecation")
#Override
public void run() {
currentLocalTime = cal.getTime();
//// .....
if(currentLocalTime.compareTo(stopt) > 0)
{
t.cancel();
}
else
Toast.makeText(getApplication(), "d < d1", Toast.LENGTH_LONG).show();
gps = new GPSTracker(GPS.this);
// check if GPS enabled
if(gps.canGetLocation())
{
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
String text ="https://Maps.google.com/maps?q=" + Double.toString(latitude) + "," + Double.toString(longitude) ;// latitude
//............................
String em="";
//String pn="";
//SharedPreferences pref = getSharedPreferences("pref",0);
//SharedPreferences.Editor edit = pref.edit();
//String pn= pref.getString("PhNum", null);
//edit.commit();
SQLiteDatabase db;
db = openOrCreateDatabase(
"Saftey.db"
, SQLiteDatabase.CREATE_IF_NECESSARY
, null
);
db.setVersion(1);
db.setLocale(Locale.getDefault());
db.setLockingEnabled(true);
Cursor cur = db.query("info", null, null, null, null, null, null);
cur.moveToFirst();
while (cur.isAfterLast() == false)
{
//pn = cur.getString(0);
em=cur.getString(3);
cur.moveToNext();
}
cur.close();
// if(NotifyWay.equals("Email"))
// {
SendingEmail(em, text);
// }
/* else
{
if(NotifyWay.equals("SMS"))
{
SendingSMS(pn, text);
}
}*/
//......................
}
else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
//// .....
time += 1;
}
});
}
}, 0, interval);
}
public void SendingEmail(String em, String text)
{
Mail m = new Mail("mbrm.yu#gmail.com", "mbrm_yu123");
String[] toArr = {em};
m.setTo(toArr);
m.setFrom("mbrm.yu#gmail.com");
m.setSubject("This is an email sent using my Mail JavaMail wrapper from an Android device.");
//m.setBody("I'm in Danger Dad, please Help ...");
m.setBody(text);
try
{
//m.addAttachment("/sdcard/filelocation");
if(m.send()) {
Toast.makeText(getApplication(), "Email was sent successfully.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplication(), "Email was not sent.", Toast.LENGTH_LONG).show();
}
}
catch(Exception e)
{
Toast.makeText(getApplication(), "There was a problem sending the email to : " + em, Toast.LENGTH_LONG).show();
Log.e("MailApp", "Could not send email", e);
}
}
/*public void SendingSMS(String pn, String text)
{
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
new Intent(DELIVERED), 0);
//---when the SMS has been sent---
registerReceiver(new BroadcastReceiver(){
#Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
//---when the SMS has been delivered---
registerReceiver(new BroadcastReceiver(){
#Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS delivered",
Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(getBaseContext(), "SMS not delivered",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(DELIVERED));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(pn, null, text, sentPI, deliveredPI);
}*/
}
manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.safetymobile"
android:versionCode="2"
android:versionName="1.2" >
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CALL_PHONE" >
</uses-permission>
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" >
</uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" >
</uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.VIBRATE" >
</uses-permission>
<uses-permission android:name="android.permission.WAKE_LOCK" >
</uses-permission>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.SEND_SMS" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.safetymobile.MainActivity"
android:label="#string/app_name"
android:theme="#android:style/Theme.Light.NoTitleBar.Fullscreen"
android:clearTaskOnLaunch="true"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.safetymobile.ContactList"
android:label="#string/title_activity_contact_list" >
</activity>
<activity
android:name="com.example.safetymobile.Change_setting"
android:label="#string/title_activity_change_setting"
android:clearTaskOnLaunch="true" >
</activity>
<activity
android:name="com.example.safetymobile.CallContent"
android:label="#string/title_activity_call_content"
android:theme="#android:style/Theme.Light.NoTitleBar.Fullscreen" >
</activity>
<activity
android:name="com.example.safetymobile.SMS"
android:label="#string/title_activity_sms"
android:theme="#android:style/Theme.Light.NoTitleBar.Fullscreen" >
</activity>
<activity
android:name="com.example.safetymobile.Alication_list"
android:label="#string/title_activity_alication_list" >
</activity>
<activity
android:name="com.example.safetymobile.Apps"
android:label="#string/title_activity_apps"
android:theme="#android:style/Theme.Light.NoTitleBar.Fullscreen">
</activity>
<activity
android:name="com.example.safetymobile.Pass"
android:label="#string/title_activity_pass" >
</activity>
<activity
android:name="com.example.safetymobile.ChangePass"
android:label="#string/title_activity_change_pass" >
</activity>
<activity
android:name="com.example.safetymobile.GPS"
android:label="#string/title_activity_gps" >
</activity>
<activity
android:name="com.example.safetymobile.LightActivity"
android:label="#string/title_activity_light"
android:theme="#android:style/Theme.Light.NoTitleBar.Fullscreen" >
</activity>
<receiver android:name=".StartupActivity">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
<category android:name="android.intent.category.DEFAULT"></category>
</intent-filter>
</receiver>
</application>
</manifest>
please any help?
getting address in android using web service
See the answer i have posted. my code works fine, but in android version 4.0 and above, you have to manually open GPS. You can not open it programmatically
Save yourself some trouble and just use Google Play Services Locations API. They provide a good implementation and precise location if you have Play Services installed on your device (most of devices do now)

Categories

Resources