Wednesday, April 20, 2016

Customized Notification - More Powerful

" Jai Saraswati Maa" 
Hi ... Dear All ..Today I am uploading a superb example of Creating Notification with Action and after click it will disappear. 
Please check.
I am using Android Studio 1.5.1
Minimun SDK API 19
Target SDK API 23
Please Like us & put your valuable suggestions in comment box.
**** Nothing in layout xml file its blank
A. Output will be like 
a.      


b.   
          


B. Java Code  


package com.exam.ravi.notificationex1;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
 Intent intent = new Intent(Intent.ACTION_DIAL);

    PendingIntent pendingIntent = PendingIntent.getActivity(this,1,intent,0);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setContentTitle("Lunch is ready! ");
    builder.setContentText("Call Him...It's getting cold...");
    builder.setContentIntent(pendingIntent);
    builder .addAction(android.R.drawable.ic_menu_call, "Call", pendingIntent);
    builder.setSmallIcon(android.R.drawable.ic_menu_call);
    builder.setAutoCancel(true);
    Notification notification = builder.build();
    NotificationManager notificationManager = (NotificationManager) 
                                    getSystemService(NOTIFICATION_SERVICE);

    notificationManager.notify(1,notification);
    }
}


Create Notification and start new Activity

" Jai Saraswati Maa" 
Hi ... Dear All ..Today I am uploading a superb example of Creating Notification and start of a new activity on click this notification. 
Please check.
I am using Android Studio 1.5.1
Minimun SDK API 19
Target SDK API 23
Please Like us & put your valuable suggestions in comment box.
Add one button in main layout file with onClick attribute (My function is madeNotification )
 and a display message on second activity layout.
A. Output will be like 
a.     


b.
               


c.    
                



B.  Java Source code 


package com.exam.ravi.notificationex1;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

    }
    public void madeNotification(View view) {

        Intent intent = new Intent(this, NotificationReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, intent,
                                               PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setContentTitle("New mail from  Ravi Sir");
        builder.setContentText("Hi this is notification mail");
        builder .setSmallIcon(R.mipmap.ic_launcher);
        builder .setContentIntent(pendingIntent);
        Notification notification = builder.build();
        NotificationManager notificationManager = (NotificationManager) 
                                 getSystemService(NOTIFICATION_SERVICE);
        notificationManager.notify(1, notification);
    }
} 

Tuesday, April 19, 2016

Google Map API V2 Part-II (Add Marker with Google Map)

" Jai Saraswati Maa"

Please follow

Google Map API V2 Part-I (Prepare yourself to do fun with Google Map)


Extra add on from previous example ....
1. implements OnMapReadyCallback interface
2. Add fragment with Async
3. Implements callback method
4. Add marker 

A. Output will be like  - You have to Zoom Out 
   




B. xml layout file is same as in Part-I

C. Java file MapsActivity.java is as 


package com.exam.ravi.googlemapex1;

import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback
 {

    private GoogleMap mMap;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
  SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
     .findFragmentById(R.id.map);
     mapFragment.getMapAsync(this);
}

@Overridepublic void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
LatLng jaipur = new LatLng(26.923952,75.826743);
MarkerOptions mo = new MarkerOptions();
mo.position(jaipur).title("HawaMahal Jaipur").snippet("Padahro Mhare Desh...");
mMap.addMarker(mo);
mMap.moveCamera(CameraUpdateFactory.newLatLng(jaipur));
   }
}


D.....   Just change inside the onMapReady method like you will get already zoomed out output

Like    ---  

@Overridepublic void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    LatLng jaipur = new LatLng(26.923952,75.826743);
    CameraPosition cameraPosition = CameraPosition.builder()
      .zoom(17).tilt(20).bearing(90).target(jaipur).build();
    MarkerOptions mo = new MarkerOptions();
    mo.position(jaipur).title("HawaMahal Jaipur").snippet("Padahro Mhare Desh...");
    mMap.addMarker(mo);
    mMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}

