Java 使用异步任务存储位置数据MYSQL数据库与谷歌播放服务?

Java 使用异步任务存储位置数据MYSQL数据库与谷歌播放服务?,java,android,mysql,google-play-services,mamp,Java,Android,Mysql,Google Play Services,Mamp,因此,基本上我正在尝试将我的位置更新存储在mysql数据库中(external->MAMP),作为两个坐标纬度和经度。因此,由于更新是基于我声明的时间间隔(10000)进行的,所以它应该一直添加到数据库中,直到我单击停止按钮 单击按钮showLocation时调用async类。同时也会触发位置更新 我已经添加了我的代码,没有错误,但是我的信息没有存储到数据库中…有什么想法吗 public class UserLocation extends ActionBarActivity implement

因此,基本上我正在尝试将我的位置更新存储在mysql数据库中(external->MAMP),作为两个坐标纬度和经度。因此,由于更新是基于我声明的时间间隔(10000)进行的,所以它应该一直添加到数据库中,直到我单击停止按钮

单击按钮showLocation时调用async类。同时也会触发位置更新

我已经添加了我的代码,没有错误,但是我的信息没有存储到数据库中…有什么想法吗

public class UserLocation extends ActionBarActivity implements ConnectionCallbacks,
        OnConnectionFailedListener, LocationListener {

    //For Updating the Database with Locations
    private static String url_create_profile = "http://MYIP:8888/android_connect/add_location.php";
    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    //JSON Parser
    JSONParser jsonParser = new JSONParser();
    // Progress Dialog
    private ProgressDialog pDialog;

    // LogCat tag
    private static final String TAG = UserLocation.class.getSimpleName();

    private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;

    private Location mLastLocation;

    // Google client to interact with Google API
    private GoogleApiClient mGoogleApiClient;

    // boolean flag to toggle periodic location updates
    private boolean mRequestingLocationUpdates = false;

    private LocationRequest mLocationRequest;

    // Location updates intervals in sec
    private static int UPDATE_INTERVAL = 10000; // 10 sec
    private static int FATEST_INTERVAL = 5000; // 5 sec
    private static int DISPLACEMENT = 10; // 10 meters

    // UI elements
    private TextView lblLocation;
    private Button btnShowLocation, btnStartLocationUpdates;

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

        lblLocation = (TextView) findViewById(R.id.lblLocation);
        btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
        btnStartLocationUpdates = (Button) findViewById(R.id.btnLocationUpdates);

        // First we need to check availability of play services
        if (checkPlayServices()) {

            // Building the GoogleApi client
            buildGoogleApiClient();

            createLocationRequest();
        }

        // Show location button click listener
        btnShowLocation.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                displayLocation();
            }
        });

        // Toggling the periodic location updates
        btnStartLocationUpdates.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                togglePeriodicLocationUpdates();
                new AddLocation().execute();
            }
        });

    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        checkPlayServices();

        // Resuming the periodic location updates
        if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) {
            startLocationUpdates();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopLocationUpdates();
    }

    /**
     * Method to display the location on UI
     * */
    private void displayLocation() {

        mLastLocation = LocationServices.FusedLocationApi
                .getLastLocation(mGoogleApiClient);

        if (mLastLocation != null) {
            double latitude = mLastLocation.getLatitude();
            double longitude = mLastLocation.getLongitude();

            lblLocation.setText(latitude + ", " + longitude);

        } else {

            lblLocation
                    .setText("(Couldn't get the location. Make sure location is enabled on the device)");
        }
    }

    /**
     * Method to toggle periodic location updates
     * */
    private void togglePeriodicLocationUpdates() {
        if (!mRequestingLocationUpdates) {
            // Changing the button text
            btnStartLocationUpdates
                    .setText(getString(R.string.btn_stop_location_updates));

            mRequestingLocationUpdates = true;

            // Starting the location updates
            startLocationUpdates();

            Log.d(TAG, "Periodic location updates started!");

        } else {
            // Changing the button text
            btnStartLocationUpdates
                    .setText(getString(R.string.btn_start_location_updates));

            mRequestingLocationUpdates = false;

            // Stopping the location updates
            stopLocationUpdates();

            Log.d(TAG, "Periodic location updates stopped!");
        }
    }

    /**
     * Background Async Task to Add Location
     * */
    class AddLocation extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(UserLocation.this);
            pDialog.setMessage("Adding Location..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        /**
         * Creating product
         * */
        protected String doInBackground(String... args) {
            String latitude = lblLocation.getText().toString();
            String longitude = lblLocation.getText().toString();


            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("latitude", latitude));
            params.add(new BasicNameValuePair("longitude", longitude));


            // getting JSON Object
            // Note that create product url accepts POST method
            JSONObject json = jsonParser.makeHttpRequest(url_create_profile,
                    "POST", params);

            // check log cat fro response
            Log.d("Create Response", json.toString());

            // check for success tag
            try {
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // successfully created product
                   // Intent i = new Intent(getApplicationContext(), AllProfile.class);
                    //startActivity(i);
                    Log.d(TAG, "Location Added");
                    // closing this screen
                    //finish();
                } else {
                    // failed to create product
                    Log.d(TAG, "Error in Adding Location");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
            pDialog.dismiss();
        }

    }



    /**
     * Creating google api client object
     * */
    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API).build();
    }

    /**
     * Creating location request object
     * */
    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(UPDATE_INTERVAL);
        mLocationRequest.setFastestInterval(FATEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
    }

    /**
     * Method to verify google play services on the device
     * */
    private boolean checkPlayServices() {
        int resultCode = GooglePlayServicesUtil
                .isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                        PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
                Toast.makeText(getApplicationContext(),
                        "This device is not supported.", Toast.LENGTH_LONG)
                        .show();
                finish();
            }
            return false;
        }
        return true;
    }

    /**
     * Starting the location updates
     * */
    protected void startLocationUpdates() {

        LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);

    }

    /**
     * Stopping location updates
     */
    protected void stopLocationUpdates() {
        LocationServices.FusedLocationApi.removeLocationUpdates(
                mGoogleApiClient, this);
    }

    /**
     * Google api callback methods
     */
    @Override
    public void onConnectionFailed(ConnectionResult result) {
        Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
                + result.getErrorCode());
    }

    @Override
    public void onConnected(Bundle arg0) {

        // Once connected with google api, get the location
        displayLocation();

        if (mRequestingLocationUpdates) {
            startLocationUpdates();
        }
    }

    @Override
    public void onConnectionSuspended(int arg0) {
        mGoogleApiClient.connect();
    }

    @Override
    public void onLocationChanged(Location location) {
        // Assign the new location
        mLastLocation = location;

        Toast.makeText(getApplicationContext(), "Location changed!",
                Toast.LENGTH_SHORT).show();

        // Displaying the new location on UI
        displayLocation();
    }
