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")
###########################