E.  If you will change the body of onMapReady function you will get output like 
          
            



Location Based Services Part-III (Get Updated Address also with Latitude & Longitude)

" Jai Saraswati Maa"

Please refer Part - II  of LBS


In this example you will also get Address of your new updated location.
In previous example i have added only one Button & one Text View in Layout.
One method which is on onClick of Button.
Changed from previous example are in Bold Italic. 
A. Changed Layout file is activity_main.xml file is as
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:paddingBottom="@dimen/activity_vertical_margin"

    android:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin"

    tools:context="com.exam.ravi.locationbsex1.MainActivity">

    <TextView        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Ltitude and  Longitude... "

        android:id="@+id/textLocation"

        android:textSize="20dp"/>
    <Button        android:layout_width="wrap_content"

        android:layout_height="wrap_content"        android:text="GetAddress"

        android:onClick="findAddress"

        android:id="@+id/butAdd"

        android:layout_below="@+id/textLocation"

        android:layout_marginTop="10dp"/>

    <TextView        android:layout_width="wrap_content"

        android:layout_height="match_parent"

        android:id="@+id/textAdd"

        android:textSize="15sp"

        android:layout_below="@+id/butAdd"

        android:layout_marginTop="10dp"/>
</RelativeLayout>

B. Java code is as   MainActivity.java  

package com.exam.ravi.locationbsex1;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class MainActivity extends AppCompatActivity
         implements GoogleApiClient.OnConnectionFailedListener ,
                GoogleApiClient.ConnectionCallbacks ,LocationListener
{
    TextView dis,add;
    GoogleApiClient googleApiClient;
    int SERVICE_CODE = 99;
    Double lat,lng;
    LocationRequest locationRequest;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        add= (TextView) findViewById(R.id.textAdd);
        dis = (TextView) findViewById(R.id.textLocation);
        if(checkServices())
        {
            clientInitialization();
        }
    }
    private void clientInitialization() {
        googleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addOnConnectionFailedListener(this)
                .addConnectionCallbacks(this)
                .build();
    }
    @Override    protected void onStart() {
        super.onStart();
        googleApiClient.connect();
    }
@Overrideprotected void onStop() {
    super.onStop();
    if(googleApiClient.isConnected())
        googleApiClient.disconnect();
}

private boolean checkServices()
{
    int result= GooglePlayServicesUtil.isGooglePlayServicesAvailable
                                                      (getApplicationContext());
    if(result!= ConnectionResult.SUCCESS)
    {
        if(GooglePlayServicesUtil.isUserRecoverableError(result))
        {
            GooglePlayServicesUtil.getErrorDialog(result,this,SERVICE_CODE).show();
        }
        return false;
    }
    return true;
}

@Overridepublic void onConnected(Bundle bundle) {
locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(36000000);
        LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient,
                               locationRequest,this);

    }

    @Override    public void onConnectionSuspended(int i) {
     Toast.makeText(this, "Connection Susspended", Toast.LENGTH_SHORT).show();
    }

    @Override    public void onConnectionFailed(ConnectionResult connectionResult) {
        Toast.makeText(this, "Connection Failed", Toast.LENGTH_SHORT).show();

    }

    @Override    public void onLocationChanged(Location location) {
        lat = location.getLatitude();
        lng = location.getLongitude();
        if(location!=null)
            dis.setText("Latitude = " + lat + "\n Longitude = " + lng);
        else            dis.setText("Location Not Found");

    }
   public void findAddress(View view) {
       Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
       try {
           List<Address> addressList = geocoder.getFromLocation(lat,lng, 1);
           if (addressList != null && addressList.size() > 0) {
             String message ="";
               for(int i = 0 ; i<addressList.get(0).getMaxAddressLineIndex();i++)
               {
                   message = message + addressList.get(0).getAddressLine(i)+"\n";
               }
            
               add.setText("Address is \n"+ message);
           }
       } catch (IOException e) {
           e.printStackTrace();
       }
   }
}
  