公共类UserLocation扩展了ActionBarActivity实现了ConnectionCallbacks,
OnConnectionFailedListener,LocationListener{
//用于使用位置更新数据库
私有静态字符串url\u创建\u配置文件=”http://MYIP:8888/android_connect/add_location.php";
//JSON节点名称
私有静态最终字符串标记_SUCCESS=“SUCCESS”;
//JSON解析器
JSONParser JSONParser=新的JSONParser();
//进度对话框
私人对话;
//LogCat标签
私有静态最终字符串标记=UserLocation.class.getSimpleName();
专用最终静态整数播放服务解析请求=1000;
私人场所;
//Google客户端与Google API交互
私人GoogleapClient MGoogleapClient;
//用于切换定期位置更新的布尔标志
私有布尔值mRequestingLocationUpdates=false;
私人位置请求mLocationRequest;
//位置更新间隔(秒)
私有静态整型更新间隔=10000;//10秒
私有静态int-FATEST_间隔=5000;//5秒
专用静态int位移=10;//10米
//UI元素
私有文本视图分配;
私人按钮btnShowLocation,BTNStartLocation更新;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u user\u location);
lblLocation=(TextView)findViewById(R.id.lblLocation);
btnShowLocation=(按钮)findViewById(R.id.btnShowLocation);
btnStartLocationUpdates=(按钮)findViewById(R.id.btnLocationUpdates);
//首先,我们需要检查播放服务的可用性
如果(checkPlayServices()){
//构建GoogleApi客户端
buildGoogleAppClient();
createLocationRequest();
}
//显示位置按钮单击侦听器
btnShowLocation.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
显示位置();
}
});
//切换定期位置更新
btnStartLocationUpdates.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
切换PeriodicLocationUpdates();
新建AddLocation().execute();
}
});
}
@凌驾
受保护的void onStart(){
super.onStart();
if(mGoogleApiClient!=null){
mGoogleApiClient.connect();
}
}
@凌驾
受保护的void onResume(){
super.onResume();
checkPlayServices();
//恢复定期位置更新
if(mgoogleapClient.isConnected()&&mRequestingLocationUpdates){
startLocationUpdates();
}
}
@凌驾
受保护的void onStop(){
super.onStop();
if(mgoogleapClient.isConnected()){
mGoogleApiClient.disconnect();
}
}
@凌驾
受保护的void onPause(){
super.onPause();
stopLocationUpdates();
}
/**
*方法在UI上显示位置
* */
私有void displayLocation(){
mLastLocation=LocationServices.FusedLocationApi
.getLastLocation(MGoogleapClient);
如果(mLastLocation!=null){
双纬度=mLastLocation.getLatitude();
double longitude=mLastLocation.getLongitude();
lblLocation.setText(纬度+“,”+经度);
}否则{
分配
.setText((无法获取位置。请确保设备上已启用位置)”;
}
}
/**
*方法来切换定期位置更新
* */
private void togglePeriodicLocationUpdates(){
如果(!mrequestingLocationUpdate){
//更改按钮文本
BTNStartLocationUpdate
.setText(getString(R.string.btn\u stop\u location\u updates));
mRequestingLocationUpdates=true;
//启动位置更新
startLocationUpdates();
Log.d(标记“定期位置更新已开始!”);
}否则{
//更改按钮文本
BTNStartLocationUpdate
.setText(getString(R.string.btn_start_location_updates));
mRequestingLocationUpdates=false;
//停止位置更新
stopLocationUpdates();
Log.d(标记“定期位置更新已停止!”);
}
}
/**
*要添加位置的后台异步任务
* */
类AddLocation扩展了异步任务{
/**
*在启动后台线程显示进度对话框之前
* */
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
pDialog=newprogressdialog(UserLocation.this);
pDialog.setMessage(“添加位置…”);
pDialog.setUndeterminate(假);
pDialog.setCancelable(真);
pDialog.show();
}
/**
*创造产品
* */
受保护的字符串doInBackground(字符串…args){
字符串纬度=lblLocation.getText().toString();
字符串经度=磅