Android location issue - java

Hi i am trying to get the device location using the Location api in android using the device network or wifi connection. However it doesnt seem to get the latt or longitude.
i have created a location provider and manager, and registered a location listener.
i then
launched
locationManagaer.requestLocationUpdates(locationProvide.getName(),TIME_INTERVAL, DISTANCE, this);
and from that point on, the app doesnt retrieve new location changes at all. what am i missing?
here is my userLocation Code
public class UserLocation implements LocationListener{
public static final int UPDATE_LATT = 0;
private static final int TIME_INTERVAL = 1000;
private static final int DISTANCE = 10;
private LocationManager locationManagaer;
private LocationProvider locationProvide;
private Handler mHandler;
public UserLocation(Context context, Handler handler){
locationManagaer = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
locationProvide = locationManagaer.getProvider(LocationManager.NETWORK_PROVIDER);
mHandler = handler;
}
public void startSearchLocation(){
Log.d("", "sart location search");
locationManagaer.requestLocationUpdates(locationProvide.getName(),TIME_INTERVAL, DISTANCE, this);
}
#Override
public void onLocationChanged(Location location) {
Log.d("", "location update on " + location.getLongitude());
Message.obtain(mHandler,UPDATE_LATT, new Position(location.getLongitude(), location.getLatitude()));
}
#Override
public void onProviderDisabled(String provider) {
Log.d("", "onProviderDisabled");
}
#Override
public void onProviderEnabled(String provider) {
Log.d("", "onProviderEnabled");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("", "onStatusChanged");
}
}
here is my activity that uses this class to setup and listen for new locations
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
position = (Position) msg.obj;
Toast.makeText(
getApplicationContext(),
position.getLattitude() + " " + position.getLongetude(),
Toast.LENGTH_LONG).show();
}
};
userLocation = new UserLocation(this, mHandler);
initializeViews();
userLocation.startSearchLocation();
}
Here is my position POJO
public class Position {
private double longetude;
private double lattitude;
public Position(){
}
public Position(double longetude, double lattitude){
}
public double getLongetude() {
return longetude;
}
public void setLongetude(double longetude) {
this.longetude = longetude;
}
public double getLattitude() {
return lattitude;
}
public void setLattitude(double lattitude) {
this.lattitude = lattitude;
}
}
Here is part of my manifest file
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.jr.haliotest.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>
</application>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
Logcat:
03-23 20:19:14.309: D/(16992): sart location search
03-23 20:19:14.384: E/(16992): file /data/data/com.nvidia.NvCPLSvc/files/driverlist.txt: not found!
03-23 20:19:14.384: I/(16992): Attempting to load EGL implementation /system/lib//egl/libEGL_tegra_impl
03-23 20:19:14.449: I/(16992): Loaded EGL implementation /system/lib//egl/libEGL_tegra_impl
03-23 20:19:14.514: I/(16992): Loading GLESv2 implementation /system/lib//egl/libGLESv2_tegra_impl
Testing on a htc one x thats rooted if that helps. wifi is on and god signal

If you are within a building then it is probably that your device is not able to connect to a GPS Provider. I would suggest if you move to a more open space so that you can get a signal.
One hint that if the device is connected to receive a gps signal. The sign of the gps will stop blinking and will become solid.

I would start by checking if your phones location services are enabled and maybe try rebooting. Also try using "GPS" instead of "network" to see if the problem is related to your network not providing location info.
From my experience wifi networks will sometimes simply not provide location info. I'm not sure if that's also true for cell networks, but I suspect there is no guarantee.

Related

App crashes after granting USB permission - Unity app using aar java plugin

