0% found this document useful (0 votes)
341 views11 pages

User Location Access in Android 31

Uploaded by

umeshsabale.2006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
341 views11 pages

User Location Access in Android 31

Uploaded by

umeshsabale.2006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
  • Practical No 31
  • Practical No 32

Practical No 31

31.1
[Link]
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="[Link]
package="[Link]">

<uses-permission
android:name="[Link].ACCESS_COARSE_LOCATION" />
<uses-permission
android:name="[Link].ACCESS_FINE_LOCATION" />
<uses-permission
android:name="[Link].ACCESS_BACKGROUND_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/[Link]">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="[Link]" />

<category android:name="[Link]" />


</intent-filter>
</activity>
</application>

</manifest>
Main_Activity.Java
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class MainActivity extends AppCompatActivity {

private static final int


PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
private FusedLocationProviderClient fusedLocationClient;

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);

fusedLocationClient =
[Link](this);

// Check for permissions


if ([Link](this,
[Link].ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Permission is not granted, request it
[Link](this,
new String[]{[Link].ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
} else {
// Permission has already been granted
getLocation();
}
}

private void getLocation() {


// Check if permission is granted
if ([Link](this,
[Link].ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
// Permission is granted
[Link]()
.addOnSuccessListener(this, location -> {
// Got last known location. In some rare situations, this can be
null.
if (location != null) {
// Handle location
double latitude = [Link]();
double longitude = [Link]();
[Link](this, "Latitude: " + latitude + ", Longitude: " +
longitude,
Toast.LENGTH_LONG).show();
} else {
[Link](this, "Location not available",
Toast.LENGTH_SHORT).show();
}
});
} else {
// Permission denied
[Link](this, "Location permission denied",
Toast.LENGTH_SHORT).show();
}
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull
String[] permissions, @NonNull int[] grantResults) {
if (requestCode ==
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION) {
if ([Link] > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
// Permission granted, get the location
getLocation();
} else {
// Permission denied
[Link](this, "Location permission denied",
Toast.LENGTH_SHORT).show();
}
}
}
}
Activity_Main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

</RelativeLayout>
Practical No 32
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<fragment
android:id="@+id/map"
android:name="[Link]"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="50dp" />

<Button
android:id="@+id/button_draw_route"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Draw Route"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="16dp"/>

</RelativeLayout>
[Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import
[Link]
st;
import [Link];
import [Link];
import [Link];
import
[Link];
import
[Link];
import
[Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class MainActivity extends AppCompatActivity implements


OnMapReadyCallback {

private GoogleMap mMap;


private PlacesClient placesClient;
private Button drawRouteButton;
private LatLng origin, destination;

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);

SupportMapFragment mapFragment = (SupportMapFragment)


getSupportFragmentManager()
.findFragmentById([Link]);
[Link](this);

drawRouteButton = findViewById([Link].button_draw_route);
[Link](new [Link]() {
@Override
public void onClick(View view) {
drawRoute();
}
});
if (![Link]()) {
[Link](getApplicationContext(),
getString([Link].google_maps_key));
}
placesClient = [Link](this);
}

@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
[Link]([Link](this,
[Link].map_style));
LatLng defaultLocation = new LatLng(37.7749, -122.4194); // San
Francisco
[Link]([Link](defaultLocation,
12));
LatLng sydney = new LatLng(-34, 151);
[Link](new MarkerOptions().position(sydney).title("Marker in
Sydney"));
[Link]([Link](sydney));
}

private void drawRoute() {


if (origin == null || destination == null) {
[Link](this, "Please select origin and destination",
Toast.LENGTH_SHORT).show();
return;
}
DirectionsApiRequest directions = new DirectionsApiRequest(new
[Link]()
.apiKey(getString([Link].google_maps_key))
.build());

[Link](new [Link]([Link],
[Link]));
[Link](new
[Link]([Link], [Link]));
[Link]([Link]);
[Link]([Link]);
[Link](new DateTime());

[Link](new [Link]<DirectionsResult>() {
@Override
public void onResult(DirectionsResult result) {
}

@Override
public void onFailure(Throwable e) {
}
});
}
}

Common questions

Powered by AI

The application's error handling primarily consists of toast messages to inform the user of issues, such as permission denial or null locations. This simplistic approach lacks depth, as it does not log errors, offer retry mechanisms, or notify users of mitigation strategies. This might lead to poor user experience under network or service errors. Instead, implementing logging, detailed user feedback, and corrective instructions could significantly improve reliability and user confidence during location or map service failures .

The application could be extended by incorporating real-time location tracking, integrating geofencing features for location-based notifications, and utilizing background location services to maintain activities like tracking routes while in background. Enhancements like local weather integration using location data, travel recommendations, and extended route planning with waypoints and estimated times could significantly enrich user experience. Additionally, using machine learning to predict user location patterns and offer personalized suggestions could be explored .

The application uses 'SupportMapFragment' to integrate Google Maps into the UI. Upon initialization, it calls 'getMapAsync' on the map fragment to setup the map. Once the map is ready, it sets a custom style with 'setMapStyle'. The camera is moved to a default location (San Francisco: 37.7749, -122.4194) with a zoom level of 12. Additionally, it adds a marker for Sydney and moves the camera to this location too. These operations set up the initial view and style of the map .

The 'drawRoute' method is designed to calculate a route between an origin and a destination if both are set. The method utilizes 'DirectionsApiRequest' with parameters including the origin and destination coordinates, mode set to driving, and metric units. It configures the request using an 'GeoApiContext' initialized with an API key. If either the origin or destination is unset, the method displays a toast prompting the user to set these locations. The route calculation is executed asynchronously with callbacks handling success or failure .

The application customizes the map style using 'MapStyleOptions.loadRawResourceStyle', which allows it to load a JSON file defining the map's visual styling. This can impact user experience positively by offering a more visually appealing and coherent map style that aligns with the app's theme or branding. At the same time, it can highlight or suppress certain map features based on user or business requirements, which can enhance usability or focus relevant data on the map .

Compatibility with different device orientations and screen sizes is managed through the use of 'RelativeLayout' with components set to 'match_parent' dimensions, allowing UI components to dynamically scale with the device's screen. This layout choice ensures that UI elements such as buttons and map views adjust their placement based on the relative positions, keeping them visible and functional across different device configurations and orientations .

The application first checks for the 'ACCESS_FINE_LOCATION' permission using the 'ContextCompat.checkSelfPermission' method. If the permission is not granted, it requests the required permission using 'ActivityCompat.requestPermissions'. If permissions are denied upon request, the application displays a toast message indicating "Location permission denied" .

The 'FusedLocationProviderClient' is used to obtain location information. It provides a simplified API to access location features. In the application, this client is retrieved by calling 'LocationServices.getFusedLocationProviderClient'. The application uses this client to get the last known location with 'getLastLocation'. If the location is successfully retrieved and not null, the latitude and longitude are extracted and displayed using a toast message .

The application initializes the Places API by checking if 'Places' is initialized and calls 'Places.initialize' with the context and Google Maps API key. This is a necessary step to use the Places API. After initialization, a 'PlacesClient' is created with 'Places.createClient'. This approach correctly follows the required steps for initializing Places services; however, the comprehensive error handling during initialization is not discussed, which could potentially lead to missed errors or API misuse. Ensuring robust error handling and validation during API initialization is vital for smooth operation in production environments .

Without the 'ACCESS_BACKGROUND_LOCATION' permission, the application won't be able to access location data while it's running in the background. This limits the app's capability to provide location-based services unless it is actively in use by the user. The manifest includes this permission declaration, indicating an intent to offer background location tracking, though it may not be currently implemented in the code provided. Lack of this functionality could diminish user experience in terms of continuous navigation or location-based alerts when the app is minimized .

You might also like