Google Map API V2 Part-I (Prepare yourself to do fun with Google Map)

" Jai Saraswati Maa" 
Hi ... Dear All ..Today I am uploading a superb example Part I of my Google Map Series.
In this examples we are using Google Map API V2 latest one API for Google Map.
This example is just to setup your emulator to do fun with Google Map.
I am using Android Studio 1.5.1
Minimun SDK API 19
Target SDK API 23
*** Make sure Google Play Services is installed or not. (if not please install first)
*** add permission in manifest file like 
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
*** Add meta data tag within application tag like 
<meta-data    android:name="com.google.android.geo.API_KEY"

    android:value="@string/google_maps_key" />

**here Google Map API key is very important so i have added at the starting  of this 
    example how to get this Key.  Read Carefully  
Okkkkkkk... lets start

Create a new project with Google Map Activity 
It will generate one important file google_maps_api.xml file under Values folder.

***A .... How get Google API 
1. open Google Console API  use https://console.developers.google.com
2.   Click on Google Maps Android API in Google Maps APIs 
3. Enable this after Enabled it shows Disable option 
4. Go on Create a New Project Name your Project and click OK 
5. Now Create Credentials for API key 
6. Select Android Key   
7. Name your key and add package name and SHA1 fingerprint (Which you get from 
     google_maps_api.xml) like my is AA:A2:E3:05:65:2A:89:1E:83:81:8F:78:A0:89:73:1B 
     you should put yours  and insert your package name   and click on create copy 
     the key and put it in the google_maps_api.xml at the place of your key.
******* you should logged in to do all above steps.
A. Output will be like 
           
                  

B. Layout xml file is  activity_maps.xml is as 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:map="http://schemas.android.com/apk/res-auto"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical"

    tools:context="com.exam.ravi.googlemapex1.MapsActivity" >
    <fragment        android:id="@+id/map"

        android:name="com.google.android.gms.maps.SupportMapFragment"

        android:layout_width="match_parent"

        android:layout_height="match_parent"></fragment>
    </LinearLayout>

C. Java file is 

package com.exam.ravi.googlemapex1;

import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;

public class MapsActivity extends AppCompatActivity

{

   private GoogleMap mMap;

   @Override   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_maps);
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
    .findFragmentById(R.id.map);
    }
}

Sunday, April 17, 2016

Location Based Services Part-II (Get Updates in every 30 seconds)

Please refer Part - I

Location Based Services Part-I (Find Latitude & Longitude)


And make few changes in MainActivity.java file.
Please see.....

A. One more method added and LocationListener added   in 
       MainActivity.java   is as 

package com.exam.ravi.locationbsex1;
import android.location.Location;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

public class MainActivity extends AppCompatActivity
         implements GoogleApiClient.OnConnectionFailedListener ,
                GoogleApiClient.ConnectionCallbacks ,LocationListener
{
    TextView dis;
    GoogleApiClient googleApiClient;
    int SERVICE_CODE = 99;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dis = (TextView) findViewById(R.id.textLocation);
        if(checkServices())
        {
            clientInitialization();
        }
    }
    private void clientInitialization() {
        googleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addOnConnectionFailedListener(this)
                .addConnectionCallbacks(this)
                .build();
    }
    @Override    protected void onStart() {
        super.onStart();
        googleApiClient.connect();
    }

    @Override    protected void onStop() {
        super.onStop();
        if(googleApiClient.isConnected())
            googleApiClient.disconnect();
    }

    private boolean checkServices()
    {
        int result= GooglePlayServicesUtil.isGooglePlayServicesAvailable
                                             (getApplicationContext());
        if(result!= ConnectionResult.SUCCESS)
        {
            if(GooglePlayServicesUtil.isUserRecoverableError(result))
            {
             GooglePlayServicesUtil.getErrorDialog(result,this,SERVICE_CODE).show();
            }
            return false;
        }
        return true;
    }

    @Override    public void onConnected(Bundle bundle) {
         LocationRequest locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(30000);
        LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient,
                                                        locationRequest,this);
    }

    @Override    public void onConnectionSuspended(int i) {
        Toast.makeText(this, "Connection Susspended", Toast.LENGTH_SHORT).show();
    }

    @Override    public void onConnectionFailed(ConnectionResult connectionResult) {
        Toast.makeText(this, "Connection Failed", Toast.LENGTH_SHORT).show();

    }

    @Override    public void onLocationChanged(Location location) {
        
        if(location!=null)
            dis.setText("Latitude = " + location.getLatitude()+ 
                              "Longitude" + location.getLongitude());
        else            dis.setText("Location Not Found");


    }
}