I am creating an Unity app which will be controlling Numato GPIO USB powered controller through smartphone USB connection. Since I have to connect the controller to phone I have no debug log so I have no idea what is going on. Thus, I include plugin code and a custom manifest which I use in Unity.
I get questioned by the App if I want to grant permission to control the device (Shows right device name etc) and after I grant the permission app crashes immediately.
Is there a way to check what causes the error? Or maybe I don't see something obvious here.
public class PluginInstance extends Activity {
private static Activity unityActivity;
private static Context unityContext;
public Gpio laser1;
public static void receiveUnityActivity(Activity tActivity) {
unityActivity = tActivity;
}
public static void receiveUnityContext(Context tContext) { unityContext = tContext; }
//Debugging purposes
public void Toast(String msg) {
Toast.makeText(unityActivity, msg, Toast.LENGTH_SHORT).show();
}
//Action Usb Permission
public static final String ACTION_USB_PERMISSION = "com.unity3d.player.UnityPlayerActivity.USB_PERMISSION";
public DevicesManager mDevicesManager;
//USB permission
public final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if (device != null) {
Bundle deviceIndexBundle = intent.getExtras();
if (deviceIndexBundle == null) {
return;
}
int deviceIndex = deviceIndexBundle.getInt(AppConstant.EXTRA_DEVICE_INDEX);
Toast.makeText(unityActivity, "Usb permission granted", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(unityActivity, "Usb permission declined", Toast.LENGTH_SHORT).show();
}
unregisterReceiver(mUsbReceiver);
}
}
}
};
public void InstantiateManager() {
mDevicesManager = DevicesManager.getInstance();
}
public void GetGpios() {
NumatoUSBDevice numatoUSBDevice = mDevicesManager.getDevices().get(0);
Gpio lazer1 = numatoUSBDevice.mGpios.get(1);
}
public void GpioOn() {
laser1.setCurrentOutputState(true);
laser1.setState(true);
}
public void GpioOff() {
laser1.setCurrentOutputState(false);
laser1.setState(false);
}
public void EnumerateDevices() {
UsbManager manager = (UsbManager) unityActivity.getSystemService(Context.USB_SERVICE);
int index = 0;
ArrayList<UsbDevice> cdcAcmDevices = CdcAcmDriver.ListDevices(manager);
mDevicesManager.clearDevices();
ArrayList<Integer> supportedDevices = NumatoUSBDevice.GetSupportedProductIds();
if(!cdcAcmDevices.isEmpty()){
for (UsbDevice cdcAcmDevice : cdcAcmDevices){
int vendorId = cdcAcmDevice.getVendorId();
if(vendorId == NumatoUSBDevice.VID_NUMATOLAB && supportedDevices.contains(cdcAcmDevice.getProductId())){
mDevicesManager.addDevice(new NumatoUSBDevice(index, cdcAcmDevice, manager));
index++;
}
}
}
}
public void MakeConnection() {
NumatoUSBDevice numatoUSBDevice = mDevicesManager.getDevices().get(0);
UsbManager manager = (UsbManager) unityActivity.getSystemService(Context.USB_SERVICE);
//TODO unityContext in mPermissionIntent
PendingIntent mPermissionIntent = PendingIntent.getBroadcast(unityContext, 0,
new Intent(ACTION_USB_PERMISSION).putExtra(AppConstant.EXTRA_DEVICE_INDEX, 0), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
unityActivity.registerReceiver(mUsbReceiver, filter);
manager.requestPermission(numatoUSBDevice.getDevice(), mPermissionIntent);
}
}
And the manifest file:
<?xml version="1.0" encoding="utf-8"?>
<!-- GENERATED BY UNITY. REMOVE THIS COMMENT TO PREVENT OVERWRITING WHEN EXPORTING AGAIN-->
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.unity3d.player"
xmlns:tools="http://schemas.android.com/tools">
<application>
<activity android:name="com.unity3d.player.UnityPlayerActivity"
android:theme="#style/UnityThemeSelector">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"/>
</intent-filter>
<meta-data
android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
android:resource="#xml/device_filter"/>
</activity>
</application>
</manifest>
Edit: I managed to access debug log through wifi and this is what I get:
FATAL EXCEPTION: main
Process: com.jonquil.A2NumatoController, PID: 16837
java.lang.RuntimeException: Error receiving broadcast Intent { act=com.unity3d.player.UnityPlayerActivity.USB_PERMISSION flg=0x10 (has extras) } in com.jonquil.unityplugin.PluginInstance$1#7d45921
at android.app.LoadedApk$ReceiverDispatcher$Args.lambda$getRunnable$0$LoadedApk$ReceiverDispatcher$Args(LoadedApk.java:1689)
at android.app.LoadedApk$ReceiverDispatcher$Args$$ExternalSyntheticLambda0.run(Unknown Source:2)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7838)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.content.Context.unregisterReceiver(android.content.BroadcastReceiver)' on a null object reference
at android.content.ContextWrapper.unregisterReceiver(ContextWrapper.java:769)
at com.jonquil.unityplugin.PluginInstance$1.onReceive(PluginInstance.java:63)
at android.app.LoadedApk$ReceiverDispatcher$Args.lambda$getRunnable$0$LoadedApk$ReceiverDispatcher$Args(LoadedApk.java:1679)
... 9 more
This looks like there is a problem with broadcast receiver since error is caused by invoking method on a null object reference.

