Wednesday, September 29, 2021

Where am I ? Location Based Services @FusedLocationProviderClient

 "Jai Sarawati Maa"

Location Based Services 

The location APIs available in Google Play services facilitate adding location awareness to your app with automated location tracking, wrong-side-of-the-street detection, geofencing, and activity recognition. 

The API updates your app periodically with the best available location, based on the currently-available location providers such as WiFi and GPS (Global Positioning System). 

I am uploading how to find out your current location and address by using FusedLocationProviderClient. Which is the best way to deal with location based activities.  

Step-I: Open Android SDK Manager and check either Google Play Services Installed or not. if not please install google play services. See the below pic. 


  

Step-II: After installation kindly add below dependencies in module level gradle file. 

implementation 'com.google.android.gms:play-services-location:18.0.0'

Step-III: Add meta data in between application tag and required permission in Manifest file.

<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version"/>

<uses-permission android:name="android.permission.
                              ACCESS_FINE_LOCATION"/>
Step-IV: Your output will be like. 





See the code of MainActivity
package com.example.locationbasedservices2021;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity
{
final int REQUEST_CODE_LOCATION=123;
int locationRequestCode;
TextView lat_text,long_text,add_text;
FusedLocationProviderClient fusedLocationClient;
double lat, longi;
String addres;
Button button;
Boolean flag = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lat_text = findViewById(R.id.textLat);
long_text = findViewById(R.id.textLong);
add_text = findViewById(R.id.textCity);
button = findViewById(R.id.btn_location);
fusedLocationClient = LocationServices.
getFusedLocationProviderClient(this);

locationRequestCode =
ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION);
 button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(flag)
{
finLoc();

}
}
});
}

@Override
protected void onStart() {
super.onStart();

if(locationRequestCode == PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(this,"Permission Already Given ",
                        Toast.LENGTH_LONG).show();
flag = true;
}
else
{
askforPermission();
}
}
private void askforPermission() {

if(locationRequestCode != PackageManager.PERMISSION_GRANTED)
{
if(!ActivityCompat.shouldShowRequestPermissionRationale
      (MainActivity.this,Manifest.permission.ACCESS_FINE_LOCATION))
{
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_CODE_LOCATION);
return;
}
else
{
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_CODE_LOCATION);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
        String[] permissions,int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions,
            grantResults);
if(requestCode == REQUEST_CODE_LOCATION)
{
if(grantResults.length>0 && grantResults[0] ==
                    PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(this,"Permission Granted",
                                Toast.LENGTH_LONG).show();
flag = true;
finLoc();
}
}
}
private void finLoc() {

fusedLocationClient.getLastLocation().addOnCompleteListener
                (new OnCompleteListener<Location>() {
        @Override
public void onComplete(Task<Location> task) {

Location location = task.getResult();
if(location!=null)
{
Geocoder geocoder = new Geocoder(MainActivity.this,
                                 Locale.getDefault());
try {
List<Address> address = geocoder.getFromLocation
                                        (location.getLatitude(),
             location.getLongitude(),1);
lat = location.getLatitude();
longi = location.getLongitude();
lat_text.setText("Latitide: " + lat);
long_text.setText("Longitude: " + longi);

StringBuilder sb = new StringBuilder();
if (address.size() > 0) {
Address addr = address.get(0);
for (int i = 0; i < addr.getMaxAddressLineIndex(); i++)
sb.append(addr.getAddressLine(i)).append("\n");
sb.append(addr.getLocality()).append("\n");
sb.append(addr.getPostalCode()).append("\n");
sb.append(addr.getCountryName());
}
addres = sb.toString();

} catch (IOException e) {
e.printStackTrace();
}
}
add_text.setText("Address:"+addres);
}
});
}
}

// Layout File 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">

<Button
android:id="@+id/btn_location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="120dp"
android:layout_marginTop="100dp"
android:text="Find Location" />

