我正在从我的应用程序打开谷歌地图,以显示从一个点到另一个点的路线,但是当我返回到我的应用程序时,地图不在那里(地图在片段中)。我希望当我回到我的应用程序时,地图仍然存在。
返回时这是我的xml文件:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="185dp"
android:id="@+id/relativeLayout">
<com.google.android.gms.maps.MapView
android:id="@+id/googleMap"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageViewPerfilPersona"
android:src="@drawable/perfil_persona_b"
android:layout_alignParentTop="true"
android:layout_alignRight="@+id/textViewClientName"
android:layout_alignEnd="@+id/textViewClientName"
android:layout_marginTop="120dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="@string/ClientName"
android:id="@+id/textViewClientName"
android:layout_below="@+id/imageViewPerfilPersona"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="@string/TimeLeftRequest"
android:id="@+id/textViewTimeLeft"
android:layout_below="@+id/textViewClientName"
android:layout_centerHorizontal="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageViewCar"
android:src="@drawable/car"
android:paddingRight="5dp"
android:paddingTop="0dp"
android:paddingBottom="0dp"
android:layout_alignTop="@+id/textViewTypeCar"
android:layout_toStartOf="@+id/textViewTypeCar"
android:layout_alignBottom="@+id/textViewTypeCar"
android:layout_toLeftOf="@+id/textViewTypeCar" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="@string/TypeCar"
android:id="@+id/textViewTypeCar"
android:paddingLeft="20dp"
android:layout_marginTop="30dp"
android:layout_below="@+id/textViewTimeLeft"
android:layout_centerHorizontal="true"
android:paddingTop="0dp"
android:paddingRight="10dp"
android:paddingStart="20dp"
android:paddingEnd="10dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="@string/I_need"
android:id="@+id/textViewI_need"
android:layout_below="@+id/textViewTypeCar"
android:layout_alignLeft="@+id/textViewTypeCar"
android:layout_alignStart="@+id/textViewTypeCar"
android:layout_marginTop="15dp"
android:paddingLeft="20dp"
android:paddingRight="10dp"
android:paddingStart="20dp"
android:paddingEnd="10dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageViewTire"
android:layout_below="@+id/imageViewCar"
android:layout_alignLeft="@+id/imageViewCar"
android:layout_alignStart="@+id/imageViewCar"
android:src="@drawable/tire"
android:layout_alignBottom="@+id/textViewI_need"
android:layout_alignRight="@+id/imageViewCar"
android:layout_alignEnd="@+id/imageViewCar"
android:layout_alignTop="@+id/textViewI_need" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="@string/ClientLocation"
android:id="@+id/textViewLocation"
android:layout_below="@+id/textViewI_need"
android:layout_alignLeft="@+id/textViewI_need"
android:layout_alignStart="@+id/textViewI_need"
android:layout_marginTop="15dp"
android:paddingLeft="20dp"
android:paddingRight="10dp"
android:paddingStart="20dp"
android:paddingEnd="10dp"
android:textStyle="bold"
android:onClick="pathGoogle"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageViewLocation"
android:layout_alignLeft="@+id/imageViewTire"
android:layout_alignStart="@+id/imageViewTire"
android:src="@drawable/map"
android:layout_alignBottom="@+id/textViewLocation"
android:layout_alignRight="@+id/imageViewTire"
android:layout_alignEnd="@+id/imageViewTire"
android:layout_alignTop="@+id/textViewLocation" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButtonCheck"
android:src="@drawable/check"
android:background="@null"
android:onClick="requestCheckButton"
android:layout_alignParentBottom="true"
android:layout_alignRight="@+id/textViewTypeCar"
android:layout_alignEnd="@+id/textViewTypeCar"
android:layout_marginBottom="38dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="@string/WaitResponse"
android:id="@+id/textViewResponse"
android:layout_below="@+id/textViewLocation"
android:layout_alignLeft="@+id/textViewLocation"
android:layout_alignStart="@+id/textViewLocation"
android:layout_marginTop="15dp"
android:paddingLeft="20dp"
android:paddingRight="10dp"
android:paddingStart="20dp"
android:paddingEnd="10dp"
android:visibility="invisible"
android:onClick="requestSent"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageViewResponse"
android:layout_alignTop="@+id/textViewResponse"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:src="@drawable/wait_response"
android:layout_alignBottom="@+id/textViewResponse"
android:layout_alignRight="@+id/imageViewLocation"
android:layout_alignEnd="@+id/imageViewLocation"
android:visibility="invisible" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/BeginService"
android:id="@+id/buttonBeginService"
android:layout_alignTop="@+id/imageButtonCheck"
android:layout_centerHorizontal="true"
android:visibility="invisible"
android:onClick="beginService"
android:background="@drawable/button_red"
android:textColor="@color/white"
android:elevation="10px"/>
地图的类是片段:
public class Request extends Fragment implements LocationListener {
private FragmentActivity myContext;
Marker marker;
MapView mapView;
GoogleMap map;
Context ctx;
public static final String ARG_REQUEST = "arg_request";
public Request() {
// Empty constructor required for fragment subclasses
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.request, container, false);
// Gets the MapView from the XML layout and creates it
switch (GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity()) )
{
case ConnectionResult.SUCCESS:
mapView = (MapView) v.findViewById(R.id.googleMap);
mapView.onCreate(savedInstanceState);
// Gets to GoogleMap from the MapView and does initialization stuff
if(mapView!=null)
{
map = mapView.getMap();
map.getUiSettings().setMyLocationButtonEnabled(false);
map.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) myContext.getSystemService(myContext.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);
}
break;
case ConnectionResult.SERVICE_MISSING:
break;
case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:
break;
default:
}
// Updates the location and zoom of the MapView
return v;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Add your menu entries here
inflater.inflate(R.menu.main, menu);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public void onResume() {
mapView.onResume();
super.onResume();
Log.i("onResumeRequest","request");
}
@Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
Log.i("onDestroy Request", "request");
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public void onLocationChanged(Location location) {
if(marker != null){
marker.remove();
}
map.clear();
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
marker = map.addMarker(new MarkerOptions()
.position(latLng));
marker.setPosition(latLng);
marker.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.car_marker));
marker.setTitle("Tu ubicación");
marker.showInfoWindow();
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//center map on marker and zoom
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(latitude, longitude), 15));
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onAttach(Activity activity) {
myContext=(FragmentActivity) activity;
super.onAttach(activity);
}
}
我的主要活动:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private static int RESULT_LOAD_IMG = 1;
String imgDecodableString;
Fragment fragment;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private ImageButton button;
private TextView userNameNavHeader;
private TextView userEmailNavHeader;
private TextView textViewWaitResponse;
private TextView textViewTimeLeft;
private ImageView imageViewWaitResponse;
private Button buttonBService;
private RelativeLayout nav_header;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
private RequestAccepted ra;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
mTitle = mDrawerTitle = getTitle();
fragment = new Request();
Bundle args = new Bundle();
args.putInt(Request.ARG_REQUEST, 0);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// 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();
fillInfo();
}
@Override
public void onResume() {
Toast.makeText(MainActivity.this,"onResumeMainActivity",Toast.LENGTH_SHORT).show();
super.onResume();
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
public void fillInfo(){
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
View header = LayoutInflater.from(this).inflate(R.layout.nav_header_main, null);
navigationView.addHeaderView(header);
navigationView.setNavigationItemSelectedListener(this);
userNameNavHeader = (TextView) header.findViewById(R.id.userNameTextView);
userEmailNavHeader = (TextView) header.findViewById(R.id.userEmailTextView);
userNameNavHeader.setText(ParseUser.getCurrentUser().getString("name"));
userEmailNavHeader.setText(ParseUser.getCurrentUser().getString("email"));
Typeface roboto_regular = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Regular.ttf");
userNameNavHeader.setTypeface(roboto_regular);
userNameNavHeader.setTextSize(16); //32 px
userEmailNavHeader.setTypeface(roboto_regular);
userEmailNavHeader.setTextSize(12); //24 px
}
public boolean onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.main, menu);
//return true;
menu.findItem(R.id.action_settings).setVisible(false);
return super.onCreateOptionsMenu(menu);
}
@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
if (id == R.id.action_settings) {
//Verificar primero si ya se dio click en el boton comenzar servicio (para poderlo cancelar) Falta!!!
//cancelTicket (ParseCloud)
//posteriormente se necesitara hacer un query para poder obtener el ticketId directo de parse
String ticketId = "B61JHphZPs";
Map<String,Object> parameters = new HashMap<String,Object>();
parameters.put("ticketId", ticketId);
ParseCloud.callFunctionInBackground("cancelTicket", parameters, new FunctionCallback<ParseObject>() {
@Override
public void done(ParseObject anwser, ParseException e) {
// TODO Auto-generated method stub
if (e == null) {
Toast.makeText(MainActivity.this, "Servicio cancelado", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, BeginService.class);
startActivity(intent);
} else {
Toast.makeText(MainActivity.this, "Ocurrió un error al cancelar el servicio" + e, Toast.LENGTH_SHORT).show();
Log.i("ERROR",e+"");
}
}
});
}
if(id == R.id.refresh){
Intent i = new Intent(this,MainActivity.class);
startActivity(i);
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
Fragment fragment;
int id = item.getItemId();
if (id == R.id.nav_request) {
setTitle(R.string.TitleRequest);
fragment = new Request();
Bundle args = new Bundle();
args.putInt(Request.ARG_REQUEST, 0);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
}
if (id == R.id.nav_history) {
setTitle(R.string.TitleHistory);
fragment = new History();
Bundle args = new Bundle();
args.putInt(History.ARG_HISTORY, 1);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
}
if (id == R.id.nav_profile) {
setTitle(R.string.TitleProfile);
fragment = new Profile();
Bundle args = new Bundle();
args.putInt(Profile.ARG_PROFILE, 2);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
}
if(id == R.id.nav_sign_out){
SignOutDialog(this);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void loadImagefromGallery(View view) {
// Create intent to Open Image applications like Gallery, Google Photos
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
ImageView imgView = (ImageView) findViewById(R.id.imageViewFotoPerfil);
// Set the Image in ImageView after decoding the String
imgView.setImageBitmap(BitmapFactory
.decodeFile(imgDecodableString));
} else {
Toast.makeText(this, "No has elegido una imagen",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Algo salió mal", Toast.LENGTH_LONG)
.show();
}
}
@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.example.ally.helper/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
@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.example.ally.helper/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
public void openDetails(View view){
Intent intent = new Intent(this,DetailsActivity.class);
startActivity(intent);
}
public void pathGoogle(View view){
setContentView(R.layout.request);
TextView clientLocation = (TextView) findViewById(R.id.textViewLocation);
String map = "http://maps.google.co.in/maps?daddr=" + clientLocation.getText();
//from current location remove saddr=32.5224337,-117.0211995
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse(map));
startActivity(intent);
}
public void requestCheckButton(View view){
button = (ImageButton)findViewById(R.id.imageButtonCheck);
textViewWaitResponse = (TextView) findViewById(R.id.textViewResponse);
imageViewWaitResponse = (ImageView)findViewById(R.id.imageViewResponse);
textViewTimeLeft = (TextView) findViewById(R.id.textViewTimeLeft);
ra = new RequestAccepted(this,button,textViewWaitResponse,
imageViewWaitResponse,textViewTimeLeft);
}
public void requestSent(View view){
textViewWaitResponse = (TextView) findViewById(R.id.textViewResponse);
imageViewWaitResponse = (ImageView)findViewById(R.id.imageViewResponse);
String mens = this.getString(R.string.Location)+" ";
mens += ra.getProgress()+" minutos\n\n\n";
mens += this.getString(R.string.Remember);
final AlertDialog.Builder waitingDialog = new AlertDialog.Builder(this);
waitingDialog.setTitle(this.getString(R.string.ClientWaiting));
waitingDialog.setMessage(mens);
waitingDialog.setPositiveButton(this.getString(R.string.waitingDialogPositiveButton), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
buttonBService=(Button)findViewById(R.id.buttonBeginService);
buttonBService.setVisibility(View.VISIBLE);
imageViewWaitResponse.setVisibility(View.INVISIBLE);
textViewWaitResponse.setVisibility(View.INVISIBLE);
}
});
final AlertDialog dialog = waitingDialog.create();
dialog.show();
}
public void beginService(View view){
//startService (ParseCloud)
//posteriormente se necesitara hacer un query para poder obtener el serviceId directo de parse
String serviceId = "KCHWWxCoNP";
Map<String,Object> parameters = new HashMap<String,Object>();
parameters.put("serviceId", serviceId);
ParseCloud.callFunctionInBackground("startService", parameters, new FunctionCallback<ParseObject>() {
@Override
public void done(ParseObject anwser, ParseException e) {
// TODO Auto-generated method stub
if (e == null) {
Toast.makeText(MainActivity.this, "Servicio comenzado", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, BeginService.class);
startActivity(intent);
} else {
Toast.makeText(MainActivity.this, "Ocurrió un error al comenzar el servicio", Toast.LENGTH_SHORT).show();
}
}
});
}
public void saveProfile(View view){
Toast toast = Toast.makeText(this, "Presionaste guardar perfil", Toast.LENGTH_LONG);
toast.show();
}
// Dialogs
public void SignOutDialog(MainActivity v){
AlertDialog.Builder signOut = new AlertDialog.Builder(this);
signOut.setTitle("");
signOut.setMessage("¿Estás seguro que deseas cerrar sesión?");
signOut.setPositiveButton("Cerrar Sesión", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ParseUser.logOut();
Intent intent = new Intent(MainActivity.this, Login.class);
startActivity(intent);
finish();
}
});
signOut.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "Presionaste Cancelar", Toast.LENGTH_SHORT).show();
}
});
signOut.show();
}
}