how to add permission in my sms manager

I'm very new to android studio and in my first app I want to build an sos app, my sos app specifically sends a message via sms with the current location. When I first built it, it only works on android 5.0 and down, it will not work in 6.0 and up and now I've tried to look at the logcat and the logcat says it needs a permission to send sms so I gave it a permission using the code below this paragraph and now it runs in android 6.0 but it's not sending messages... {if(checkselfpermission(Manifest.permission.SEND_SMS)==PackageManager.PERMISSION GRANTED);}
can you help me here is my manifest my file
<?xml version="1.0" encoding="utf-8"?>
<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.SEND_SMS" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.ACCESS_COURSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#mipmap/sos"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!--
ATTENTION: This was auto-generated to add Google Play services to your project for
App Indexing. See https://g.co/AppIndexing/AndroidStudio for more information.
-->
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name=".DisplayContactActivity"
android:label="#string/title_activity_display_contact"
android:parentActivityName=".MainActivity"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".EditContactActivity"
android:label="#string/title_activity_edit_contact"
android:parentActivityName=".DisplayContactActivity"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".DisplayMessageActivity"
android:label="#string/title_activity_display_message"
android:parentActivityName=".MainActivity"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".LogInActivity"
android:label="#string/title_activity_log_in"
android:parentActivityName=".MainActivity"
android:theme="#style/AppTheme.NoActionBar"></activity>
</application>
and here is my main activity.
public class MainActivity extends AppCompatActivity {
private static final int PERMISSION_SEND_SMS = 1;
ContactDbAdapter contactDbAdapter;
private GoogleApiClient client;
EditText messageText;
UserDbAdapter userDbAdapter;
Cursor cursor;
TextView locationText;
#Override
public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
return super.checkUriPermission(uri, pid, uid, modeFlags);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
userDbAdapter = new UserDbAdapter(this);
messageText = (EditText) findViewById(R.id.messageText);
locationText = (TextView) findViewById(R.id.locationTextView);
try {
userDbAdapter.open();
} catch (SQLException error) {
Log.e("mytag", "Error open userDbAdapter\n");
}
contactDbAdapter = new ContactDbAdapter(this);
try {
contactDbAdapter.open();
} catch (SQLException error) {
Log.e("mytag", "Error open contactDbAdapter\n");
}
cursor = contactDbAdapter.getContacts();
final Button sos = (Button) findViewById(R.id.redbutton);
final Button finish = (Button) findViewById(R.id.greenbutton);
final CountDownTimer timer = new CountDownTimer(3999, 100) {
public void onTick(long millisUntilFinished) {
assert sos != null;
sos.setText("" + ((int) (millisUntilFinished) / 1000));
}
#TargetApi(Build.VERSION_CODES.M)
public void onFinish() {
sos.setVisibility(View.GONE);
finish.setVisibility(View.VISIBLE);
finish.setText("finish");
SmsManager smsManager = SmsManager.getDefault();
cursor = contactDbAdapter.getContacts();
String msg = messageText.getText().toString() + "#" + locationText.getText().toString();
Log.e("mytag", msg);
if(cursor.moveToFirst()){
do{
if (checkSelfPermission(Manifest.permission.SEND_SMS)==PackageManager.PERMISSION_GRANTED);
String number=cursor.getString(cursor.getColumnIndex(contactDbAdapter.PHONE_NUM));
smsManager.sendTextMessage(number, null, msg, null, null);
}while(cursor.moveToNext());
}
}
};
sos.setTag(1);
sos.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
final int status = (Integer) v.getTag();
if (status != 1) {
sos.setText("sos");
sos.setTag(1);
timer.cancel();
} else {
sos.setTag(0);
timer.start();
}
}
}
);
finish.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
sos.setVisibility(View.VISIBLE);
finish.setVisibility(View.GONE);
sos.callOnClick();
}
}
);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
switch (id) {
case R.id.contact:
Intent contactIntent = new Intent(getApplicationContext(), LogInActivity.class);
startActivity(contactIntent);
return true;
case R.id.message:
Intent messageIntent = new Intent(getApplicationContext(), DisplayMessageActivity.class);
startActivity(messageIntent);
default:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.cse4471.osu.sos_osu/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
#Override
public void onResume() {
super.onResume();
// refresh user message
cursor = userDbAdapter.getUsers();
if (cursor.moveToFirst()) {
messageText.setText(cursor.getString(cursor.getColumnIndex(userDbAdapter.MESSAGE)));
}
// Acquire a reference to the system Location Manager
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.INTERNET}, 10);
return;
}
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
locationText.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 0, locationListener);
Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(loc != null) {
// messageText.setText("Latitude:" + loc.getLatitude() + ", Longitude:" + loc.getLongitude());
locationText.setText("Latitude:" + loc.getLatitude() + ", Longitude:" + loc.getLongitude());
}
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.cse4471.osu.sos_osu/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
#Override
public void onDestroy() {
super.onDestroy();
if (cursor != null) {
cursor.close();
}
}
this is also the logcat that appeared before I gave the permission to run it on android 6.0
Process: com.cse4471.osu.sos_osu, PID: 23011
java.lang.SecurityException: Sending SMS message: uid 10179 does not have android.permission.SEND_SMS.
at android.os.Parcel.readException(Parcel.java:1620)
at android.os.Parcel.readException(Parcel.java:1573)
at com.android.internal.telephony.ISms$Stub$Proxy.sendTextForSubscriber(ISms.java:842)
at android.telephony.SmsManager.sendTextMessageInternal(SmsManager.java:317)
at android.telephony.SmsManager.sendTextMessage(SmsManager.java:300)
at com.cse4471.osu.sos_osu.MainActivity$1.onFinish(MainActivity.java:119)
at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:127)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5628)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:853)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:737)
I hope you can help me with this.
You can try this :-
Add it in Manifest -
<uses-permission android:name="android.permission.SEND_SMS" />
And use this runtime permission in your activity
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.SEND_SMS},1);

