Tuesday, 12 November 2013

Adding and removing Proximity Alert in Google Map Android API V2 using LocationManager

Step 1 :- Create New Android Project.



Step 2 :- Add Google-play-services_lib to your project.

Step 3 :- Open AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mapv2.demo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
   
    <permission
          android:name="com.mapv2.demo.permission.MAPS_RECEIVE"
          android:protectionLevel="signature"/>

    <uses-permission android:name="com.mapv2.demo.permission.MAPS_RECEIVE"/>

    <uses-permission android:name="android.permission.INTERNET"/>
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
        <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>


    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/>  

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.mapv2.demo.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
       
        <activity
            android:name=".ProximityActivity"
            android:label="@string/app_name" >
            <intent-filter >
                <action android:name="in.wptrafficanalyzer.activity.proximity"/>
                <category android:name="android.intent.category.DEFAULT" />           
            </intent-filter>
        </activity>
       
        <activity
            android:name=".NotificationView"
            android:label="@string/app_name" >

            <intent-filter >
                <category android:name="android.intent.category.DEFAULT" />           
                </intent-filter>

        </activity>
       
       
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyCmX7SLVHXxU9pSqb2QbAOvdnjAGUulOrk"/>       
       
    </application>

</manifest>

Step 4 :- Open activity_main.xml.

<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"
    tools:context=".MainActivity" >         
   
    <fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.SupportMapFragment" />

</RelativeLayout>


1.)  notification.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
   
    <TextView
        android:id="@+id/tv_notification"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

Step 5 :- Open MainActivity.java

package com.mapv2.demo;

import android.app.Dialog;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends FragmentActivity {
   
    GoogleMap googleMap;
    LocationManager locationManager;
    PendingIntent pendingIntent;
    SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);   
       
       
         // Getting Google Play availability status
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

        // Showing status
        if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available

            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
            dialog.show();

        }else { // Google Play Services are available           

            // Getting reference to the SupportMapFragment of activity_main.xml
            SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

            // Getting GoogleMap object from the fragment
            googleMap = fm.getMap();

            // Enabling MyLocation Layer of Google Map
            googleMap.setMyLocationEnabled(true);          
           
           
            // Getting LocationManager object from System Service LOCATION_SERVICE
            locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
           
           
            // Opening the sharedPreferences object
            sharedPreferences = getSharedPreferences("location", 0);
           
            // Getting stored latitude if exists else return 0
            String lat = sharedPreferences.getString("lat", "0");
           
            // Getting stored longitude if exists else return 0
            String lng = sharedPreferences.getString("lng", "0");
           
            // Getting stored zoom level if exists else return 0
            String zoom = sharedPreferences.getString("zoom", "0");
           
            // If coordinates are stored earlier
            if(!lat.equals("0")){
               
                // Drawing circle on the map
                drawCircle(new LatLng(Double.parseDouble(lat), Double.parseDouble(lng)));
               
                // Drawing marker on the map
                drawMarker(new LatLng(Double.parseDouble(lat), Double.parseDouble(lng)));
               
                // Moving CameraPosition to previously clicked position
                googleMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(Double.parseDouble(lat), Double.parseDouble(lng))));
               
                // Setting the zoom level in the map
                googleMap.animateCamera(CameraUpdateFactory.zoomTo(Float.parseFloat(zoom)));               
               
                               
            }
           
           
            googleMap.setOnMapClickListener(new OnMapClickListener() {
               
                @Override
                public void onMapClick(LatLng point) {
                   
                    // Removes the existing marker from the Google Map
                    googleMap.clear();       
                                       
                    // Drawing marker on the map
                    drawMarker(point);
                   
                    // Drawing circle on the map
                    drawCircle(point);                   
                   
                    // This intent will call the activity ProximityActivity
                    Intent proximityIntent = new Intent("in.wptrafficanalyzer.activity.proximity");                   
                   
                    // Creating a pending intent which will be invoked by LocationManager when the specified region is
                    // entered or exited
                    pendingIntent = PendingIntent.getActivity(getBaseContext(), 0, proximityIntent,Intent.FLAG_ACTIVITY_NEW_TASK);                   
                   
                    // Setting proximity alert
                    // The pending intent will be invoked when the device enters or exits the region 20 meters
                    // away from the marked point
                    // The -1 indicates that, the monitor will not be expired
                    locationManager.addProximityAlert(point.latitude, point.longitude, 20, -1, pendingIntent);   
                   
                    /** Opening the editor object to write data to sharedPreferences */
                    SharedPreferences.Editor editor = sharedPreferences.edit();

                    /** Storing the latitude of the current location to the shared preferences */
                    editor.putString("lat", Double.toString(point.latitude));
                   
                    /** Storing the longitude of the current location to the shared preferences */
                    editor.putString("lng", Double.toString(point.longitude));
                   
                    /** Storing the zoom level to the shared preferences */
                    editor.putString("zoom", Float.toString(googleMap.getCameraPosition().zoom));               

                    /** Saving the values stored in the shared preferences */
                    editor.commit();               
                   
                    Toast.makeText(getBaseContext(), "Proximity Alert is added", Toast.LENGTH_SHORT).show();                   
                   
                }
            });   
           
            googleMap.setOnMapLongClickListener(new OnMapLongClickListener() {               
                @Override
                public void onMapLongClick(LatLng point) {
                    Intent proximityIntent = new Intent("in.wptrafficanalyzer.activity.proximity");
                   
                    pendingIntent = PendingIntent.getActivity(getBaseContext(), 0, proximityIntent,Intent.FLAG_ACTIVITY_NEW_TASK);
                   
                    // Removing the proximity alert                   
                    locationManager.removeProximityAlert(pendingIntent);
                   
                    // Removing the marker and circle from the Google Map
                    googleMap.clear();
                   
                    // Opening the editor object to delete data from sharedPreferences
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                   
                    // Clearing the editor
                    editor.clear();
                   
                    // Committing the changes
                    editor.commit();
                   
                    Toast.makeText(getBaseContext(), "Proximity Alert is removed", Toast.LENGTH_LONG).show();
                }
            });          
        }   
    }   
   
    private void drawMarker(LatLng point){
        // Creating an instance of MarkerOptions
        MarkerOptions markerOptions = new MarkerOptions();                   
       
        // Setting latitude and longitude for the marker
        markerOptions.position(point);
       
        // Adding marker on the Google Map
        googleMap.addMarker(markerOptions);
       
    }
   
   
    private void drawCircle(LatLng point){
       
        // Instantiating CircleOptions to draw a circle around the marker
        CircleOptions circleOptions = new CircleOptions();
       
        // Specifying the center of the circle
        circleOptions.center(point);
       
        // Radius of the circle
        circleOptions.radius(20);
       
        // Border color of the circle
        circleOptions.strokeColor(Color.BLACK);
       
        // Fill color of the circle
        circleOptions.fillColor(0x30ff0000);
       
        // Border width of the circle
        circleOptions.strokeWidth(2);
       
        // Adding the circle to the GoogleMap
        googleMap.addCircle(circleOptions);
       
    }   

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}