Location Based Services Part-I (Find Latitude & Longitude)

" Jai Saraswati Maa" 
Hi ... Dear All ..Today I am uploading a superb example of finding Latitude & Longitude of your position.

Please check.
I am using Android Studio 1.5.1
Minimun SDK API 19
Target SDK API 23
Please Like us & put your valuable suggestions in comment box.
***Please check on physical device or on emulator but make sure to set your position.
*** Make sure Google Play Services is installed or not. (if not please install first)
*** Add dependency in gradle file like
compile 'com.google.android.gms:play-services:8.3.0'

*** Add meta tag with application tag in manifest file like 
<meta-data    android:name="com.google.android.gms.version"

    android:value="@integer/google_play_services_version"/>
**** Also add permission in manifest file like 
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION">
               </uses-permission>

A. Nothing in Layout file only one text view is there to show values
xml code of activity_main.xml is 

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:paddingBottom="@dimen/activity_vertical_margin"

    android:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin"

    tools:context="com.exam.ravi.locationbsex1.MainActivity">

    <TextView        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Ltitude and  Longitude... "

        android:id="@+id/textLocation"

        android:textSize="25sp"/>
</RelativeLayout>

B. Java Code of MainActivity.java 

package com.exam.ravi.locationbsex1;
import android.location.Location;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;

public class MainActivity extends AppCompatActivity
         implements GoogleApiClient.OnConnectionFailedListener ,
                                        GoogleApiClient.ConnectionCallbacks
{
    TextView dis;
    GoogleApiClient googleApiClient;
    int SERVICE_CODE = 99;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dis = (TextView) findViewById(R.id.textLocation);
        if(checkServices())
        {
            clientInitialization();
        }
    }
    private void clientInitialization() {
        googleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addOnConnectionFailedListener(this)
                .addConnectionCallbacks(this)
                .build();
    }
    @Override    protected void onStart() {
        super.onStart();
        googleApiClient.connect();
    }

    @Override    protected void onStop() {
        super.onStop();
        if(googleApiClient.isConnected())
            googleApiClient.disconnect();
    }

    private boolean checkServices()
    {
        int result= GooglePlayServicesUtil.isGooglePlayServicesAvailable
                                           (getApplicationContext());
        if(result!= ConnectionResult.SUCCESS)
        {
            if(GooglePlayServicesUtil.isUserRecoverableError(result))
            {
                GooglePlayServicesUtil.getErrorDialog(result,this,SERVICE_CODE).show();
            }
            return false;
        }
        return true;
    }

    @Override    public void onConnected(Bundle bundle) {
        Location location  = LocationServices.FusedLocationApi.getLastLocation
                                            (googleApiClient);
        if(location!=null)
            dis.setText("Latitude = " + location.getLatitude()+ "Longitude" +
                                  location.getLongitude());
        else            dis.setText("Location Not Found");

    }

    @Override

    public void onConnectionSuspended(int i) {
        Toast.makeText(this, "Connection Susspended", Toast.LENGTH_SHORT).show();
    }

    @Override

    public void onConnectionFailed(ConnectionResult connectionResult) {
        Toast.makeText(this, "Connection Failed", Toast.LENGTH_SHORT).show();

    }
}