android - 从android插入坐标到mysql

标签 android mysql gps location

我找到了一个关于 GPS 定位服务的教程。 每件事都运转良好。 我要写的下一件事是将坐标从 app 传递到 mysql。 我已经尝试了几个关于 android mysql 的教程,但我不知道如何将它们应用到这段代码中。

我想要实现的目标是 onLocationChanged 将纬度和经度发送到数据库。

有人可以告诉我该怎么做吗?

这是代码:

连接.php

<?php
 define('HOST','localhost');
 define('USER','');
 define('PASS','');
 define('DB','coordinates');

 $con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
 ?>

插入.php

<?php
require_once('connect.php');

if($_SERVER['REQUEST_METHOD']=='POST'){
    $la = $_POST['la_string'];
    $lo = $_POST['lo_string'];   

    $get_result = $con->query("INSERT INTO gps(la,lo) VALUES ('$la','$lo')"); 

    if($get_result === true){
    echo "Successfully Registered";
    }else{
    echo "Not Registered";
    }
}else{
    echo 'error';
}

?>

MainActivity.java

public class MainActivity extends AppCompatActivity {

private Button start, stop, exit;
private TextView data_lo, text_lo, text_la, data_la;
private BroadcastReceiver broadcastReceiver;
private String la_string,lo_string;





@Override
protected void onResume() {
    super.onResume();
    if (broadcastReceiver == null) {
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                data_la.setText("" + intent.getExtras().get("latitude"));
                data_lo.setText("" + intent.getExtras().get("longitude"));

            }
        };
    }

    registerReceiver(broadcastReceiver, new IntentFilter("location_update"));

}




@Override
protected void onDestroy() {
    super.onDestroy();
    if(broadcastReceiver != null){
        unregisterReceiver(broadcastReceiver);
    }
}

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


    start = (Button) findViewById(R.id.start);
    stop = (Button) findViewById(R.id.stop);
    data_la = (TextView) findViewById(R.id.data_la);
    data_lo = (TextView) findViewById(R.id.data_lo);
    text_la = (TextView) findViewById(R.id.text_la);
    text_lo = (TextView) findViewById(R.id.text_lo);
    exit = (Button) findViewById(R.id.exit);



    if(!runtime_permissions())
        enable_buttons();

}

private void enable_buttons() {

    start.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent i =new Intent(getApplicationContext(),GPS_Service.class);
            startService(i);
        }
    });

    stop.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {Intent i = new Intent(getApplicationContext(),GPS_Service.class);
            stopService(i);

        }
    });

}

private boolean runtime_permissions() {
    if(Build.VERSION.SDK_INT >= 23 &&
            ContextCompat.checkSelfPermission
                    (this, Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED &&
            ContextCompat.checkSelfPermission
                    (this, Manifest.permission.ACCESS_COARSE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED){
        requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION},100);

        return true;
    }
    return false;
}


@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(requestCode == 100){
        if( grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED){
            enable_buttons();
        }else {
            runtime_permissions();
        }
    }
}}

GPS_Service.java

public class GPS_Service extends Service {


private LocationListener locationListener;
private LocationManager locationManager;


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

@Override
public void onCreate() {

    locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            Intent i = new Intent("location_update");
            i.putExtra("latitude", location.getLatitude());
            i.putExtra("longitude", location.getLongitude());
            sendBroadcast(i);




        }






        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {

        }

        @Override
        public void onProviderEnabled(String s) {

        }

        @Override
        public void onProviderDisabled(String s) {
            Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(i);
        }
    };

    locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);

    //noinspection MissingPermission
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,3000,0,locationListener);

}

@Override
public void onDestroy() {
    super.onDestroy();
    if(locationManager != null){
        //noinspection MissingPermission
        locationManager.removeUpdates(locationListener);
    }
}}

最佳答案

您必须通过 HttpClient 向您的服务器发出调用,并通过该服务器以 Post 形式发送数据并编码数据。

try{
        String data  = URLEncoder.encode("la_string", "UTF-8") + "=" +
           URLEncoder.encode(data_la.text, "UTF-8");
        data += "&" + URLEncoder.encode("lo_string", "UTF-8") + "=" + 
           URLEncoder.encode(data_lo.text, "UTF-8");

        URL url = new URL(URL);
        URLConnection conn = url.openConnection();

        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());

        wr.write( data );
        wr.flush();

        BufferedReader reader = new BufferedReader(new
           InputStreamReader(conn.getInputStream()));

        StringBuilder sb = new StringBuilder();
        String line = null;

        // Read Server Response if you have something to do with it
        while((line = reader.readLine()) != null) {
           sb.append(line);
           break;
        }

        return sb.toString();
     } catch(Exception e){
        return new String("Exception: " + e.getMessage());
     }

您可以在此处查看完整的示例:https://www.tutorialspoint.com/android/android_php_mysql.htm

关于android - 从android插入坐标到mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44885031/

相关文章:

PHP:我应该同时使用 MYSQLI_CLIENT_COMPRESS 和 MYSQL_CLIENT_SSL 标志吗?

sql - 在 PostgreSQL 中执行多个平均查询

ios - 如何使用PHPhotoKit将CLLocation的GPS信息写入UIImage?

android - 无法对 Android 模拟器进行地理修复

mysql - 如何在 MySQL 中排序子查询?

java - Android sqlite JOIN 查询与 String[] 给出的选择列

android - 如何在非 Android 模块上运行 Android Lint?

android - 如何在另一个 Activity 中重用下载的图像?

android - 在 Recyclerview 中使用 Glide 发出警告

PHP MYSQL 添加单个表中的条目数并以 HTML 形式显示