Приложение Google Maps работает на эмуляторе, но не на самом устройстве
Я новый пользователь здесь, и моей репутации недостаточно, чтобы отобразить некоторые изображения моего приложения вместе с моим вопросом, который сделает его более продуманным, поэтому, к сожалению, просто задавая вопрос без каких-либо изображений приложения
Я использую виртуальное устройство google nexus 4..API 18 (android version 4.3) и разрабатываю это приложение, которое может работать на любом устройстве Android с api 11 или 11+ и протестировать это приложение на реальном Android-устройстве ( Samsung galaxy S2 lite), но сталкиваются с некоторыми проблемами, которые
1) всякий раз, когда пользователь вводит любое имя местоположения в текстовое поле редактирования и нажимает кнопку поиска в той же самой активности, маркер рисуется на карте ниже. он работает отлично в виртуальном устройстве каждый раз, но на андроиде устройство в этот момент, когда пользователь нажимает на приложение "Найти", получает сбой.
2) во втором действии здесь я сделал кнопку своего местоположения, когда пользователь нажимает на нее.. он получит координаты gps устройства и обратит геокод и отобразит адрес местоположения в одном из текста редактирования ящики. Это также отлично работает в виртуальном устройстве. Это займет время, чтобы делать все, но в реальном устройстве он не отображает ничего, когда я нажимаю на значок в левом верхнем углу, он показывает поиск с помощью gps, но не отображает ничего почему здесь слишком много времени.
так что это две проблемы, с которыми я сталкиваюсь на устройстве Android, но они отлично работают на виртуальном устройстве.
plzzz помогите мне там, я работаю над своим fyp и повесуюсь здесь
здесь указан код проблемы № 1, следуя
package com.example.citytourguide;
import java.io.IOException;
import java.util.List;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class TourGuide extends FragmentActivity {
GoogleMap googleMap;
Marker mark;
LatLng latLng;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tour_guide);
SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
googleMap = supportMapFragment.getMap();
Button btn_route=(Button) findViewById(R.id.route);
btn_route.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
startActivity(new Intent(getBaseContext(),ShowPath.class));
}
});
// Getting reference to btn_find of the layout activity_main
Button btn_find = (Button) findViewById(R.id.btn_find);
btn_find.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditText loc_name = (EditText) findViewById(R.id.editText1);
String location = loc_name.getText().toString();
if(location.equals("")){
Toast.makeText(getBaseContext(), "Please! Enter Something to Find...", Toast.LENGTH_SHORT).show();
}
else{
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
boolean isWiFi = networkInfo.getType() == ConnectivityManager.TYPE_WIFI;
if (isWiFi==true)
{
new GeocoderTask().execute(location);
}
else {
Toast.makeText(getBaseContext(), "Ooops! Error In Network Connection...", Toast.LENGTH_LONG).show();
}
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.tour_guide, menu);
return true;
}
// An AsyncTask class for accessing the GeoCoding Web Service
protected class GeocoderTask extends AsyncTask<String, Void, List<Address>>{
@Override
protected List<Address> doInBackground(String... locationName) {
// Creating an instance of Geocoder classtry
Geocoder geocoder = new Geocoder(getBaseContext());
List<Address> addresses = null;
try {
// Getting a maximum of 3 Address that matches the input text
addresses = geocoder.getFromLocationName(locationName[0], 3);
} catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
@Override
protected void onPostExecute(List<Address> addresses) {
if(addresses==null || addresses.size()==0){
Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();
}
// Clears all the existing markers on the map
googleMap.clear();
// Adding Markers on Google Map for each matching address
for(int i=0;i<addresses.size();i++){
Address address = (Address) addresses.get(i);
// Creating an instance of GeoPoint, to display in Google Map
latLng = new LatLng(address.getLatitude(), address.getLongitude());
String addressText = String.format("%s, %s", address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",address.getCountryName());
// Showing the marker on the Map
Marker mark =googleMap.addMarker(new MarkerOptions().position(latLng).title(addressText));
mark.showInfoWindow(); // displaying title on the marker
// Locate the first location
if(i==0)
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
}
}
это файл, в котором у меня есть доступ к местоположению
package com.example.citytourguide;
import java.io.IOException;
import java.util.List;
import com.google.android.gms.maps.model.LatLng;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.Toast;
public class ShowPath extends FragmentActivity implements OnClickListener,LocationListener {
AutoCompleteTextView auto_to, auto_from;
Button btn_path, btn_loc;
double lat,lng;
int i = 1 ;
int a = 1 ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_path);
// Getting reference to btn_find of the layout activity_main
auto_from = (AutoCompleteTextView) findViewById(R.id.from);
auto_to = (AutoCompleteTextView) findViewById(R.id.to);
auto_from.setText(null);
auto_to.setText(null);
btn_path=(Button) findViewById(R.id.path);
btn_loc=(Button) findViewById(R.id.btn_loc);
btn_path.setOnClickListener(this);
btn_loc.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.show_path, menu);
MenuItem menuitem=menu.add(Menu.NONE,Menu.FIRST,Menu.NONE,"Save");
menuitem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
return true;
}
public boolean onMenuItemSelected(int featureId,MenuItem item)
{
Toast.makeText(getBaseContext(),"Map has been concluded from " + " to " , Toast.LENGTH_SHORT).show();
return super.onMenuItemSelected(featureId, item);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.path:
String from=auto_from.getText().toString();
String to = auto_to.getText().toString();
if(to.equals("")&& from.equals("")){
Toast.makeText(getBaseContext(), "Please! Enter Start and Destination properly...", Toast.LENGTH_SHORT).show();
}
else{
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
boolean isWiFi = networkInfo.getType() == ConnectivityManager.TYPE_WIFI;
if (isWiFi==true)
{
Intent in = new Intent(ShowPath.this,ShowMap.class);
in.putExtra("Start", from);
in.putExtra("Dest", to);
startActivity(in);
}
else {
Toast.makeText(getBaseContext(), "Ooops! Error In Network Connection...", Toast.LENGTH_LONG).show();
}
}
break;
case R.id.btn_loc:
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
Location location = null ;
if(provider.contains("gps"))
{
// Getting Current Location From GPS
if(auto_from.getText().toString().matches("") && (auto_to.getText().toString().matches(""))){
i=0 ;
}
else if (auto_to.getText().toString().matches("")) {
a=0;
}
location = locationManager.getLastKnownLocation(provider);
if(location!=null)
onLocationChanged(location);
}
else
{
showDialog(0);
}
locationManager.requestLocationUpdates(provider, 1000, 0, this);
//locationManager.requestLocationUpdates(provider, 20000, 0, this);
break;
default:
break;
} //switch statement ends
} // on click func ends
@Override
protected Dialog onCreateDialog(int id){
final String message = "Enable either GPS or any other location"
+ " service to find current location. Click OK to go to"
+ " location services settings to let you do so.";
return new AlertDialog.Builder(this).setMessage(message)
.setTitle("Warning")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int whichButton)
{
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int whichButton)
{
Toast.makeText(getBaseContext(),
"Gps services still disabled", Toast.LENGTH_SHORT).show();
}
}).create();
}
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
lat = location.getLatitude();
lng = location.getLongitude();
LatLng point = new LatLng(lat,lng);
// converting user location to address and assign it to autocomplete text box
new ReverseGeocodingTask(getBaseContext()).execute(point);
}
private class ReverseGeocodingTask extends AsyncTask<LatLng, Void, String>{
Context mContext;
public ReverseGeocodingTask(Context context){
super();
mContext = context;
}
// Finding address using reverse geocoding
@Override
protected String doInBackground(LatLng... params) {
Geocoder geocoder = new Geocoder(mContext);
double latitude = params[0].latitude;
double longitude = params[0].longitude;
List<Address> addresses = null;
String addressText="";
try {
addresses = geocoder.getFromLocation(latitude, longitude,1);
} catch (IOException e) {
e.printStackTrace();
}
if(addresses != null && addresses.size() > 0 ){
Address address = addresses.get(0);
addressText = String.format("%s, %s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getLocality(),
address.getCountryName());
}
return addressText;
}
@Override
protected void onPostExecute(String addressText) {
if(i==0){
auto_from.setText(addressText);
i++ ;
}
else if(a==0){
Log.d("asim","" + a);
auto_to.setText(addressText);
a++;
}
}// post execute finish
}// class reverse geocoding finish
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
Ответы
Ответ 1
Во втором действии реальному устройству требуется много времени, чтобы получить ваше местоположение (2-10 минут) в зависимости от того, находитесь ли вы на открытом воздухе или в доме.
Emulater берет координаты местоположения с помощью элемента управления Emulater в DDMS, поэтому это займет не более нескольких секунд. Попробуйте проверить приложение ur на открытом воздухе.