org.borderstone.tagtags.widgets.BGPSWidget.java Source code

Java tutorial

Introduction

Here is the source code for org.borderstone.tagtags.widgets.BGPSWidget.java

Source

/*   Copyright (c) The Krycklan Catchment Study, 2015
    
   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.
    
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
    
   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.*/

package org.borderstone.tagtags.widgets;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.Toast;
import org.borderstone.bcsv.ColumnProperties;
import org.borderstone.tagtags.R;
import org.borderstone.tagtags.convenience.Constants;
import org.borderstone.tagtags.convenience.widgets.BInfoLabel;
import org.borderstone.tagtags.dialogs.BWarningDialog;
import org.borderstone.tagtags.dialogs.WarningMessageListener;

/**
 * Created by kim on 2015-01-31.
 */

/**
 * This class used to be so pretty... now its not all that pretty anymore.
 * I had to re-implement old code in conjunction with new code and it had to be done quickly.
 * It works, but it is a bit spaghetti.
 */
public class BGPSWidget extends BGeneralWidget
        implements GPSEventListener, LocationListener, View.OnClickListener, View.OnLongClickListener {
    private BInfoLabel lblCoordinates = null;
    private ImageButton btnGPS = null;

    private LocationManager locationManager = null;
    private String provider = null;
    private boolean gps_enabled = false;
    private boolean network_enabled = false;

    private boolean gpsButtonActive = true;

    String coordinates = "";

    public BGPSWidget(Context context, ColumnProperties props, int ROW, int COLUMN) {
        super(context);

        setProperties(ROW, COLUMN, props, context);
        initUI();

        lblCoordinates = new BInfoLabel(context);

        String data = Constants.csv.getValue(row, column);

        if (data.equals("") && props.recurring && props.lastValue != null) {
            data = props.lastValue;
            updateData(data);
        } else if (!data.equals("")) {
            hasSavedData = true;
        }

        lblCoordinates.setText(data);

        if (properties.gpsGlobal) {
            lblCoordinates.setGravity(Gravity.CENTER);
            this.addView(lblCoordinates);
        } else {
            RelativeLayout rl = new RelativeLayout(context);
            RelativeLayout.LayoutParams labelParams = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            RelativeLayout.LayoutParams buttonParams = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

            labelParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
            buttonParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

            btnGPS = new ImageButton(context);
            btnGPS.setBackgroundResource(R.drawable.camera_button);

            btnGPS.setOnClickListener(this);
            btnGPS.setOnLongClickListener(this);

            rl.addView(lblCoordinates, labelParams);
            rl.addView(btnGPS, buttonParams);

            updateButtonDrawable();

            this.addView(rl);
        }
    }

    private void startLocationListener() {
        locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);

        try {
            gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        } catch (Exception ignored) {
        }
        try {
            network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        } catch (Exception ignored) {
        }

        if (!gps_enabled && !network_enabled) {
            Toast.makeText(getContext(), "Location services are not active!", Toast.LENGTH_LONG).show();
        } else {
            if (network_enabled)
                provider = LocationManager.NETWORK_PROVIDER;

            if (gps_enabled)
                provider = LocationManager.GPS_PROVIDER;

            if (checkPermission())
                locationManager.requestLocationUpdates(provider, 0, 0, this);

            tick();
            setGPSButtonEnabled(true);
        }
    }

    private boolean tick = false;

    private void tick() {
        tick = !tick;

        if (tick)
            btnGPS.setImageResource(R.drawable.gps1);
        else
            btnGPS.setImageResource(R.drawable.gps2);
    }

    private void setGPSButtonEnabled(boolean tf) {
        if (!tf) {
            btnGPS.setImageResource(R.drawable.gps_toolbar_disabled);
            gpsButtonActive = false;
        } else {
            gpsButtonActive = true;
        }
    }

    private boolean checkPermission() {
        if (ContextCompat.checkSelfPermission(getContext(),
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(getContext(),
                    "Action failed because you have not given this app permission to access the GPS.",
                    Toast.LENGTH_LONG).show();
            return false;
        }

        return true;
    }

    private void updateButtonDrawable() {
        if (hasSavedData)
            btnGPS.setImageResource(R.drawable.gps_toolbar_disabled);
        else
            btnGPS.setImageResource(R.drawable.gps);

    }

    private void locationChanged(Location location) {
        if (location != null) {
            double latitude = location.getLatitude();
            double longitude = location.getLongitude();
            double accuracy = location.getAccuracy();

            switch (properties.gpsData) {
            case "Lat":
                coordinates = String.valueOf(latitude);
                break;
            case "Long":
                coordinates = String.valueOf(longitude);
                break;
            case "Acc":
                coordinates = String.valueOf(accuracy);
                break;
            case "Coord":
                coordinates = latitude + ", " + longitude;
                break;
            case "All":
                coordinates = latitude + ", " + longitude + " (" + accuracy + ")";
                break;
            }

            setText();
        }
    }

    private void killLocationManager() {
        if (locationManager != null) {
            if (checkPermission())
                locationManager.removeUpdates(this);
            locationManager = null;
        }
    }

    @Override
    public void setEnabled(boolean tf) {
        if (btnGPS != null) {
            btnGPS.setEnabled(tf);
        }

        super.setEnabled(tf);
    }

    @Override
    public void onGlobalLocationChanged(Location location) {
        if (properties.gpsGlobal)
            locationChanged(location);
    }

    @Override
    public void onSaveData() {
        if (properties.gpsGlobal)
            updateData(coordinates);
    }

    @Override
    public void onActivate() {
        if (properties.gpsGlobal)
            lblCoordinates.setText("Searching for location...");
    }

    private void setText() {
        lblCoordinates.setText(coordinates);
    }

    @Override
    public void onClick(View v) {
        if (v.equals(btnGPS) && gpsButtonActive) {
            if (locationManager != null) {
                updateData(coordinates);

                killLocationManager();

                setGPSButtonEnabled(false);
                Toast.makeText(getContext(), "Saved coordinates.", Toast.LENGTH_SHORT).show();
            } else {
                startLocationListener();

                lblCoordinates.setText("...");
            }
        }
    }

    @Override
    public boolean onLongClick(View v) {
        if (v.equals(btnGPS) && !gpsButtonActive) {
            new BWarningDialog(getContext(), "Yes", "No", "Do you really want to look for a new location?",
                    new WarningMessageListener() {
                        @Override
                        public void acceptWarning(boolean tf) {
                            if (tf) {
                                setGPSButtonEnabled(true);
                                startLocationListener();
                            }
                        }
                    });
        }

        return false;
    }

    @Override
    public void onLocationChanged(Location location) {
        locationChanged(location);
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onProviderDisabled(String provider) {
    }
}