<TextView
android:id="@+id/textLat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Lattitude"
android:textSize="30dp"
android:layout_marginLeft="60dp"
android:layout_marginTop="20dp"/>
<TextView
android:id="@+id/textLong"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Longitude "
android:textSize="30dp"
android:layout_marginLeft="60dp"
android:layout_marginTop="20dp"/>

<TextView
android:id="@+id/textCity"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_marginLeft="60dp"
android:layout_marginTop="20dp"
android:text="City"
android:textSize="30dp" />

</LinearLayout>


Friday, April 2, 2021

Broadcast Receiver in Android

Broadcast Receiver 

Android apps can send or receive broadcast messages from the Android system and other Android apps. These broadcasts are sent when an event of interest occurs. 

For example, the Android system sends broadcasts when various system events occur, such as when the system boots up or the device starts charging. Apps can also send custom broadcasts, for example, to notify other apps of something that they might be interested in (for example, some new data has been downloaded).

Apps can register to receive specific broadcasts. When a broadcast is sent, the system automatically routes broadcasts to apps that have subscribed to receive that particular type of broadcast.

System Broadcast : The system automatically sends broadcasts when various system events occur, such as when the system switches in and out of airplane mode. System broadcasts are sent to all apps that are subscribed to receive the event.

Referenceshttps://developer.android.com/guide/components/broadcasts

Demo App which implement System Broadcast

Step-1: Create a Main Activity (No need to add any widget in Layout File)

Like: 

import androidx.appcompat.app.AppCompatActivity; // package name

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

IntentFilter intentfilterAirplaneMode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

intentfilterAirplaneMode = new IntentFilter
                                    (Intent.ACTION_AIRPLANE_MODE_CHANGED);
}

}
Step-2: Create a java class (Define Broadcast Receiver) by                             
                Extending BroadcastReceiver  

 Like: 

package com.example.broadcastex1y2021;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class AirModeChanged extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, " Airplane Mode Changed",
                                      Toast.LENGTH_LONG).show();
}
}
Step-3: Add the action in manifest file with the receiver (inside application tag)
 Like: 
<receiver android:name=".AirModeChanged">
<intent-filter>
<action android:name="android.intent.action.AIRPLANE_MODE"/>
</intent-filter>
</receiver>

Run your app and see the effect by changing Airplane Mode 

Demo App which implement User Defined Broadcast

Step-1: Create a Main Activity with Layout as


Add onClick on Button - I have added 
SendBroadCast

Now see the Main Activity Code 

import androidx.appcompat.app.AppCompatActivity; // package name

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

IntentFilter intentFilter;
    Intent intent;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

 intentFilter = new IntentFilter("MAIS");
    }
    public void SendBroadCast(View view) {
    intent = new Intent("MAIS");
intent.putExtra("BCA", "Hi How are you");
sendBroadcast(intent);
    }
}
Step-2: Create two or more  java classes which you want to respond after   
             Broadcasting (Define Broadcast Receiver) by                       
            Extending BroadcastReceiver  

 Like: 

   FirstReceiver
    package com.example.broadcastex1y2021;

    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.widget.Toast;

    public class FirstReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, " Received Message in 1 " +
intent.getStringExtra("BCA"), Toast.LENGTH_LONG).show();
     }
    }

SecondReceiver
package com.example.broadcastex1y2021;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class SecondReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Received message in 2 " +
intent.getStringExtra("BCA"), Toast.LENGTH_LONG).show();
}
}

Step-3: Add the action in manifest file with the receiver (inside application tag) for                 both receiver 
 Like: 
<receiver android:name=".FirstReceiver">
<intent-filter>
<action android:name="MAIS"/>
</intent-filter>
</receiver>
<receiver android:name=".SecondReceiver">
<intent-filter>
<action android:name="MAIS"/>
</intent-filter>
</receiver>

Run your app and see the effect by clicking on Button