android获取位置并上传

android获取位置并上传

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.provider.Settings;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_LOCATION_PERMISSION = 1;
    private int WatchdogCount=0;


    SimpleDateFormat format1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);


        ////////////////////////////////////////////////////////

        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION_PERMISSION);
        }

        //获取GPS服务
        LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            TextView textView3=findViewById(R.id.textView3);
            textView3.setText("未授权");

            //return;
        }
        Location lc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        updateShow(lc);
        //参数一:使用的定位服务
        //参数二:最短时间触发
        //参数三:最短距离触发
        //参数四:位置改变的监听器
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000L, 8.0f, new LocationListener() {
                    //当位置改变时触发
                    @Override
                    public void onLocationChanged(Location location) {
                        updateShow(location);
                    }

                    //当GPS状态发生变化时触发
                    @Override
                    public void onStatusChanged(String provider, int status, Bundle extras) {
                    }

                    //当LocationProvider可用时
                    @Override
                    public void onProviderEnabled(String provider) {

                    }

                    //当LocationProvider不可用时
                    @Override
                    public void onProviderDisabled(String provider) {
                        updateShow(null);
                    }
                });
        ////////////////////////////////////////////////////////



        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
    }




    //定义一个更新显示的方法
    private void updateShow(Location location) {
        if (location != null) {


            Date indexDate=new Date();
            String indexStrD=format1.format(indexDate);

            StringBuilder sb = new StringBuilder();
            sb.append("当前的位置信息:\n");
            sb.append("精度:" + location.getLongitude() + "\n");
            sb.append("纬度:" + location.getLatitude() + "\n");
            sb.append("高度:" + location.getAltitude() + "\n");
            sb.append("速度:" + location.getSpeed() + "\n");
            sb.append("方向:" + location.getBearing() + "\n");
            sb.append("定位精度:" + location.getAccuracy() + "\n");
            sb.append("当前时间:" + indexStrD + "\n");
            //Toast.makeText(this, sb.toString(), Toast.LENGTH_SHORT).show();
            //Log.e("aaa", sb.toString());

            TextView textView3=findViewById(R.id.textView3);
            textView3.setText(sb.toString());

            
            sendPostWithOkHttp(location.getLongitude(),location.getLatitude());

            if(WatchdogCount>=255){
                WatchdogCount=0;
            }
            WatchdogCount++;

        } else {
            TextView textView3=findViewById(R.id.textView3);
            textView3.setText("当前的位置信息:无");
            //Toast.makeText(this, "当前的位置信息:无", Toast.LENGTH_SHORT).show();
            Log.e("aaa", "当前的位置信息:无");
        }
    }



    



    public void sendPostWithOkHttp(double latitude, double longitude) {
        OkHttpClient client = new OkHttpClient();

        String androidId = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);

        //String tagID="xcvxczvxzvcxz";
        String tagID=""+androidId;
        String name="";
        String biaoduan="";
        String type1="";
        String postData ="tagID="+tagID+"&name="+name+"&biaoduan="+biaoduan+"&type1="+type1+"&longitude="+longitude+"&latitude="+latitude+"&WatchdogCount="+WatchdogCount+"";


        String urlString = "http://117.34.47.236:8080/bjcj/dsfsadfasdsfasdfdsa.action";



        // 创建FormBody添加POST参数
        RequestBody formBody = new FormBody.Builder()
                .add("tagID", tagID)
                .add("name", name)
                .add("biaoduan", biaoduan)
                .add("type1", type1)
                .add("longitude", longitude+"")
                .add("latitude", latitude+"")
                .add("WatchdogCount", WatchdogCount+"")
                .build();

        // 创建Request对象
        Request request = new Request.Builder()
                .url(urlString)
                .post(formBody)
                .build();

        // 执行请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 处理失败情况
                TextView textView6=findViewById(R.id.textView6);
                textView6.setText("处理失败");

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // 处理成功响应
                TextView textView6=findViewById(R.id.textView6);
                textView6.setText("处理成功");

            }
        });
    }







}

 

dependencies中添加:
implementation("com.google.code.gson:gson:2.8.5")
implementation("com.squareup.okhttp3:okhttp:3.10.0")

 

 

 

###########################

posted @ 2024-04-09 23:55  西北逍遥  阅读(36)  评论(0编辑  收藏  举报