SERVICE_VERSION_UPDATE_REQUIRED

Actually I'm building an application which requires user's location. But I'm getting SERVICE_VERSION_UPDATE_REQUIRED error. Following are my MainActivity.java and AndroidManifest.xml files:
MainActivity.java
TextView lat, lon;
private static final String TAG = MainActivity.class.getSimpleName();
private FusedLocationProviderApi locationProvider = LocationServices.FusedLocationApi;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private double latitude, longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lat = (TextView) findViewById(R.id.lat);
lon = (TextView) findViewById(R.id.lon);
if (googleApiClient == null) {
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
locationRequest = new LocationRequest();
locationRequest.setInterval(10000);
locationRequest.setFastestInterval(1000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
public void onConnected(#Nullable Bundle bundle) {
requestLocationUpdates();
}
private void requestLocationUpdates() {
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) {
// 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;
}
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.d(TAG, connectionResult.toString());
}
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
lat.setText("Latitude: " + String.valueOf(latitude));
lon.setText("Longitude: " + String.valueOf(longitude));
}
#Override
protected void onStart() {
super.onStart();
googleApiClient.connect();
}
#Override
protected void onResume() {
super.onResume();
if (googleApiClient.isConnected()) {
requestLocationUpdates();
}
}
#Override
protected void onPause() {
super.onPause();
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}
#Override
protected void onStop() {
super.onStop();
googleApiClient.disconnect();
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.harshil.location">
<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" />
<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">
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Here is what logcat says:
D/MainActivity: ConnectionResult{statusCode=SERVICE_VERSION_UPDATE_REQUIRED, resolution=null, message=null}
So, How to get through this problem?
I solved my problem by changing following line [in build.gradle] from:
compile 'com.google.android.gms:play-services:10.0.1'
to:
compile 'com.google.android.gms:play-services:9.8.0'
So, the problem is I am using higher version of Google Play Service for development than that installed on my device or emulator.
I came to my solution as follow:
1. I checked to update Google Play Service on my device but it says it is up-to-date.
2. I checked in App Manager to see the version of it, and I came to know that it is actually at 9.8.77. So I changed play-service version from 10.0.1 to 9.8.0.
Now, I am out of this problem.
Thank you.
Download the the google play store in your mobile and check it .for me i was not installed google play store in my mobile now i installed google play store ,its working fine.

Not able to get location with Service (LocationManager)

i am in real trouble here. Trying to get lat and lon with a background service every 3 sec but i am only able to get some data written when i click send lat and lon in extended controls of the emulator , so both phone and emulator are not working. Here is my code below, it would be awesome if someone could help me. Thanks!
Service
public class GPSService extends Service {
private static final String TAG = "GpsService";
private LocationListener locationListener;
private LocationManager locationManager;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Intent i = new Intent("location_update");
i.putExtra("latExtra",location.getLatitude());
i.putExtra("lonExtra",location.getLongitude());
sendBroadcast(i);
Log.i(TAG, "onLocationChanged: extras lat lon"+location.getLatitude()+" "+location.getLongitude());
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
Log.i(TAG, "onProviderDisabled: DISABLED");
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
};
locationManager =(LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
Criteria c = new Criteria();
String provider =locationManager.getBestProvider(c,true);
Log.i(TAG, "onCreate: bestProvider "+provider);
//noinspection MissingPermission
locationManager.requestLocationUpdates(provider,2000,0,locationListener);
}
#Override
public void onDestroy() {
super.onDestroy();
if (locationManager != null){
Log.i(TAG, "onDestroy: Location manager nije null i brisem");
//noinspection MissingPermission
locationManager.removeUpdates(locationListener);
}
}
}
MainActivity
private final String TAG = "Main";
...
BroadcastReceiver broadcastReciever;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//setStatusBarTranslucent(false);
if(!runtimePermisions()){
startLocationUpdate();}
...
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//stopService();
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) {
//REQUEST PERMISSION
Log.i(TAG, "onClick: NO PERMISION");
} else {
Log.i(TAG, "onClick: got permision");
}
...
}
public void startLocationUpdate(){
Intent i = new Intent(this,GPSService.class);
startService(i);
Log.i(TAG, "startLocationUpdate: Pokrenuo sam service");
}
#Override
protected void onResume() {
super.onResume();
if (broadcastReciever == null){
broadcastReciever = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
lat = (Double) intent.getExtras().get("latExtra");
lon = (Double) intent.getExtras().get("lonExtra");
Log.i(TAG, "onReceive: lat lon "+lat+" "+lon);
}
};
}
registerReceiver(broadcastReciever,new IntentFilter("location_update"));
}
#Override
protected void onDestroy() {
super.onDestroy();
if (broadcastReciever!=null){
unregisterReceiver(broadcastReciever);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 100) {
if (grantResults [0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED){
startLocationUpdate();
}else{
runtimePermisions();}
}
}
private boolean runtimePermisions() {
if (Build.VERSION.SDK_INT >= 23 &&ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
requestPermissions(new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,
},100);
return true;
}
return false;
}
MANIFEST
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.digiart.yoweather">
<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"/>
<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"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SettingsActivity"
android:theme="#style/SettingsTheme"></activity>
<service android:name=".Gps.GPSService"/>
</application>
</manifest>
Again... Any help would be great! THANKS :D
As K. Sopheak said, it can take a while to get the location. From the documentation:
It may take a while to receive the first location update. If an immediate location is required, applications may use the getLastKnownLocation(String) method.
So, you could try getting the last known location using getLastKnownLocation(String) when the service is started and, assuming it exists, broadcast it in the same way you would a location update. Bear in mind, though, that the last known location could be out of date. Depending on what you're using the location for this may or may not be acceptable.
Also, as an aside, a couple of thoughts:
You said 3 seconds, but the code uses 2,000 milliseconds - was that just a typo?
The frequency of location updates is a minimum time - you are not guaranteed to get updates that often. As per the documentation:
The location update interval can be controlled using the minTime parameter. The elapsed time between location updates will never be less than minTime, although it can be more depending on the Location Provider implementation and the update interval requested by other applications.
Is there any particular reason you need location updates at such a high frequency? Obtaining a location can be battery intensive, particularly given that you are requesting FINE as well as COARSE location permissions, so requesting it so frequently could place an enormous drain on device battery life. This is particularly so given that the code is running in a service and will therefore continue to run even when the application is in the background or the user is in an activity which does not require location data. Again, from the documentation:
Choosing a sensible value for minTime is important to conserve battery life. Each location update requires power from GPS, WIFI, Cell and other radios. Select a minTime value as high as possible while still providing a reasonable user experience. If your application is not in the foreground and showing location to the user then your application should avoid using an active provider (such as NETWORK_PROVIDER or GPS_PROVIDER), but if you insist then select a minTime of 5 * 60 * 1000 (5 minutes) or greater. If your application is in the foreground and showing location to the user then it is appropriate to select a faster update interval.
Google recommends using the Google Play services location APIs instead of the Android framework location APIs:
The Google Play services location APIs are preferred over the Android framework location APIs (android.location) as a way of adding location awareness to your app. If you are currently using the Android framework location APIs, you are strongly encouraged to switch to the Google Play services location APIs as soon as possible.

