Working on a project on Android studio to turn on LED via Bluetooth using mapbox turn-by-turn navigation directions. To be specific turn on left LED on the "To the right" direction arrow is displayed or any other is displayed. Is it possible to do?
MainActivity.java
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.mapbox.geojson.Point;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.annotations.Marker;
import com.mapbox.mapboxsdk.annotations.MarkerOptions;
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.mapbox.mapboxsdk.plugins.locationlayer.LocationLayerMode;
import com.mapbox.mapboxsdk.plugins.locationlayer.LocationLayerPlugin;
import com.mapbox.services.android.location.LostLocationEngine;
import com.mapbox.services.android.navigation.ui.v5.NavigationLauncher;
import com.mapbox.services.android.navigation.ui.v5.NavigationViewOptions;
import com.mapbox.services.android.navigation.ui.v5.route.NavigationMapRoute;
import com.mapbox.services.android.navigation.v5.navigation.NavigationRoute;
import com.mapbox.services.android.telemetry.location.LocationEngine;
import com.mapbox.services.android.telemetry.location.LocationEngineListener;
import com.mapbox.services.android.telemetry.location.LocationEnginePriority;
import com.mapbox.services.android.telemetry.permissions.PermissionsListener;
import com.mapbox.services.android.telemetry.permissions.PermissionsManager;
// classes to calculate a route
import com.mapbox.services.android.navigation.ui.v5.route.NavigationMapRoute;
import com.mapbox.services.android.navigation.v5.navigation.NavigationRoute;
import com.mapbox.api.directions.v5.models.DirectionsResponse;
import com.mapbox.api.directions.v5.models.DirectionsRoute;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.util.List;
public class MainActivity extends AppCompatActivity implements LocationEngineListener, PermissionsListener {
private MapView mapView;
private MapboxMap map;
private PermissionsManager permissionsManager;
private LocationLayerPlugin locationPlugin;
private LocationEngine locationEngine;
private Location originLocation;
private Marker destinationMarker;
private LatLng originCoord;
private LatLng destinationCoord;
private Button button;
// variables for calculating and drawing a route
private Point originPosition;
private Point destinationPosition;
private DirectionsRoute currentRoute;
private static final String TAG = "DirectionsActivity";
private NavigationMapRoute navigationMapRoute;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Mapbox.getInstance(this, getString(R.string.access_token));
setContentView(R.layout.activity_main);
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(final MapboxMap mapboxMap) {
map = mapboxMap;
enableLocationPlugin();
originCoord = new LatLng(originLocation.getLatitude(), originLocation.getLongitude());
mapboxMap.addOnMapClickListener(new MapboxMap.OnMapClickListener() {
#Override
public void onMapClick(#NonNull LatLng point) {
if (destinationMarker != null) {
mapboxMap.removeMarker(destinationMarker);
}
destinationCoord = point;
destinationMarker = mapboxMap.addMarker(new MarkerOptions()
.position(destinationCoord)
);
destinationPosition = Point.fromLngLat(destinationCoord.getLongitude(), destinationCoord.getLatitude());
originPosition = Point.fromLngLat(originCoord.getLongitude(), originCoord.getLatitude());
getRoute(originPosition, destinationPosition);
button.setEnabled(true);
button.setBackgroundResource(R.color.mapboxBlue);
};
});
};
});
button = findViewById(R.id.startButton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Point origin = originPosition;
Point destination = destinationPosition;
// Pass in your Amazon Polly pool id for speech synthesis using Amazon Polly
// Set to null to use the default Android speech synthesizer
String awsPoolId = null;
boolean simulateRoute = false;
NavigationViewOptions options = NavigationViewOptions.builder()
.origin(origin)
.destination(destination)
.awsPoolId(awsPoolId)
.shouldSimulateRoute(simulateRoute)
.build();
// Call this method with Context from within an Activity
NavigationLauncher.startNavigation(MainActivity.this, options);
}
});
}
#SuppressWarnings( {"MissingPermission"})
private void enableLocationPlugin() {
// Check if permissions are enabled and if not request
if (PermissionsManager.areLocationPermissionsGranted(this)) {
// Create an instance of LOST location engine
initializeLocationEngine();
locationPlugin = new LocationLayerPlugin(mapView, map, locationEngine);
locationPlugin.setLocationLayerEnabled(LocationLayerMode.TRACKING);
} else {
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
}
}
#SuppressWarnings( {"MissingPermission"})
private void initializeLocationEngine() {
locationEngine = new LostLocationEngine(MainActivity.this);
locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
locationEngine.activate();
Location lastLocation = locationEngine.getLastLocation();
if (lastLocation != null) {
originLocation = lastLocation;
setCameraPosition(lastLocation);
} else {
locationEngine.addLocationEngineListener(this);
}
}
private void setCameraPosition(Location location) {
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 13));
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
private void getRoute(Point origin, Point destination) {
NavigationRoute.builder()
.accessToken(Mapbox.getAccessToken())
.origin(origin)
.destination(destination)
.build()
.getRoute(new Callback<DirectionsResponse>() {
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
// You can get the generic HTTP info about the response
Log.d(TAG, "Response code: " + response.code());
if (response.body() == null) {
Log.e(TAG, "No routes found, make sure you set the right user and access token.");
return;
} else if (response.body().routes().size() < 1) {
Log.e(TAG, "No routes found");
return;
}
currentRoute = response.body().routes().get(0);
// Draw the route on the map
if (navigationMapRoute != null) {
navigationMapRoute.removeRoute();
} else {
navigationMapRoute = new NavigationMapRoute(null, mapView, map, R.style.NavigationMapRoute);
}
navigationMapRoute.addRoute(currentRoute);
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable throwable) {
Log.e(TAG, "Error: " + throwable.getMessage());
}
});
}
#Override
#SuppressWarnings( {"MissingPermission"})
protected void onStart() {
super.onStart();
if (locationEngine != null) {
locationEngine.requestLocationUpdates();
}
if (locationPlugin != null) {
locationPlugin.onStart();
}
mapView.onStart();
}
#Override
protected void onStop() {
super.onStop();
if (locationEngine != null) {
locationEngine.removeLocationUpdates();
}
if (locationPlugin != null) {
locationPlugin.onStop();
}
mapView.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
if (locationEngine != null) {
locationEngine.deactivate();
}
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
#Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
#Override
public void onConnected() {
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onExplanationNeeded(List<String> permissionsToExplain) {
}
#Override
public void onPermissionResult(boolean granted) {
}
}
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:mapbox="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/startButton"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:padding="5px"
android:layout_margin="20px"
android:text="Start navigation"
android:background="#color/mapboxGrayLight"
android:textColor="#color/mapboxWhite"
android:enabled="false"/>
<com.mapbox.mapboxsdk.maps.MapView
android:id="#+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent"
mapbox:mapbox_cameraTargetLat="38.9098"
mapbox:mapbox_cameraTargetLng="-77.0295"
mapbox:mapbox_styleUrl="mapbox://styles/mapbox/streets-v10"
mapbox:mapbox_cameraZoom="12" />
</RelativeLayout>
build.gradle
android {
compileSdkVersion 26
defaultConfig {
applicationId "com.adailtonribeiro.android_navigator"
minSdkVersion 19
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
repositories {
mavenCentral()
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
implementation 'com.mcxiaoke.volley:library:1.0.19'
implementation ('com.mapbox.mapboxsdk:mapbox-android-sdk:5.5.0#aar') {
transitive=true
}
implementation 'com.mapbox.mapboxsdk:mapbox-android-navigation:0.11.1'
implementation ('com.mapbox.mapboxsdk:mapbox-android-navigation-ui:0.11.1') {
transitive = true
}
implementation 'com.mapbox.mapboxsdk:mapbox-android-plugin-locationlayer:0.4.0'
}
buildscript {
repositories {
google()
jcenter()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.2.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.adailtonribeiro.android_navigator">
<!-- Coarse location -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<!-- Or fine location -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
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>
Related
I'm having trouble creating facebook-like chat heads. I am using the react-native-floating-bubble library. When I call the showFloatingBubble () function, it falls into catch and the chat head is not displayed. Could someone help me solve this problem?
Library Link -> https://github.com/hybriteq/react-native-floating-bubble/blob/master/README.md
App.js
/**
* Sample React Native App
* https://github.com/facebook/react-native
*
* #format
* #flow
*/
import React from 'react';
import firebase from 'react-native-firebase';
import {
showFloatingBubble,
hideFloatingBubble,
requestPermission,
checkPermission,
initialize,
} from 'react-native-floating-bubble';
class App extends React.Component {
async componentDidMount() {
showFloatingBubble();
const enabled = await firebase.messaging().hasPermission();
if (enabled) {
const fcmToken = firebase.messaging().getToken();
console.log('fcmToken', fcmToken);
firebase.notifications().onNotification(notification => {
alert(notification);
});
} else {
try {
firebase.messaging().requestPermission();
} catch (e) {
alert('usuário rejeitou as permissões');
}
}
}
render() {
return <></>;
}
}
export default App;
MainApplication.java
package com.poc;
import android.app.Application;
import android.content.Context;
import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
import io.invertase.firebase.RNFirebasePackage;
import io.invertase.firebase.messaging.RNFirebaseMessagingPackage;
import io.invertase.firebase.notifications.RNFirebaseNotificationsPackage;
import com.dieam.reactnativepushnotification.ReactNativePushNotificationPackage;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.soloader.SoLoader;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost =
new ReactNativeHost(this) {
#Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
#Override
protected List<ReactPackage> getPackages() {
#SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
packages.add(new RNFirebaseMessagingPackage());
packages.add(new RNFirebaseNotificationsPackage());
return packages;
};
#Override
protected String getJSMainModuleName() {
return "index";
}
};
#Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
#Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
initializeFlipper(this); // Remove this line if you don't want Flipper enabled
}
/**
* Loads Flipper in React Native templates.
*
* #param context
*/
private static void initializeFlipper(Context context) {
if (BuildConfig.DEBUG) {
try {
/*
We use reflection here to pick up the class that initializes Flipper,
since Flipper library is not available in release mode
*/
Class<?> aClass = Class.forName("com.facebook.flipper.ReactNativeFlipper");
aClass.getMethod("initializeFlipper", Context.class).invoke(null, context);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
build.gradle
apply plugin: "com.android.application"
import com.android.build.OutputFile
project.ext.react = [
entryFile: "index.js",
enableHermes: false, // clean and rebuild if changing
]
apply from: "../../node_modules/react-native/react.gradle"
def enableSeparateBuildPerCPUArchitecture = false
def enableProguardInReleaseBuilds = false
def jscFlavor = 'org.webkit:android-jsc:+'
def enableHermes = project.ext.react.get("enableHermes", false)
android {
compileSdkVersion rootProject.ext.compileSdkVersion
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
defaultConfig {
applicationId "com.poc"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "1.0"
}
splits {
abi {
reset()
enable enableSeparateBuildPerCPUArchitecture
universalApk false // If true, also generate a universal APK
include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
}
}
signingConfigs {
debug {
storeFile file('debug.keystore')
storePassword 'android'
keyAlias 'androiddebugkey'
keyPassword 'android'
}
}
buildTypes {
debug {
signingConfig signingConfigs.debug
}
release {
matchingFallbacks = ['release', 'debug']
signingConfig signingConfigs.debug
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
}
}
applicationVariants.all { variant ->
variant.outputs.each { output ->
def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
def abi = output.getFilter(OutputFile.ABI)
if (abi != null) { // null for the universal-debug, universal-release variants
output.versionCodeOverride =
versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
}
}
}
}
dependencies {
implementation project(':react-native-floating-bubble')
implementation project(':react-native-firebase')
implementation "com.google.android.gms:play-services-base:16.1.0"
implementation "com.google.firebase:firebase-core:16.0.9"
implementation project(':react-native-push-notification')
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation "com.facebook.react:react-native:+" // From node_modules
implementation "com.google.firebase:firebase-messaging:18.0.0"
implementation 'me.leolin:ShortcutBadger:1.1.21#aar'
if (enableHermes) {
def hermesPath = "../../node_modules/hermes-engine/android/"
debugImplementation files(hermesPath + "hermes-debug.aar")
releaseImplementation files(hermesPath + "hermes-release.aar")
} else {
implementation jscFlavor
}
}
task copyDownloadableDepsToLibs(type: Copy) {
from configurations.compile
into 'libs'
}
apply from: file("../../node_modules/#react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
apply plugin: 'com.google.gms.google-services'
settings.gradle
rootProject.name = 'poc'
include ':react-native-firebase'
project(':react-native-firebase').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-firebase/android')
include ':react-native-push-notification'
project(':react-native-push-notification').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-push-notification/android')
include ':react-native-floating-bubble'
project(':react-native-floating-bubble').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-floating-bubble/android')
apply from: file("../node_modules/#react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)
include ':app'
I am using Mapbox sdk for android.
I want to get current location,and i am also getting,but the problem is:
I am getting wrong current location,which is near Nigeria.
can anyone help me to get perfect location??
here is my gradle file's details:
android {
compileSdkVersion 27
defaultConfig {
applicationId "com.app.mapboxdemo"
minSdkVersion 15
targetSdkVersion 27
multiDexEnabled true
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
//noinspection GradleCompatible
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support:design:27.1.1'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.intuit.ssp:ssp-android:1.0.5'
implementation 'com.intuit.sdp:sdp-android:1.0.5'
implementation('com.mapbox.mapboxsdk:mapbox-android-sdk:6.1.3#aar') {
transitive = true
}
implementation 'com.mapbox.mapboxsdk:mapbox-android-plugin-locationlayer:0.5.3'
implementation 'com.mapbox.mapboxsdk:mapbox-android-plugin-cluster-utils:0.3.0'
implementation 'com.mapbox.mapboxsdk:mapbox-android-navigation:0.13.0'
implementation('com.mapbox.mapboxsdk:mapbox-android-navigation-ui:0.13.0') {
transitive = true
}
}
and here are the permisssions:
<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"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-feature android:name="android.hardware.location.gps"/>
and here is my code for getting user location:
package com.app.mapboxdemo;// classes needed to initialize map
import com.mapbox.api.geocoding.v5.MapboxGeocoding;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.maps.MapView;
// classes needed to add location layer
import com.mapbox.geojson.Point;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import android.location.Location;
import com.mapbox.mapboxsdk.geometry.LatLng;
import android.os.Bundle;
import android.support.annotation.NonNull;
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory;
import com.mapbox.mapboxsdk.plugins.locationlayer.LocationLayerPlugin;
import com.mapbox.mapboxsdk.plugins.locationlayer.modes.CameraMode;
import com.mapbox.mapboxsdk.plugins.locationlayer.modes.RenderMode;
import com.mapbox.services.android.navigation.ui.v5.NavigationLauncherOptions;
import com.mapbox.android.core.location.LocationEngine;
import com.mapbox.android.core.location.LocationEngineListener;
import com.mapbox.android.core.location.LocationEnginePriority;
import com.mapbox.android.core.location.LocationEngineProvider;
import com.mapbox.android.core.permissions.PermissionsListener;
import com.mapbox.android.core.permissions.PermissionsManager;
// classes needed to add a marker
import com.mapbox.mapboxsdk.annotations.Marker;
import com.mapbox.mapboxsdk.annotations.MarkerOptions;
// classes to calculate a route
import com.mapbox.services.android.navigation.ui.v5.route.NavigationMapRoute;
import com.mapbox.services.android.navigation.v5.navigation.NavigationRoute;
import com.mapbox.api.directions.v5.models.DirectionsResponse;
import com.mapbox.api.directions.v5.models.DirectionsRoute;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
// classes needed to launch navigation UI
import android.view.View;
import android.widget.Button;
import com.mapbox.services.android.navigation.ui.v5.NavigationLauncher;
// classes needed to add location layer
import com.mapbox.geojson.Point;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import android.location.Location;
import com.mapbox.mapboxsdk.geometry.LatLng;
import android.support.annotation.NonNull;
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory;
import com.mapbox.mapboxsdk.plugins.locationlayer.LocationLayerPlugin;
import com.mapbox.mapboxsdk.plugins.locationlayer.modes.RenderMode;
import com.mapbox.services.android.navigation.ui.v5.NavigationLauncherOptions;
import com.mapbox.android.core.location.LocationEngine;
import com.mapbox.android.core.location.LocationEngineListener;
import com.mapbox.android.core.location.LocationEnginePriority;
import com.mapbox.android.core.location.LocationEngineProvider;
import com.mapbox.android.core.permissions.PermissionsListener;
import com.mapbox.android.core.permissions.PermissionsManager;
// classes needed to add a marker
import com.mapbox.mapboxsdk.annotations.Marker;
import com.mapbox.mapboxsdk.annotations.MarkerOptions;
// classes to calculate a route
import com.mapbox.services.android.navigation.ui.v5.route.NavigationMapRoute;
import com.mapbox.services.android.navigation.v5.navigation.NavigationRoute;
import com.mapbox.api.directions.v5.models.DirectionsResponse;
import com.mapbox.api.directions.v5.models.DirectionsRoute;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import android.util.Log;
// classes needed to launch navigation UI
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.mapbox.services.android.navigation.ui.v5.NavigationLauncher;
import java.util.List;
public class NavigationActivity extends AppCompatActivity implements LocationEngineListener, PermissionsListener {
private MapView mapView;
// variables for adding location layer
private static MapboxMap map;
private PermissionsManager permissionsManager;
private LocationLayerPlugin locationPlugin;
private LocationEngine locationEngine;
private Location originLocation;
// variables for adding a marker
private Marker destinationMarker;
private LatLng originCoord;
private LatLng destinationCoord;
// variables for calculating and drawing a route
private Point originPosition;
private Point destinationPosition;
private DirectionsRoute currentRoute;
private static final String TAG = "DirectionsActivity";
private NavigationMapRoute navigationMapRoute;
EditText edtLatitude, edtLongitude;
private Button button, buttonGetLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this, getString(R.string.access_token));
setContentView(R.layout.activity_draw_navigation);
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(final MapboxMap mapboxMap) {
map = mapboxMap;
enableLocationPlugin();
originCoord = new LatLng(originLocation.getLatitude(), originLocation.getLongitude());
/*mapboxMap.addOnMapClickListener(new MapboxMap.OnMapClickListener() {
#Override
public void onMapClick(#NonNull LatLng point) {
if (destinationMarker != null) {
mapboxMap.removeMarker(destinationMarker);
}
destinationCoord = point;
destinationMarker = mapboxMap.addMarker(new MarkerOptions()
.position(destinationCoord)
);
destinationPosition = Point.fromLngLat(destinationCoord.getLongitude(), destinationCoord.getLatitude());
originPosition = Point.fromLngLat(originCoord.getLongitude(), originCoord.getLatitude());
getRoute(originPosition, destinationPosition);
button.setEnabled(true);
button.setBackgroundResource(R.color.mapboxBlue);
}
});*/
button = findViewById(R.id.startButton);
edtLatitude = findViewById(R.id.edtLatitude);
edtLongitude = findViewById(R.id.edtLongitude);
buttonGetLocation = findViewById(R.id.buttonGetLocation);
buttonGetLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e(TAG, "buttonGetLocation onClick: " );
checkLatLong(mapboxMap);
}
});
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Point origin = originPosition;
Point destination = destinationPosition;
boolean simulateRoute = true;
NavigationLauncherOptions options = NavigationLauncherOptions.builder()
.origin(origin)
.destination(destination)
.shouldSimulateRoute(simulateRoute)
.build();
Log.e(TAG, "onClick: Start Button");
// Call this method with Context from within an Activity
NavigationLauncher.startNavigation(NavigationActivity.this, options);
}
});
}
});
}
private void getRoute(Point origin, Point destination) {
NavigationRoute.builder()
.accessToken(Mapbox.getAccessToken())
.origin(origin)
.destination(destination)
.build()
.getRoute(new Callback<DirectionsResponse>() {
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
// You can get the generic HTTP info about the response
Log.d(TAG, "Response code: " + response.code());
if (response.body() == null) {
Log.e(TAG, "No routes found, make sure you set the right user and access token.");
return;
} else if (response.body().routes().size() < 1) {
Log.e(TAG, "No routes found");
return;
}
currentRoute = response.body().routes().get(0);
// Draw the route on the map
if (navigationMapRoute != null) {
navigationMapRoute.removeRoute();
} else {
navigationMapRoute = new NavigationMapRoute(null, mapView, map, R.style.NavigationMapRoute);
}
navigationMapRoute.addRoute(currentRoute);
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable throwable) {
Log.e(TAG, "Error: " + throwable.getMessage());
}
});
}
#SuppressWarnings({"MissingPermission"})
private void enableLocationPlugin() {
// Check if permissions are enabled and if not request
if (PermissionsManager.areLocationPermissionsGranted(this)) {
initializeLocationEngine();
locationPlugin = new LocationLayerPlugin(mapView, map, locationEngine);
locationPlugin.setLocationLayerEnabled(true);
locationPlugin.setCameraMode(CameraMode.TRACKING);
locationPlugin.setRenderMode(RenderMode.COMPASS);
} else {
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
}
}
#SuppressWarnings({"MissingPermission"})
private void initializeLocationEngine() {
LocationEngineProvider locationEngineProvider = new LocationEngineProvider(this);
locationEngineProvider.obtainLocationEngineBy(LocationEngine.Type.ANDROID);
locationEngine = locationEngineProvider.obtainBestLocationEngineAvailable();
locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
locationEngine.activate();
locationEngine.requestLocationUpdates();
Location lastLocation = locationEngine.getLastLocation();
// Log.e(TAG, "initializeLocationEngine: Latitude is"+lastLocation.getLatitude()+" Longitude is "+lastLocation.getLongitude() );
if (lastLocation != null) {
originLocation = lastLocation;
setCameraPosition(lastLocation);
} else {
locationEngine.addLocationEngineListener(this);
}
}
private void setCameraPosition(Location location) {
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 13));
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
public void onExplanationNeeded(List<String> permissionsToExplain) {
}
#Override
public void onPermissionResult(boolean granted) {
if (granted) {
enableLocationPlugin();
} else {
finish();
}
}
#Override
#SuppressWarnings({"MissingPermission"})
public void onConnected() {
locationEngine.requestLocationUpdates();
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
originLocation = location;
setCameraPosition(location);
locationEngine.removeLocationEngineListener(this);
}
}
#Override
#SuppressWarnings({"MissingPermission"})
protected void onStart() {
super.onStart();
if (locationEngine != null) {
locationEngine.requestLocationUpdates();
}
if (locationPlugin != null) {
locationPlugin.onStart();
}
mapView.onStart();
}
#Override
protected void onStop() {
super.onStop();
if (locationEngine != null) {
locationEngine.removeLocationUpdates();
}
if (locationPlugin != null) {
locationPlugin.onStop();
}
mapView.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
if (locationEngine != null) {
locationEngine.deactivate();
}
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
#Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
public void checkLatLong(MapboxMap mapboxMap) {
if ((edtLatitude.getText() == null && edtLatitude.getText().length() == 0) && (edtLongitude.getText() == null && edtLongitude.getText().length() == 0)) {
Toast.makeText(getApplicationContext(), "Enter Proper Longitude and Latitude.", Toast.LENGTH_LONG).show();
} else {
if (destinationMarker != null) {
map.removeMarker(destinationMarker);
}
destinationCoord = new LatLng(Double.parseDouble(edtLatitude.getText().toString()), Double.parseDouble(edtLongitude.getText().toString()));
destinationMarker = map.addMarker(new MarkerOptions()
.position(destinationCoord)
);
Log.e(TAG, "checkLatLong: ");
destinationPosition = Point.fromLngLat(destinationCoord.getLongitude(), destinationCoord.getLatitude());
originPosition = Point.fromLngLat(originCoord.getLongitude(), originCoord.getLatitude());
getRoute(originPosition, destinationPosition);
setCameraPosition(originLocation);
button.setEnabled(true);
button.setBackgroundResource(R.color.mapboxBlue);
}
}
}
please help me to get user location.
Help is appreciated,i referred a lot of questions but didnt get any solution.
than also,suggest any help in reffering questions too.
I Solved it by making few changes in methods initializeLocationEngine() and enableLocationPlugin()
Here are the modified methods for answer:
private void enableLocationPlugin() {
// Check if permissions are enabled and if not request
if (PermissionsManager.areLocationPermissionsGranted(this)) {
initializeLocationEngine();
locationPlugin = new LocationLayerPlugin(mapView, map, locationEngine);
locationPlugin.setLocationLayerEnabled(true);
locationPlugin.setCameraMode(CameraMode.TRACKING);
locationPlugin.setRenderMode(RenderMode.COMPASS);
getLifecycle().addObserver(locationPlugin);
Log.e(TAG, "enableLocationPlugin:Permission Granted" );
} else {
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
Log.e(TAG, "enableLocationPlugin:Permission Not Granted" );
}
}
private void initializeLocationEngine() {
locationEngine = new LocationEngineProvider(this).obtainBestLocationEngineAvailable();
locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
locationEngine.addLocationEngineListener(this);
locationEngine.activate();
Location lastLocation = locationEngine.getLastLocation();
if (lastLocation != null) {
setCameraPosition(lastLocation);
} else {
locationEngine.addLocationEngineListener(this);
}
}
I have to send location(latitude & longitude) from android device to server (php) automatically (every 2 min)
and for this work I am using JobSchedulerCompat for service to send location.
But after this send locations to the server only after the application run, I want to send locations to the server continuously.
How can I achieve that?
Here is my code so far:
GpsTracker.java
public class GPSTracker extends Service {
private final Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
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();
}
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
try {
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}catch (Exception ex){
ex.printStackTrace();
}
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, locationListenerNetwork);
Toast.makeText(mContext,"Network Enabled",Toast.LENGTH_SHORT).show();
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, locationListenerGps);
//Log.d("GPS Enabled", "GPS Enabled");
Toast.makeText(mContext,"GPS Enabled",Toast.LENGTH_SHORT).show();
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(locationListenerGps);
}
}
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;
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
MyService.java
public class MyService extends JobService{
String code;
#Override
public boolean onStartJob(JobParameters params) {
code=readsavefile(getApplicationContext(),"Code2","Error");
//Toast.makeText(getApplicationContext(),code,Toast.LENGTH_SHORT).show();
new SendLocation(this,params,getApplicationContext()).execute(code);
//Toast.makeText(getApplicationContext(),"Start",Toast.LENGTH_SHORT).show();
//jobFinished(params, false);
return true;
}
public static String readsavefile(Context context,String pname,String dvalue){
SharedPreferences shared=context.getSharedPreferences("GetCodeService", Context.MODE_PRIVATE);
return shared.getString(pname,dvalue);
}
#Override
public boolean onStopJob(JobParameters params) {
return false;
}
private static class SendLocation extends AsyncTask<String, Void, String> {
MyService myService;
JobParameters jobParameters;
Context _context;
GPSTracker gps;
double lat,lon;
public SendLocation(MyService myService,JobParameters jobParameters,Context context){
this._context=context;
gps=new GPSTracker(context);
if (gps.canGetLocation){
lat=gps.getLatitude();
lon=gps.getLongitude();
}
this.myService=myService;
this.jobParameters=jobParameters;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
String link = Config.IP_Config + "Hatef/getlocation.php";
HttpClient httpclint = new DefaultHttpClient();
HttpPost httppost = new HttpPost(link);
try {
JSONObject jsonobj = new JSONObject();
jsonobj.put("latitude", lat+"");
jsonobj.put("longitude", lon+"");
jsonobj.put("code", strings[0]);
List<NameValuePair> namevaluepair = new ArrayList<NameValuePair>();
namevaluepair.add(new BasicNameValuePair("req", jsonobj.toString()));
httppost.setEntity(new UrlEncodedFormEntity(namevaluepair, HTTP.UTF_8));
HttpResponse response = httpclint.execute(httppost);
InputStream inputstream = response.getEntity().getContent();
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(inputstream));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return sb.toString();
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String s) {
myService.jobFinished(jobParameters, false);
}
}
}
Run Service
JobInfo.Builder builder=new JobInfo.Builder(100,new ComponentName(this,MyService.class));
builder.setPeriodic(10000)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.setPersisted(true);
mJobScheduler.schedule(builder.build());
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher2"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".Main"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".second_page"
android:screenOrientation="portrait" >
</activity>
<service android:name=".MyService"
android:permission="android.permission.BIND_JOB_SERVICE"
android:exported="true"
/>
</application>
When I am running this code it gives current location after I clicked the button_currentlocation. But when I checked the accuracy it is very low accuracy (sometime 5000m). But I need to get current location for one time with high accuracy (around 10m).
If someone can help me to correct my coding,it will be great help for my research.
My cordings are as follow
in my manifest
uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"
LocationProvider Class
public class LocationProvider implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
public abstract interface LocationCallback {
public void handleNewLocation(Location location);
}
public static final String TAG = LocationProvider.class.getSimpleName();
/*
* Define a request code to send to Google Play services
* This code is returned in Activity.onActivityResult
*/
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private LocationCallback mLocationCallback;
private Context mContext;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
public LocationProvider(Context context, LocationCallback callback) {
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationCallback = callback;
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
mContext = context;
}
public void connect() {
mGoogleApiClient.connect();
}
public void disconnect() {
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
#Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "Location services connected.");
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
else {
mLocationCallback.handleNewLocation(location);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
/*
* Google Play services can resolve some errors it detects.
* If the error has a resolution, try sending an Intent to
* start a Google Play services activity that can resolve
* error.
*/
if (connectionResult.hasResolution() && mContext instanceof Activity) {
try {
Activity activity = (Activity)mContext;
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(activity, CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
#Override
public void onLocationChanged(Location location) {
mLocationCallback.handleNewLocation(location);
}
}
In HomePage Class
package com.ksfr.finaltest01;
import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;
import com.google.android.gms.maps.model.LatLng;
public class HomePage extends Activity implements AdapterView.OnItemSelectedListener,LocationProvider.LocationCallback {
public static final String TAG = HomePage.class.getSimpleName();
Button button_disFinder;
private LocationProvider locationProvider;
String Provider,Str_endLocation;
double cur_latitude, cur_longitude,cur_accuracy, end_latitude, end_longitude;
float distance_cur_to_end;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
locationProvider = new LocationProvider(this,this);
Spinner spinner = (Spinner) findViewById(R.id.spinner_schools);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.school_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
public void CurrentLocationClicked(View view) {
if (cur_latitude!=0&&cur_longitude != 0 ){
Spinner spinner = (Spinner) findViewById(R.id.spinner_schools);
spinner.setClickable(true);
String message= String.format("Current Location\n" + "Latitude :" + cur_latitude + "\nLongitude :" + cur_longitude+"\nAccuracy :"+cur_accuracy+"\nProvider :"+Provider);
Toast.makeText(HomePage.this, message, Toast.LENGTH_LONG).show();
}
else{
String message= String.format("Location services disconnected.\nSwich ON Location Service to work App.");
Toast.makeText(HomePage.this, message, Toast.LENGTH_LONG).show();
//System.exit(0);
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(position!= 0) {
Str_endLocation=String.valueOf(parent.getItemAtPosition(position));
Toast.makeText(getApplicationContext(), Str_endLocation + " Selected", Toast.LENGTH_SHORT).show();
switch (Str_endLocation){
//end location latitude and logitude will be taken from here.
case "Kahagolla National School":
end_latitude = 6.816703;end_longitude = 80.9637076;
break;
}
String message3= String.format("End Location\n"+"Latitude :"+end_latitude+"\nLongitude :"+end_longitude);//For Testing
Toast.makeText(HomePage.this, message3, Toast.LENGTH_LONG).show();//For Testing
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public void FindDistanceClicked (View view){
Location curlocation = new Location("");
curlocation.setLatitude(cur_latitude);
curlocation.setLongitude(cur_longitude);
Location endlocation = new Location("");
endlocation.setLatitude(end_latitude);
endlocation.setLongitude(end_longitude);
distance_cur_to_end = curlocation.distanceTo(endlocation)/1000;
String message5= String.format("Distance from current location to\n" + Str_endLocation + " :" + String.format("%.3g%n", distance_cur_to_end)+"km");//For testing
Toast.makeText(HomePage.this, message5, Toast.LENGTH_LONG).show();//For testing
}
public void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
cur_latitude = location.getLatitude();
cur_longitude = location.getLongitude();
cur_accuracy = location.getAccuracy();
Provider = location.getProvider();
LatLng cur_latLng = new LatLng(cur_latitude, cur_longitude);
}
#Override
protected void onResume() {
super.onResume();
locationProvider.connect();
}
#Override
protected void onPause() {
super.onPause();
locationProvider.disconnect();
}
public void ClearClicked (View view){
}
}
Try reversing your onConnected method location code.
First try to get current location and if that is not available then try getting lastKnown location.
Some thing like this
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();
}
}
}
I corrected my issue finally,
From this method i got locations in 3m accuracy,which I want.
Here's code
DistanceFinderActivity.java
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 5*1000; // in Milliseconds
protected LocationManager locationManager;
double cur_latitude, cur_longitude,cur_accuracy, end_latitude, end_longitude;
float distance_cur_to_end;
public LatLng cur_latLng,end_latLng;
MyLocationListener myLocationListener =new MyLocationListener();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_distance_finder);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
myLocationListener
);
//......
}
protected void showCurrentLocation() {
Location location = locationManager.getLastKnownLocation(GPS_PROVIDER);
if (location != null) {
cur_latitude = location.getLatitude();
cur_longitude = location.getLongitude();
cur_accuracy = location.getAccuracy();
Provider = location.getProvider();
DecimalFormat df = new DecimalFormat("#.###");
df.setMinimumFractionDigits(2);
String message = String.format(
"Current Location \nLatitude: %1$s\nLongitude: %2$s\nAccuracy: %3$s\n" +
" Provider: %4$s\nWait until new location capture",
cur_latitude, cur_longitude,String.valueOf(df.format(cur_accuracy)),Provider.toUpperCase()
);
Toast.makeText(MainDistanceFinderActivity.this, message,
Toast.LENGTH_LONG).show();
}
}
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
cur_latitude = location.getLatitude();
cur_longitude = location.getLongitude();
cur_accuracy = location.getAccuracy();
Provider = location.getProvider();
DecimalFormat df = new DecimalFormat("#.###");
df.setMinimumFractionDigits(2);
String message = String.format(
"New Location Captured. \nLatitude: %1$s\nLongitude: %2$s\nAccuracy: %3$s\n" +
" Provider: %4$s",
cur_latitude, cur_longitude,String.valueOf(df.format(cur_accuracy)), Provider.toUpperCase()
);
Toast.makeText(MainDistanceFinderActivity.this, message, Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(MainDistanceFinderActivity.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(MainDistanceFinderActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
Toast.makeText(MainDistanceFinderActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Calling camera from an activity, capturing an image and uploading to a server
i am very new to android, i am trying to capture the image after that i placed that image into image view,its working on emulator but in device it crashes it shows the message force close even it cannot open the camera activity.the following is my code.
please help me how to solve this problem.thank you.
package com.gss.android;
package com.gss.android;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class Pictures extends Activity{
Button btnsave,btnnewpic;
protected ImageView image;
protected String _path;
File sdImageMainDirectory;
private static final int IMAGE_CAPTURE = 0;
protected boolean _taken = true;
private Uri imageUri;
protected static final String PHOTO_TAKEN = "photo_taken";
private static final int CAMERA_PIC_REQUEST = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pictures);
btnsave=(Button)findViewById(R.id.btnsave);
btnnewpic=(Button)findViewById(R.id.btnnewpic);
btnnewpic.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startCameraActivity2();
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if ( requestCode == CAMERA_PIC_REQUEST){
if (resultCode == RESULT_OK){
switch (resultCode) {
case 0:
finish();
break;
case -1:
try {
StoreImage(this, Uri.parse(data.toURI()),
sdImageMainDirectory);
Log.e("file path", "stiring file") ;
} catch (Exception e) {
e.printStackTrace();
}
finish();
}
}
} else if ( requestCode == IMAGE_CAPTURE) {
if (resultCode == RESULT_OK){
Log.d("ANDRO_CAMERA","Picture taken!!!");
ImageView image = (ImageView) findViewById(R.id.image);
image.setImageURI(imageUri);
}
}
}
protected void startCameraActivity2()
{
Log.d("ANDRO_CAMERA", "Starting camera on the phone...");
String fileName = "testphoto.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION,
"Image capture by camera");
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
imageUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, IMAGE_CAPTURE);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState.getBoolean(Pictures.PHOTO_TAKEN)) {
_taken = true;
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean(Pictures.PHOTO_TAKEN, _taken);
}
public static void StoreImage(Context mContext, Uri imageLoc, File imageDir) {
Bitmap bm = null;
try {
bm = MediaStore.Images.Media.getBitmap(mContext.getContentResolver(), imageLoc);
FileOutputStream out = new FileOutputStream(imageDir);
bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
Log.e("file dir",imageDir.toString());
bm.recycle();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I think this is a problem related to the emulator and not the physical device.
I used this code and I got a bitmap:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
captureButton = (Button)findViewById(R.id.capture);
captureButton.setOnClickListener(listener);
imageView = (ImageView)findViewById(R.id.image);
destination = new File(Environment.getExternalStorageDirectory(),"image.jpg");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_IMAGE && resultCode == Activity.RESULT_OK) {
//Bitmap userImage = (Bitmap)data.getExtras().get("data");
try {
FileInputStream in = new FileInputStream(destination);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 10; //Downsample 10x
Bitmap userImage = BitmapFactory.decodeStream(in, null, options);
imageView.setImageBitmap(userImage);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//Add extra to save full-image somewhere
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(destination));
Toast.makeText(JMABarcodeScannerActivity.this, Uri.fromFile(destination).toString(), Toast.LENGTH_SHORT).show();
startActivityForResult(intent, REQUEST_IMAGE);
}
};
}
Main.XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="#+id/capture"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Take a Picture"
/>
<ImageView
android:id="#+id/image"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="centerInside"
/>
</LinearLayout>