1.)  NotificationView.java

package com.mapv2.demo;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class NotificationView extends Activity {
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.notification);
       
        TextView tv = (TextView) findViewById(R.id.tv_notification);
        Bundle data = getIntent().getExtras();
        tv.setText(data.getString("content"));       
    }
}


2.) ProximityActivity.java


package com.mapv2.demo;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;



public class ProximityActivity extends Activity {
   
    String notificationTitle;
    String notificationContent;
    String tickerMessage;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
       
        boolean proximity_entering = getIntent().getBooleanExtra(LocationManager.KEY_PROXIMITY_ENTERING, true);
       
        if(proximity_entering){
            Toast.makeText(getBaseContext(),"Entering the region"  ,Toast.LENGTH_LONG).show();
            notificationTitle="Proximity - Entry";
            notificationContent="Entered the region";
            tickerMessage = "Entered the region";
        }else{
            Toast.makeText(getBaseContext(),"Exiting the region"  ,Toast.LENGTH_LONG).show();
            notificationTitle="Proximity - Exit";
            notificationContent="Exited the region";
            tickerMessage = "Exited the region";

        }
       
        Intent notificationIntent = new Intent(getApplicationContext(),NotificationView.class);
        notificationIntent.putExtra("content", notificationContent );
       
        /** This is needed to make this intent different from its previous intents */
        notificationIntent.setData(Uri.parse("tel:/"+ (int)System.currentTimeMillis()));
       
        /** Creating different tasks for each notification. See the flag Intent.FLAG_ACTIVITY_NEW_TASK */
        PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
       
        /** Getting the System service NotificationManager */
        NotificationManager nManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
       
        /** Configuring notification builder to create a notification */
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getApplicationContext())
                            .setWhen(System.currentTimeMillis())
                            .setContentText(notificationContent)
                            .setContentTitle(notificationTitle)
                            .setSmallIcon(R.drawable.ic_launcher)
                            .setAutoCancel(true)
                            .setTicker(tickerMessage)
                            .setContentIntent(pendingIntent);                           
       
       
        /** Creating a notification from the notification builder */
        Notification notification = notificationBuilder.build();
       
        /** Sending the notification to system.
         * The first argument ensures that each notification is having a unique id
         * If two notifications share same notification id, then the last notification replaces the first notification
         * */
        nManager.notify((int)System.currentTimeMillis(), notification);
       
        /** Finishes the execution of this activity */
        finish();
       
       
    }
}

Step 6 :- Run Code.

Step 7 :- Download Code :- https://dl.dropboxusercontent.com/u/109954727/Map/map22.zip

No comments:

Post a Comment