谷歌地图未加载,并且我的Android应用程序上始终显示空白屏幕,但每次构建项目时都没有错误。
这是我的代码:
AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.user.smartmotor">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<application
android:allowBackup="true"
android:icon="@drawable/smlogo"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".splash.SplashActivity"
android:label="@string/app_name"
android:launchMode="standard"
android:screenOrientation="portrait"
android:theme="@style/SplashTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyDg_yZowxEhnWBXVEaLanuuPYhhlrJCrxM"/>
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<receiver android:name="com.example.user.smartmotor.IncomingSms">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
</manifest>
我的fragment_location.XML文件:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.user.smartmotor.Fragment.LocatorFragment">
<TableRow android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:name="com.google.android.gms.maps.MapFragment"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</TableRow>
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab_loc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_margin="@dimen/fab_margin"
android:src="@drawable/ic_my_location"
app:backgroundTint="@android:color/holo_red_dark" />
</RelativeLayout>
和我的LocatorFragment.java:
package com.example.user.smartmotor.Fragment;
import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.example.user.smartmotor.GlobalValues;
import com.example.user.smartmotor.MainActivity;
import com.example.user.smartmotor.R;
import com.example.user.smartmotor.SmsSender;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class LocatorFragment extends Fragment implements OnMapReadyCallback {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private MapFragment mapFragment;
private OnFragmentInteractionListener mListener;
private static View view;
private GoogleMap map;
public LocatorFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment LocatorFragment.
*/
// TODO: Rename and change types and number of parameters
public static LocatorFragment newInstance(String param1, String param2) {
LocatorFragment fragment = new LocatorFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final SharedPreferences prefs = getActivity().getSharedPreferences(
GlobalValues.PrefName, Context.MODE_PRIVATE);
try {
view = inflater.inflate(R.layout.fragment_locator, container, false);
mapFragment = (MapFragment) getActivity().getFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
final FloatingActionButton clickButton = (FloatingActionButton) view.findViewById(R.id.fab_loc);
clickButton.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
if(prefs.contains("CurrentMobileNo")){
new AlertDialog.Builder(getContext())
.setTitle("Smart Motor")
.setMessage("Location Request Success! Please wait for the update.")
.setIcon(android.R.drawable.ic_dialog_info)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do things
}
})
.show();
SmsSender.sendSMS(prefs.getString("CurrentMobileNo",""),"!@gps");
}else{
new AlertDialog.Builder(getContext())
.setTitle("Smart Motor")
.setMessage("Cannot Request Location, Please set the mobile number in settings.")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do things
}
})
.show();
}
}
});
} catch (Exception e) {
/* map is already there, just return view as it is */
}
((MainActivity) getActivity())
.setActionBarTitle("Locator");
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
public void onMapReady(GoogleMap googleMap) {
// Getting stored zoom level if exists else return 0
map = googleMap;
CameraUpdate center=
CameraUpdateFactory.newLatLng(new LatLng(14.6717228,
121.0441268));
CameraUpdate zoom=CameraUpdateFactory.zoomTo(10);
googleMap.moveCamera(center);
googleMap.animateCamera(zoom);
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
googleMap.setMyLocationEnabled(true);
final Handler handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
if(GlobalValues.currentLocation != null){
map.clear();
String currentLocation = GlobalValues.currentLocation;
String[] currentLocationSplit = currentLocation.split(",");
MarkerOptions markerOptions = new MarkerOptions();
Double lat = Double.parseDouble(currentLocationSplit[0]);
Double lng = Double.parseDouble(currentLocationSplit[1]);
LatLng latLng = new LatLng(lat,lng);
markerOptions.position(latLng);
markerOptions.title("Current Motor Location.");
map.addMarker(markerOptions);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,15));
GlobalValues.currentLocation = null;
}
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(r, 1000);
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}