Friday, December 19, 2014

Get current location in service even application is not running.

Hello, friends,

Here is sample service class file for getting current location in background service.



import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;

import com.sattracx.android.R;

public class GPSTrackerService extends Service implements LocationListener {

    private final Context mContext;

    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS status
    boolean canGetLocation = false;

    Location mLocation = null; // location
    double mLatitude; // latitude
    double mLongitude; // 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 mLocationManager;
   
    SharedPreferences mSharedPreferences;
    Editor mEditor;
    Resources mResources;

    public GPSTrackerService(Context context) {
        this.mContext = context;
//        getLocation();
    }

    public Location getLocation() {
        try {
            mResources = getApplicationContext().getResources();
            mSharedPreferences = getApplicationContext().getSharedPreferences(mResources.getString(R.string.sp_current_latitude), Context.MODE_PRIVATE);
            mEditor = mSharedPreferences.edit();       
           
            mLocationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            isNetworkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
                showSettingsAlert();
            } else {
                this.canGetLocation = true;
                if (isNetworkEnabled) {
                    mLocationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network Enabled");
                    if (mLocationManager != null) {
                        mLocation = mLocationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (mLocation != null) {
                            mLatitude = mLocation.getLatitude();
                            mLongitude = mLocation.getLongitude();
                            mEditor.putString(mResources.getString(R.string.sp_current_latitude),String.valueOf(mLatitude));
                            mEditor.putString(mResources.getString(R.string.sp_current_longitude),String.valueOf(mLongitude));
                            mEditor.commit();
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (mLocation == null) {
                        mLocationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS", "GPS Enabled");
                        if (mLocationManager != null) {
                            mLocation = mLocationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (mLocation != null) {
                                mLatitude = mLocation.getLatitude();
                                mLongitude = mLocation.getLongitude();
                                mEditor.putString(mResources.getString(R.string.sp_current_latitude),String.valueOf(mLatitude));
                                mEditor.putString(mResources.getString(R.string.sp_current_longitude),String.valueOf(mLongitude));
                                mEditor.commit();
                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return mLocation;
    }

    /**
     * Stop using GPS listener Calling this function will stop using GPS in your
     * app
     * */
    public void stopUsingGPS() {
        if (mLocationManager != null) {
            mLocationManager.removeUpdates(GPSTrackerService.this);
        }
    }

    /**
     * Function to get latitude
     * */
    public double getLatitude() {
        if (mLocation != null) {
            mLatitude = mLocation.getLatitude();
           
        }

        // return latitude
        return mLatitude;
    }

    /**
     * Function to get longitude
     * */
    public double getLongitude() {
        if (mLocation != null) {
            mLongitude = mLocation.getLongitude();
        }

        // return longitude
        return mLongitude;
    }

    /**
     * Function to check GPS/wifi enabled
     *
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog On pressing Settings button will
     * lauch Settings Options
     * */
    public void showSettingsAlert() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
        alertDialog
                .setMessage("Access to my location, Use GPS satellites, use wireless networks in location services. Do you want to go to settings menu?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(
                                Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        mContext.startActivity(intent);
                    }
                });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });

        // Showing Alert Message
        alertDialog.show();
    }

    @Override
    public void onLocationChanged(Location location) {
        this.mLocation = location;
        mEditor.putString(mResources.getString(R.string.sp_current_latitude),String.valueOf(location.getLatitude()));
        mEditor.putString(mResources.getString(R.string.sp_current_longitude),String.valueOf(location.getLongitude()));
        mEditor.commit();
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
   
    @Override
    public void onCreate() {
        getLocation();
        super.onCreate();
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
}


Add below permission in Menifest.xml file

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
.
.
.
<service
            android:name=".GPSTrackerService"
            android:enabled="true"
            android:process=":App_background" >
</service>
.
.

Friday, July 11, 2014

Delete folder or file from SDCard in Android

Hello, friends here is sample code for delete particular file or folder.


public void DeleteFileOrFolder(String mStringPath) {

        File mFileOrDirectory = new File(mStringPath);
       
        if (mFileOrDirectory.isDirectory()){
            for (File mFileChild : mFileOrDirectory.listFiles())
                DeleteFileOrFolder(mFileChild.getPath());
            mFileOrDirectory.delete();
        }else{
            mFileOrDirectory.delete();
        }
    }

Display only MONTH & YEAR field of DatePickerDialog in Fragment.

Hello, friends sometimes we want to display only MONTH & YEAR field in DatePickerDialog but there is no such method in Android.


Here is sample code for this functionality.


import java.util.Calendar;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.View;
import android.widget.DatePicker;

@SuppressLint("ValidFragment")
public class DatePickerForTranscationFragment extends DialogFragment implements OnDateSetListener{
   
    public DatePickerForTranscationFragment()
    {
       
    }
   
     @Override
     public Dialog onCreateDialog(Bundle savedInstanceState) {
            // Use the current date as the default date in the picker
            final Calendar mCalendar = Calendar.getInstance();
            int year = mCalendar.get(Calendar.YEAR);
            int month = mCalendar.get(Calendar.MONTH);
            int day = mCalendar.get(Calendar.DAY_OF_MONTH);

            DatePickerDialog mDatePickerDialog = new DatePickerDialog(getActivity(), this, year, month, day);
           
            try{
            java.lang.reflect.Field[] datePickerDialogFields = mDatePickerDialog.getClass().getDeclaredFields();
            for (java.lang.reflect.Field datePickerDialogField : datePickerDialogFields) {
                if (datePickerDialogField.getName().equals("mDatePicker")) {
                    datePickerDialogField.setAccessible(true);
                    DatePicker datePicker = (DatePicker) datePickerDialogField.get(mDatePickerDialog);
                    java.lang.reflect.Field[] datePickerFields = datePickerDialogField.getType().getDeclaredFields();
                    for (java.lang.reflect.Field datePickerField : datePickerFields) {
                       if ("mDaySpinner".equals(datePickerField.getName())) {
                          datePickerField.setAccessible(true);
                          Object dayPicker = new Object();
                          dayPicker = datePickerField.get(datePicker);
                          ((View) dayPicker).setVisibility(View.GONE);
                       }
                    }
                 }
              }
            }catch(Exception e){
                e.printStackTrace();
            }
            return mDatePickerDialog;
     }


    @Override
    public void onDateSet(DatePicker arg0, int year, int month, int day) {
        //do your code here
    }
}


How to open this FragmentDialog from Fragment.


new DatePickerForTranscationFragment().show(getFragmentManager(), "Select Month & Year");