Как я могу сделать запрос OkHttp в Сервисе Thread?


У меня проблемы с созданием потока в службе и в потоке я использую OkHttp. При запуске приложения я получаю сообщение об ошибке

E/AndroidRuntime: FATAL EXCEPTION: Thread-468
              java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

Я создал службу и службу, которая создала несколько потоков для извлечения данных из Интернета, а затем поместила их в объект и передала их вызывающей службе. Что я должен делать?
Пожалуйста, укажите, где я был не прав и как это исправить. Мой код выглядит следующим образом: Спасибо.

import android.annotation.SuppressLint;
import android.app.IntentService;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.StrictMode;
import android.os.SystemClock;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MyIntentService extends IntentService {
public static final String ACTION_1 = "MY_ACTION_1";
private SharedPreferences sharedPreferences;
private DonVi donVi = new DonVi();
private List<String> thanhPho = new ArrayList();
private List<JsonDataAPI> jsonDataAPIS = new ArrayList<>();
private TextView textView;
private Handler handler;
int dem = 0;

public MyIntentService() {
    super("MyIntentService");
}

@SuppressLint("HandlerLeak")
@Override
protected void onHandleIntent(Intent intent) {
    //cap quyen truy cap internet dong thoi
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    //tao intent de gui qua broadcast
    Intent broadcastIntent = new Intent();
    broadcastIntent.setAction(MyIntentService.ACTION_1);
    Log.d("Log", "Run");

    //kiem tra ton tai va mo file luu cai dat
    @SuppressLint("SdCardPath")
    File f = new File(
            "/data/data/com.example.ngoc_anh.myapplication2/shared_prefs/myset.xml");
    if (f.exists()) {
        sharedPreferences = getSharedPreferences("myset", MODE_PRIVATE);
        final int soluongtp = sharedPreferences.getInt("soluongtp", 1);
        boolean isload = sharedPreferences.getBoolean("isload", false);
        if (isload) {
            //String data=
        } else {
            //loading data from internet
            for (int i = 1; i <= soluongtp; i++) {
                final int k = i;
                Thread thread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            jsonDataAPIS.add(jsonToObject(GET("https://api.apixu.com/v1/forecast.json?key=c848c4ffa3ef4e5787494645181403&q=" + URLEncoder.encode("nametp" + String.valueOf(k), "UTF-8") + "&days=7")));
                        } catch (UnsupportedEncodingException e)

                        {
                            e.printStackTrace();
                        }

                        Log.d("Log", "thuc hien thread");
                    }
                });
                thread.start();
            }
            Log.d("Log", "Cap xong luon du lieu");
        }
    } else {
        Log.d("Log", "Chua ton tai file setting");
        //lay vi tri hien tai
        String vt = null;
        GPSService mGPSService = new GPSService(getApplicationContext());
        mGPSService.getLocation();
        if (mGPSService.isLocationAvailable == false) {
            Toast.makeText(getApplicationContext(), "Vui lòng bật GPS...", Toast.LENGTH_SHORT).show();
            vt = "Thanh Pho Ho Chi Minh";
        } else {
            double latitude = mGPSService.getLatitude();
            double longitude = mGPSService.getLongitude();
            vt = mGPSService.getLocationAddress();
        }
        //them thanh pho hien tai
        try {
            thanhPho.add(GET("https://api.apixu.com/v1/forecast.json?key=c848c4ffa3ef4e5787494645181403&q=" + URLEncoder.encode(vt, "UTF-8") + "&days=7"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //set don vi
        setDonVi();
        sharedPreferences = getSharedPreferences("myset", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();

        editor.putBoolean("isload", false);
        editor.putBoolean("dvgio", true);
        editor.putBoolean("dvmua", true);
        editor.putBoolean("dvnhietdo", true);
        editor.putBoolean("formattime24", true);
        editor.putInt("formatngay", 0);
        editor.putBoolean("dvtamnhin", true);
        editor.putInt("soluongtp", 1);
        editor.putString("nametp1", vt);
        editor.putString("tp", new Gson().toJson(thanhPho));

        editor.commit();
        //setting lan dau tien
        broadcastIntent.putExtra("Action", 1);
    }
    SystemClock.sleep(2000);
    sendBroadcast(broadcastIntent);
}
public JsonDataAPI jsonToObject(String response) {
    JsonDataAPI jsonDataAPI = new JsonDataAPI();
    ViTri viTri = new ViTri();
    DayCurrent dayCurrent = new DayCurrent();
    Astro astro = new Astro();
    List<DayForecast> dayForecastList = new ArrayList<>();
    JSONObject jsonObject = null;
    try {
        jsonObject = new JSONObject(response);


        String location = jsonObject.getString("location");
        JSONObject jsonObjectLocation = new JSONObject(location);
        viTri.setName(jsonObjectLocation.getString("name"));
        viTri.setCountry(jsonObjectLocation.getString("country"));
        viTri.setTime(jsonObjectLocation.getString("localtime"));
        viTri.setLat(Double.valueOf(jsonObjectLocation.getString("lat")));
        viTri.setLon(Double.valueOf(jsonObjectLocation.getString("lon")));


        String current = jsonObject.getString("current");
        JSONObject jsonObject1Current = new JSONObject(current);
        dayCurrent.setLast_updated(jsonObject1Current.getString("last_updated"));
        dayCurrent.setTemp_c(jsonObject1Current.getDouble("temp_c"));
        dayCurrent.setTemp_f(jsonObject1Current.getDouble("temp_f"));
        int tmp = jsonObject1Current.getInt("is_day");
        if ((tmp > 0)) {
            dayCurrent.setIsday(true);
        } else {
            dayCurrent.setIsday(false);
        }
        JSONObject jsonObject1Condition = new JSONObject(jsonObject1Current.getString("condition"));
        Clouds clouds = new Clouds();
        clouds.setText(jsonObject1Condition.getString("text"));
        clouds.setIcon("http:" + jsonObject1Condition.getString("icon"));
        dayCurrent.setClouds(clouds);
        dayCurrent.setWind_mph(jsonObject1Current.getDouble("wind_mph"));
        dayCurrent.setWind_kph(jsonObject1Current.getDouble("wind_kph"));
        dayCurrent.setPrecip_mm(jsonObject1Current.getDouble("precip_mm"));
        dayCurrent.setPrecip_in(jsonObject1Current.getDouble("precip_in"));
        dayCurrent.setHumidity(jsonObject1Current.getDouble("humidity"));

        String forecast = jsonObject.getString("forecast");
        JSONObject jsonObject1Forecast = new JSONObject(forecast);
        JSONArray jsonArray = jsonObject1Forecast.getJSONArray("forecastday");
        for (int i = 0; i < jsonArray.length(); i++) {
            DayForecast dayForecastTmp = new DayForecast();
            JSONObject jsonObject1List = jsonArray.getJSONObject(i);
            dayForecastTmp.setDate(jsonObject1List.getString("date"));

            JSONObject jsonObject1Day = new JSONObject(jsonObject1List.getString("day"));
            dayForecastTmp.setMaxtemp_c(jsonObject1Day.getDouble("maxtemp_c"));
            dayForecastTmp.setMaxtemp_f(jsonObject1Day.getDouble("maxtemp_f"));
            dayForecastTmp.setMintemp_c(jsonObject1Day.getDouble("mintemp_c"));
            dayForecastTmp.setMintemp_f(jsonObject1Day.getDouble("mintemp_f"));
            dayForecastTmp.setMaxwind_mph(jsonObject1Day.getDouble("maxwind_mph"));
            dayForecastTmp.setMaxwind_kph(jsonObject1Day.getDouble("maxwind_kph"));
            dayForecastTmp.setTotalprecip_mm(jsonObject1Day.getDouble("totalprecip_mm"));
            dayForecastTmp.setTotalprecip_in(jsonObject1Day.getDouble("totalprecip_in"));
            dayForecastTmp.setAvghumididy(jsonObject1Day.getDouble("avghumidity"));
            dayForecastTmp.setAvgvis_km(jsonObject1Day.getDouble("avgvis_km"));
            dayForecastTmp.setAvgvis_m(jsonObject1Day.getDouble("avgvis_miles"));

            Clouds clouds1Tmp = new Clouds();
            JSONObject jsonObject1Clouds = new JSONObject(jsonObject1Day.getString("condition"));
            clouds1Tmp.setText(jsonObject1Clouds.getString("text"));
            clouds1Tmp.setIcon("http:" + jsonObject1Clouds.getString("icon"));
            //Log.d("Log", jsonObject1Clouds.getString("icon"));
            dayForecastTmp.setClouds(clouds1Tmp);
            dayForecastTmp.setUv(jsonObject1Day.getDouble("uv"));
            JSONObject jsonObject1Astro = new JSONObject(jsonObject1List.getString("astro"));
            astro.setSunrise(jsonObject1Astro.getString("sunrise"));
            astro.setSunset(jsonObject1Astro.getString("sunset"));
            astro.setMoonrise(jsonObject1Astro.getString("moonrise"));
            astro.setMoonset(jsonObject1Astro.getString("moonset"));
            dayForecastTmp.setAstro(astro);
            dayForecastList.add(dayForecastTmp);

        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    jsonDataAPI.setViTri(viTri);
    jsonDataAPI.setDayCurrent(dayCurrent);
    jsonDataAPI.setDayForecastList(dayForecastList);
    return jsonDataAPI;
}

public static String GET(String url) {
    String result = null;
    try {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        Response responses = null;

        try {
            responses = client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        result = responses.body().string();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}

private void setDonVi() {
    donVi.setDvGio(true);
    donVi.setDvMua(true);
    donVi.setDvNhietDo(true);
    donVi.setFormatTime24(true);
    donVi.setFormatNgay(0);
    donVi.setDvTamNhin(true);
}

}

0 ответов

Другие вопросы по тегам