如何将位置管理器更改为融合位置提供程序api?

问题描述 投票:-1回答:1

我是Android工作室的新手,我正在使用一个需要更多精确定位的应用程序,首先我使用了位置管理器,但它提供的用户位置不太准确,我想将其更改为融合位置api但我很困惑,我不知道如何把它放在我的活动中,我已经在网上搜索但似乎对我没有任何意义。

这是我的主要活动

          public class MainActivity extends AppCompatActivity {

ContactDbAdapter contactDbAdapter;

private GoogleApiClient client;
EditText messageText;
UserDbAdapter userDbAdapter;
Cursor cursor;
TextView locationText;

@Override
public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
    return super.checkUriPermission(uri, pid, uid, modeFlags);
}





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

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);




    userDbAdapter = new UserDbAdapter(this);
    messageText = (EditText) findViewById(R.id.messageText);
    locationText = (TextView) findViewById(R.id.locationTextView);

    try {
        userDbAdapter.open();
    } catch (SQLException error) {
        Log.e("mytag", "Error open userDbAdapter\n");
    }


    contactDbAdapter = new ContactDbAdapter(this);
    try {
        contactDbAdapter.open();
    } catch (SQLException error) {
        Log.e("mytag", "Error open contactDbAdapter\n");
    }
    cursor = contactDbAdapter.getContacts();


    final Button sos = (Button) findViewById(R.id.redbutton);
    final Button finish = (Button) findViewById(R.id.greenbutton);

    final CountDownTimer timer = new CountDownTimer(3999, 100) {
        public void onTick(long millisUntilFinished) {
            sos.setText("" + ((int) (millisUntilFinished) / 1000));
        }
        public void onFinish() {
            sos.setVisibility(View.GONE);
            finish.setVisibility(View.VISIBLE);
            finish.setText("finish");
            SmsManager smsManager = SmsManager.getDefault();
            cursor = contactDbAdapter.getContacts();




            String msg = messageText.getText().toString() + "@" + locationText.getText().toString();
            Log.e("mytag", msg);

            if(cursor.moveToFirst()){
                do{
                    String number=cursor.getString(cursor.getColumnIndex(contactDbAdapter.PHONE_NUM));
                    smsManager.sendTextMessage(number, null, msg, null, null);
                }while(cursor.moveToNext());
            }

        }
    };

    sos.setTag(1);
    sos.setOnClickListener(
            new Button.OnClickListener() {
                public void onClick(View v) {
                    final int status = (Integer) v.getTag();
                    if (status != 1) {
                        sos.setText("sos");
                        sos.setTag(1);
                        timer.cancel();
                    } else {
                        sos.setTag(0);
                        timer.start();
                    }

                }

            }
    );
    finish.setOnClickListener(
            new Button.OnClickListener() {
                public void onClick(View v) {
                    sos.setVisibility(View.VISIBLE);
                    finish.setVisibility(View.GONE);
                    sos.callOnClick();
                }

            }
    );

    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information
    client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();


}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}


@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement

    switch (id) {

        case R.id.contact:
            Intent contactIntent = new Intent(getApplicationContext(), LogInActivity.class);
            startActivity(contactIntent);
            return true;
        case R.id.message:
            Intent messageIntent = new Intent(getApplicationContext(), DisplayMessageActivity.class);
            startActivity(messageIntent);
        default:
            break;
    }

    return super.onOptionsItemSelected(item);
}


@Override
public void onStart() {
    super.onStart();

    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    client.connect();
    Action viewAction = Action.newAction(
            Action.TYPE_VIEW, // TODO: choose an action type.
            "Main Page", // TODO: Define a title for the content shown.
            // TODO: If you have web page content that matches this app activity's content,
            // make sure this auto-generated web page URL is correct.
            // Otherwise, set the URL to null.
            Uri.parse("http://host/path"),
            // TODO: Make sure this auto-generated app deep link URI is correct.
            Uri.parse("android-app://com.cse4471.osu.sos_osu/http/host/path")
    );
    AppIndex.AppIndexApi.start(client, viewAction);
}

@Override
public  void onResume() {
    super.onResume();
    // refresh user message
    cursor = userDbAdapter.getUsers();
    if (cursor.moveToFirst()) {
        messageText.setText(cursor.getString(cursor.getColumnIndex(userDbAdapter.MESSAGE)));
    }
    // Acquire a reference to the system Location Manager
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{
                Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.INTERNET}, 10);
        return;
    }
    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

    LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            // Called when a new location is found by the network location provider.

            locationText.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());



        }

        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

        public void onProviderEnabled(String provider) {
        }
        public void onProviderDisabled(String provider) {


        }
    };

    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 0, locationListener);
    Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    if(loc != null) {

        // messageText.setText("Latitude:" + loc.getLatitude() + ", Longitude:" + loc.getLongitude());
        locationText.setText("Latitude:" + loc.getLatitude() + ", Longitude:" + loc.getLongitude());



    }


}

@Override
public void onStop() {
    super.onStop();

    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    Action viewAction = Action.newAction(
            Action.TYPE_VIEW, // TODO: choose an action type.
            "Main Page", // TODO: Define a title for the content shown.
            // TODO: If you have web page content that matches this app activity's content,
            // make sure this auto-generated web page URL is correct.
            // Otherwise, set the URL to null.
            Uri.parse("http://host/path"),
            // TODO: Make sure this auto-generated app deep link URI is correct.
            Uri.parse("android-app://com.cse4471.osu.sos_osu/http/host/path")
    );
    AppIndex.AppIndexApi.end(client, viewAction);
    client.disconnect();
}

@Override
public void onDestroy() {
    super.onDestroy();
    if (cursor != null) {
        cursor.close();
    }
}

我已经在我的清单中输入了权限,我还在我的gradle文件中添加了'com.google.android.gms:play-services-location:10.0.0'。现在的问题是我想将位置管理器更改为融合位置提供者api。

java android android-studio fusedlocationproviderapi
1个回答
0
投票

由于位置提供程序在最新的播放服务版本中不推荐使用LocationProviderClient,但是如果您想继续使用位置提供程序,那么活动中的位置提供程序的示例工作活动代码

 public class LocationActivity extends AppCompatActivity implements
    GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks,
    LocationListener, GetAddressFromLatLng.LocationAddressResponse {

private LocationRequest mLocationRequest;
public static final int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
private static final int MILLISECONDS_PER_SECOND = 1000;
private FusedLocationProviderApi locationProvider = LocationServices.FusedLocationApi;
private GoogleApiClient mGoogleApiClient;

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // create GoogleClient
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this).build();

    mGoogleApiClient.connect();

}

@Override
public void onConnected(@Nullable Bundle bundle) {
    if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
        requestLocationUpdates();
    }
}

public void requestLocationUpdates() {
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
       // runtime permissions
        return;
    }
    locationProvider.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                       @NonNull int[] grantResults) {
    switch (requestCode) {
        case LOCATION_PERMISSION_REQUEST_CODE:
            if (grantResults.length > 0) {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    requestLocationUpdates();
               }
            }
            break;
    }
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}

@Override
public void onLocationChanged(Location location) {
   // every time location changed it calls itself
}



@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case PLAY_SERVICES_RESOLUTION_REQUEST:
            switch (resultCode) {
                case Activity.RESULT_OK:
                    requestLocationUpdates();
                    break;
                case Activity.RESULT_CANCELED:
                  // Do failure task
                    break;
            }
            break;
    }
}

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

@Override
protected void onResume() {
    super.onResume();
    if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
        requestLocationUpdates();
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.