我刚开始使用Google Places API制作应用。到目前为止,该应用程序允许用户选择一个地方,然后它显示该地点的图像。但是,图像需要几分钟才能加载,有时根本不加载。如果您看到错误,请告诉我。
MainActivity.java
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlacePicker;
import java.util.concurrent.ExecutionException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainActivity extends AppCompatActivity {
private int PLACE_PICKER_REQUEST = 1;
private TextView tvName;
private TextView tvAddress;
private TextView tvAttributions;
private TextView price;
private TextView phone;
private TextView rating;
TextView id;
ImageView downloadedImg;
CharSequence placeID;
String photoReference;
public void logStuff (){
//
ImageDownloader task = new ImageDownloader();
Bitmap myImage;
try {
myImage = task.execute("https://maps.googleapis.com/maps/api/place/photo?maxwidth=500&maxheight=500&photoreference=" + photoReference + "&key=APIKEY").get();
downloadedImg.setImageBitmap(myImage);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Log.i("button", "tapped");
Log.i("imageurl", (String) placeID);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvName = (TextView) findViewById(R.id.name);
tvAddress = (TextView) findViewById(R.id.address);
tvAttributions = (TextView) findViewById(R.id.attributions);
price = (TextView) findViewById(R.id.price);
phone = (TextView) findViewById(R.id.phone);
rating = (TextView) findViewById(R.id.rating);
id = (TextView) findViewById(R.id.placeId);
downloadedImg = (ImageView) findViewById(R.id.imageView);
Toolbar toolBar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolBar);
}
public void onPickButtonClick(View v) {
// Construct an intent for the place picker
try {
PlacePicker.IntentBuilder intentBuilder =
new PlacePicker.IntentBuilder();
Intent intent = intentBuilder.build(this);
// Start the intent by requesting a result,
// identified by a request code.
startActivityForResult(intent, PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
@Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST
&& resultCode == Activity.RESULT_OK) {
// The user has selected a place. Extract the name and address.
final Place place = PlacePicker.getPlace(data, this);
final CharSequence name = place.getName();
final CharSequence address = place.getAddress();
final int priceLevel = place.getPriceLevel();
final CharSequence phoneNum = place.getPhoneNumber();
final float rate = place.getRating();
placeID = place.getId();
logStuff();
DownloadTask task = new DownloadTask();
String result = null;
try {
result = task.execute("https://maps.googleapis.com/maps/api/place/details/json?placeid=" + placeID + "&key=APIKEY").get();
Pattern p = Pattern.compile("photo_reference\" : \"(.*?)\"");
Matcher m = p.matcher(result);
while (m.find()) {
photoReference = m.group(1);
Log.i("PLACE", photoReference);
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Log.i("Contents Of URL", result);
String attributions = PlacePicker.getAttributions(data);
if (attributions == null) {
attributions = "";
}
tvName.setText(name);
tvAddress.setText(address);
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
ImageDownloader.java
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class ImageDownloader extends AsyncTask<String, Void, Bitmap> {
@Override
protected Bitmap doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream inputStream = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(inputStream);
return myBitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
DownloadTask.java
import android.os.AsyncTask;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class DownloadTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection)url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
}
catch(Exception e) {
e.printStackTrace();
return "Failed";
}
}
activity_main.xml中
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".PlacePickerActivity">
<!--including the toobar-->
<include layout="@layout/toolbar" />
<TextView
android:id="@+id/name"
android:gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/attributions"
android:layout_alignEnd="@+id/attributions"
android:layout_below="@+id/toolbar"
android:layout_margin="10dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:id="@+id/address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_below="@+id/name"
android:layout_margin="10dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:id="@+id/attributions"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:text="attributions"/>
<Button
android:layout_width="350dp"
android:layout_height="75dp"
android:onClick="onPickButtonClick"
android:text="Find a location"
android:id="@+id/button"
android:textSize="30dp"
android:background="#ebb70d"
android:layout_above="@+id/attributions"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Rating:"
android:id="@+id/rating"
android:layout_alignBaseline="@+id/phone"
android:layout_alignBottom="@+id/phone"
android:layout_alignStart="@+id/phone" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Phone"
android:id="@+id/phone"
android:layout_below="@+id/address"
android:layout_centerHorizontal="true"
android:layout_marginTop="94dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Price"
android:id="@+id/price"
android:layout_below="@+id/phone"
android:layout_centerHorizontal="true"
android:layout_marginTop="74dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="place Id"
android:id="@+id/placeId"
android:layout_below="@+id/price"
android:layout_centerHorizontal="true"
android:layout_marginTop="46dp" />
<ImageView
android:layout_width="500dp"
android:layout_height="500dp"
android:id="@+id/imageView"
android:layout_above="@+id/rating"
android:layout_alignTop="@+id/name"
android:layout_alignStart="@+id/button"
android:layout_alignEnd="@+id/button"
android:maxHeight="500dp"
android:maxWidth="500dp" />
</RelativeLayout>
注意:如果您想测试此项,则需要输入自己的api密钥