Android Studio: App crashes on some phones

I'm new at android development and really confused by this problem.
I'm making a simple app which has 3 TextViews: text, text2 and text3.
text shows the latitude of user
text2 shows the longitude of the user and
text3 shows distance between user and the place called "Azadi Square".
The app runs properly on Samsung Galaxy S4 and Samsung Galaxy Tab S, but in Huawei Y511 and one of Sony Xperias (I do not know the exact name.), the app doesn't Open and says The App has unfortunately stopped
Here is my Java code:
public class Map extends Activity implements LocationListener {
private TextView text,text2,text3;
private String provider;
private LocationManager locationManager;
private double latitude,longitude;
private Location azadiSquare;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
text = (TextView)findViewById(R.id.text);
text2 = (TextView)findViewById(R.id.text2);
text3 = (TextView)findViewById(R.id.text3);
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria,false);
azadiSquare = new Location(provider);
azadiSquare.setLatitude(35.6996540);
azadiSquare.setLongitude(51.3379906);
Location location = locationManager.getLastKnownLocation(provider);
text.setText(location.getLatitude()+"");
text2.setText(location.getLongitude()+"");
text3.setText(distanceBetweenMeter(azadiSquare,location)+"");
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider,400,1,this);
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
text.setText(latitude+"");
text2.setText(longitude+"");
text3.setText(distanceBetweenMeter(azadiSquare,location)+"");
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String s) {
Toast.makeText(this,"Enabled new provider " + provider,Toast.LENGTH_LONG).show();
}
#Override
public void onProviderDisabled(String s) {
Toast.makeText(this,"Disabled provider " + provider,Toast.LENGTH_LONG).show();
}
private double getDistanceFromLatLonInKm(double lat1,double lon1,double lat2,double lon2) {
double R = 6371; // Radius of the earth in km
double dLat = deg2rad(lat2-lat1); // deg2rad below
double dLon = deg2rad(lon2-lon1);
double a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2)
;
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double d = R * c; // Distance in km
return d;
}
private double deg2rad(double deg) {
return deg * (Math.PI/180);
}
private int distanceBetweenMeter(Location location1, Location location2){
double distanceKM = getDistanceFromLatLonInKm(location1.getLatitude(),location1.getLongitude(),
location2.getLatitude(),location2.getLongitude());
int distanceMeter = (int)(distanceKM*1000);
return distanceMeter;
}
}
Note: I just deleted the imports!
Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<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"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".Map" android:screenOrientation="landscape">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Notes: I turned On the Location of the phone before opening the app, so it is not the problem. The other thing I want to say is that all the calculations are okay and they are working fine.
On Android 6.0 (API level 23) and higher you need to request permission for ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION at run time. See, Requesting Permissions at Run Time. That may be the case.
The best thing to do is to logcat the issue and backtrace it so you could see where it's going bad or at least have one clue. If the answer from user35603 didn't worked then try this and post the logcat part regarding to your issue.
Finally the problem is solved! This part of the code was making trouble:
Location location = locationManager.getLastKnownLocation(provider);
text.setText(location.getLatitude()+"");
text2.setText(location.getLongitude()+"");
I guess it takes a little bit of time for location to get the current location. Actually, when app wants to run the line below, location is still null and app crashes:
text1.setText(location.getLatitude()+"");
I solved the crash with something like this:
Location location = locationManager.getLastKnownLocation(provider);
while(location==null){}
text.setText(location.getLatitude()+"");
text2.setText(location.getLongitude() + "");
text3.setText(distanceBetweenMeter(azadiSquare,location)+"");
Crash is solved, but the app freezes with white screen. I don't know exactly, but I guess it is trapped on while loop. Thanks!
public class MainActivity extends AppCompatActivity {
pb=findViewById(R.id.progressbar);
Example ex=new Example();//The subclass object is created here
boolean stop=false;//a boolean variable to start or stop the thread to get location.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (location== null) {
showSettingDialog();//this will show your custom way of displaying
//the location setting intent
new Thread(ex).start();//here the fetching location gets started
}
else{
//here write code after your location is fetched
//here to got some other base activity or stay in this
finish();//if you wan to stay in this activity then omit this line.
}
}
public class Example implements Runnable{ //This is a sub class in your main activity.
#Override
public void run() {//overriding run medthod
try {
while(location==null) { //this part keeps on running whithout
//ui freeze
if (stop) {
return;
}
runOnUiThread(new Runnable() {
#Override
public void run() {
pb.setVisibility(View.VISIBLE);
}
});
getLastLocation();//this function will fetch location.
Thread.sleep(1500);
pb.setVisibility(View.INVISIBLE);
if (location != null) {
//do your code here
stop = true;
finish();
}
}
}
catch(InterruptedException e){
e.printStackTrace();
}
}
}
}

Categories

Resources