简体   繁体   中英

How to make a network call in Android without using an async call?

There is some gaps in android that I do not understand. There is a file I would like to make a network call in. I keep getting an error when I don't make a network call in either a activity or fragment.

        public class Attraction {
            public String name;
            public String description;
            public String longDescription;
            public Uri imageUrl;
            public Uri secondaryImageUrl;
            public LatLng location;
            public String city;

            public Bitmap image;
            public Bitmap secondaryImage;
            public String distance;

            public Attraction() {}

            public Attraction(String name, String description, String longDescription, Uri imageUrl,
                              Uri secondaryImageUrl, LatLng location, String city) {

    //I am looking to replace these variables with information from a website
     this.name = "Hey";//name;
                this.description = description;
                this.longDescription = longDescription;
                this.imageUrl = imageUrl;
                this.secondaryImageUrl = secondaryImageUrl;
                this.location = location;
                this.city = city;
            }
        }

EVEN Better if I can make the network call here:

public class TouristAttractions extends Main2Activity{

    public static final String CITY_SYDNEY = "Sydney";
    public static final String TEST_CITY = CITY_SYDNEY;

    private static final float TRIGGER_RADIUS = 2000; // 2KM
    private static final int TRIGGER_TRANSITION = Geofence.GEOFENCE_TRANSITION_ENTER |
            Geofence.GEOFENCE_TRANSITION_EXIT;
    private static final long EXPIRATION_DURATION = Geofence.NEVER_EXPIRE;

    public static final Map<String, LatLng> CITY_LOCATIONS = new HashMap<String, LatLng>() {{
        put(CITY_SYDNEY, new LatLng(-33.873651, 151.2068896));
    }};

    /**
     * All photos used with permission under the Creative Commons Attribution-ShareAlike License.
     */
    public static final HashMap<String, List<Attraction>> ATTRACTIONS =
            new HashMap<String, List<Attraction>>() {{
//It would be perfect if I can make the network call here
        put(CITY_SYDNEY, new ArrayList<Attraction>() {{
            add(new Attraction(

                    "France",
                    "Lovely place",
                    "You should go",
                    Uri.parse("http://....png"),
                    Uri.parse("http://.....png"),
                    new LatLng(-33.858667, 151.214028),
                    CITY_SYDNEY
            ));

                        }});

    }};

    /**
     * Creates a list of geofences based on the city locations
     */
    public static List<Geofence> getGeofenceList() {
        List<Geofence> geofenceList = new ArrayList<Geofence>();
        for (String city : CITY_LOCATIONS.keySet()) {
            LatLng cityLatLng = CITY_LOCATIONS.get(city);
            geofenceList.add(new Geofence.Builder()
                    .setCircularRegion(cityLatLng.latitude, cityLatLng.longitude, TRIGGER_RADIUS)
                    .setRequestId(city)
                    .setTransitionTypes(TRIGGER_TRANSITION)
                    .setExpirationDuration(EXPIRATION_DURATION)
                    .build());
        }
        return geofenceList;
    }

    public static String getClosestCity(LatLng curLatLng) {
        if (curLatLng == null) {
            // If location is unknown return test city so some data is shown
            return TEST_CITY;
        }

        double minDistance = 0;
        String closestCity = null;
        for (Map.Entry<String, LatLng> entry: CITY_LOCATIONS.entrySet()) {
            double distance = SphericalUtil.computeDistanceBetween(curLatLng, entry.getValue());
            if (minDistance == 0 || distance < minDistance) {
                minDistance = distance;
                closestCity = entry.getKey();
            }
        }
        return closestCity;
    }


}

Simply, you cannot make network operations on UI thread. Why would you like to do it anyway? Network call will block UI message loop - possibly for serveral seconds - this will quickly cause ANR error. There are various APIs that make network operations very easy, ie. OkHTTP .

//It would be perfect if I can make the network call here

then you will have to split this part in async operation, this will require restructuring your code - there is no way around.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM