有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用AlarmManager重复任务?

如何使用AlarmManager在1分钟内重复执行任务

我的应用程序将纬度和经度发送到BD mysql。我需要每1分钟重复一次这个任务

这是我想每分钟重复的代码片段:

public void onLocationChanged(Location location) {
    TextView longitude =  findViewById(R.id.t_longitude);
    TextView latitude =  findViewById(R.id.t_latitude);

    longitude.setText("Longitude: " + location.getLongitude());
    latitude.setText("Latitude: " + location.getLatitude());


    StringRequest request = new StringRequest(Request.Method.POST, insertURL, new com.安卓.volley.Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

        }
    }, new com.安卓.volley.Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> parameters = new HashMap<String, String>();
            parameters.put("latitude",t_latitude.getText().toString());
            parameters.put("longitude",t_longitude.getText().toString());

            return parameters;

        }
    };
    requestQueue.add(request);

}

这是我的活动类,结束活动有需要重复调用的片段代码

package codingwithmitch.com.googlemapsgoogleplaces;

import 安卓.*;
import 安卓.Manifest;
import 安卓.app.AlarmManager;
import 安卓.app.PendingIntent;
import 安卓.content.Context;
import 安卓.content.Intent;
import 安卓.content.SharedPreferences;
import 安卓.content.pm.PackageManager;
import 安卓.graphics.Color;
import 安卓.location.Criteria;
import 安卓.location.Location;
import 安卓.location.LocationListener;
import 安卓.location.LocationManager;
import 安卓.os.Bundle;
import 安卓.os.SystemClock;
import 安卓.support.annotation.NonNull;
import 安卓.support.annotation.Nullable;
import 安卓.support.v4.app.ActivityCompat;
import 安卓.support.v4.content.ContextCompat;
import 安卓.support.v7.app.AlertDialog;
import 安卓.support.v7.app.AppCompatActivity;
import 安卓.util.Log;
import 安卓.view.View;
import 安卓.widget.Button;
import 安卓.widget.EditText;
import 安卓.widget.TextView;
import 安卓.widget.Toast;

import com.安卓.volley.AuthFailureError;
import com.安卓.volley.Request;
import com.安卓.volley.RequestQueue;
import com.安卓.volley.VolleyError;
import com.安卓.volley.toolbox.JsonObjectRequest;
import com.安卓.volley.toolbox.Volley;
import com.google.安卓.gms.common.api.Response;
import com.google.安卓.gms.location.FusedLocationProviderClient;
import com.google.安卓.gms.location.LocationServices;
import com.google.安卓.gms.maps.CameraUpdateFactory;
import com.google.安卓.gms.maps.GoogleMap;
import com.google.安卓.gms.maps.OnMapReadyCallback;
import com.google.安卓.gms.maps.SupportMapFragment;
import com.google.安卓.gms.maps.model.LatLng;
import com.google.安卓.gms.tasks.OnCompleteListener;
import com.google.安卓.gms.tasks.Task;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;



import com.安卓.volley.toolbox.StringRequest;
import java.util.HashMap;




/**
 * Created by User on 10/2/2017.
 */

public class MapActivity extends AppCompatActivity implements OnMapReadyCallback {


    @Override
    public void onMapReady(GoogleMap googleMap) {
        Toast.makeText(this, "Map is Ready", Toast.LENGTH_SHORT).show();
       // Log.d(TAG, "onMapReady: map is ready");
        mMap = googleMap;

        if (mLocationPermissionsGranted) {
            getDeviceLocation();

            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            mMap.setMyLocationEnabled(true);
            mMap.getUiSettings().setMyLocationButtonEnabled(false);

        }
    }

    private static final String TAG = "MapActivity";

    private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
    private static final String COURSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
    private static final float DEFAULT_ZOOM = 15f;

    //vars
    private Boolean mLocationPermissionsGranted = false;
    private GoogleMap mMap;
    private FusedLocationProviderClient mFusedLocationProviderClient;

    private int intervalInMinutes = 1;
    private AlarmManager alarmManager;
    private PendingIntent pendingIntent;

    //--PARAMETROS INICIALES PARA ENVIARL AL PHP Y GUARDAR A LA BD
    RequestQueue requestQueue;

    TextView t_longitude, t_latitude;

    //--

    LocationManager locationManager;
    String mprovider;

    //--ESTABLECEMOS LA URL DEL PHP
    String insertURL = "http://190.147.68.37/app/myapp_save.php";
    //---
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);

        getLocationPermission();

        //--DECLARAMOS LOS COMPONENTES COMO EDITTEXT, TEXTVIEW BOTONES
        t_latitude = findViewById(R.id.t_latitude);
        t_longitude = findViewById(R.id.t_longitude);


        // INICIAMOS LAS INSTRUCCIONES DEL GUARDADO Y ENVIO AL PHP
        requestQueue = Volley.newRequestQueue(getApplicationContext());

        //FIN INSTRUCCIONES PARA EL GUARDADO

    }


    private void getDeviceLocation(){
        Log.d(TAG, "getDeviceLocation: getting the devices current location");

        mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

        try{
            if(mLocationPermissionsGranted){

                final Task location = mFusedLocationProviderClient.getLastLocation();
                location.addOnCompleteListener(new OnCompleteListener() {
                    @Override
                    public void onComplete(@NonNull Task task) {
                        if(task.isSuccessful()){
                            Log.d(TAG, "onComplete: found location!");
                            Location currentLocation = (Location) task.getResult();

                            if (currentLocation != null)
                                onLocationChanged(currentLocation);
                            else
                                Toast.makeText(getBaseContext(), "No Location Provider Found Check Your Code", Toast.LENGTH_SHORT).show();


                            moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()),
                                    DEFAULT_ZOOM);

                        }else{
                            Log.d(TAG, "onComplete: current location is null");
                            Toast.makeText(MapActivity.this, "unable to get current location", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        }catch (SecurityException e){
            Log.e(TAG, "getDeviceLocation: SecurityException: " + e.getMessage() );
        }
    }

    private void moveCamera(LatLng latLng, float zoom){
        Log.d(TAG, "moveCamera: moving the camera to: lat: " + latLng.latitude + ", lng: " + latLng.longitude );
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
    }

    private void initMap(){
        Log.d(TAG, "initMap: initializing map");
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

        mapFragment.getMapAsync(MapActivity.this);
    }

    private void getLocationPermission(){
        Log.d(TAG, "getLocationPermission: getting location permissions");
        String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,
        Manifest.permission.ACCESS_COARSE_LOCATION};

        if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
                FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
            if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
                    COURSE_LOCATION) == PackageManager.PERMISSION_GRANTED){
                mLocationPermissionsGranted = true;
                initMap();
            }else{
                ActivityCompat.requestPermissions(this,
                        permissions,
                        LOCATION_PERMISSION_REQUEST_CODE);
            }
        }else{
            ActivityCompat.requestPermissions(this,
                    permissions,
                    LOCATION_PERMISSION_REQUEST_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        Log.d(TAG, "onRequestPermissionsResult: called.");
        mLocationPermissionsGranted = false;

        switch(requestCode){
            case LOCATION_PERMISSION_REQUEST_CODE:{
                if(grantResults.length > 0){
                    for(int i = 0; i < grantResults.length; i++){
                        if(grantResults[i] != PackageManager.PERMISSION_GRANTED){
                            mLocationPermissionsGranted = false;
                            Log.d(TAG, "onRequestPermissionsResult: permission failed");
                            return;
                        }
                    }
                    Log.d(TAG, "onRequestPermissionsResult: permission granted");
                    mLocationPermissionsGranted = true;
                    //initialize our map
                    initMap();
                }
            }
        }
    }


//i need repeat the below fragmment

    public void onLocationChanged(Location location) {
        TextView longitude =  findViewById(R.id.t_longitude);
        TextView latitude =  findViewById(R.id.t_latitude);

        longitude.setText("Longitude: " + location.getLongitude());
        latitude.setText("Latitude: " + location.getLatitude());


        StringRequest request = new StringRequest(Request.Method.POST, insertURL, new com.安卓.volley.Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

            }
        }, new com.安卓.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> parameters = new HashMap<String, String>();
                parameters.put("latitude",t_latitude.getText().toString());
                parameters.put("longitude",t_longitude.getText().toString());

                return parameters;

            }
        };
        requestQueue.add(request);

    }


}

共 (0) 个答案