簡體   English   中英

當工作線程在android中完成其工作時如何從工作線程向主線程獲取通知

[英]How to get notification from worker thread to main thread when worker thread done with its work in android

這是我的代碼。

公共類 MainActivity 擴展 AppCompatActivity {

    private ListView listView;

    // URL to get contacts JSON
    private static String url = "example.com";

    // JSON Node names
    private static final String TAG_DEVICES = "devices";
    private static final String TAG_TYPE = "type";
    private static final String TAG_NAME = "name";
    private static final String TAG_MODEL = "model";

    // contacts JSONArray
    JSONArray devices = null;
    String jsonStr= null;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.devices);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        /*
        List<Device> devices = new ArrayList<>();

        Device device1 = new Device("tv", "la22c450e1", "samsung");
        Device device2 = new Device("washing machine", "lg34gfer", "lg");
        Device device3 = new Device("monitor", "dlrtio78", "dell");
        Device device4 = new Device("tv", "sie45vgt", "sansui");
        devices.add(device1);
        devices.add(device2);
        devices.add(device3);
        devices.add(device4);
    */


        List<Device> deviceList = new ArrayList<>();
        String jsonStr = null;

        startProgress(url);

        // ONCE GET NOTIFICATION FROM THREAD then run this code.

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                devices = jsonObj.getJSONArray(TAG_DEVICES);

                // looping through All Contacts
                for (int i = 0; i < devices.length(); i++) {
                    JSONObject c = devices.getJSONObject(i);
                    String name = c.getString(TAG_NAME);
                    String model = c.getString(TAG_MODEL);
                    String type = c.getString(TAG_TYPE);
                    Device device = new Device(type, model, name);

                    // adding device to device list
                    deviceList.add(device);

                }
                DeviceAdapter adapter = new DeviceAdapter(getApplicationContext(), deviceList);
                listView.setAdapter(adapter);


            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }
    }

    private void startProgress(final String url) {
        // do something long
        Runnable runnable = new Runnable() {
            @Override
            public void run() {

                try{
                    jsonStr = FetchData(url);
                }
                catch(IOException ie) {
                    ie.printStackTrace();
                }


            }
        };
        new Thread(runnable).start();
    }

    private String FetchData(String url) throws IOException {
        URL obj = new URL(url);
        StringBuffer stringBuffer = null;
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        //con.setRequestProperty("User-Agent", USER_AGENT);
        int responseCode = con.getResponseCode();
        System.out.println("GET Response Code :: " + responseCode);
        if (responseCode == HttpURLConnection.HTTP_OK) { // success
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    con.getInputStream()));
            String inputLine;
            stringBuffer = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                stringBuffer.append(inputLine);
            }
            in.close();

            // print result
            System.out.println(stringBuffer.toString());
        } else {
            System.out.println("GET request not worked");
        }


        return stringBuffer.toString();

    }
}

我應該如何從工作線程獲取通知(// ONCE GET NOTIFICATION FROM THREAD 然后運行此代碼。)僅在通知后才執行代碼?

編輯:我知道 AsyncTask 可以讓我的生活變得輕松。 但是由於需求描述,我不能使用 AsyncTask。 所以請為我推薦 AsyncTask 的最佳替代方案。

這沒有任何意義:

startProgress(url);
// ONCE GET NOTIFICATION FROM THREAD then run this code.
...

我假設“一旦從線程獲得通知”應該意味着等待另一個線程。

啟動一個新線程,然后立即等待它完成是沒有任何意義的。 多線程的整點是兩個(或多個)線程可以在同一時間做不同的事情。

多線程的一個簡單用例如下所示:

startBackgroundThread(...);
doSomethingElseWhileBackgroundThreadIsRunning(...);
waitForResultFromBackgroundThread(...);

如果您不打算在后台線程運行時做其他事情,那么最好簡化程序並在一個線程中完成所有工作。


PS,如果您想將后台任務的單個結果傳送到前台線程,您可以嘗試使用java.util.concurrent.SynchronousQueue實例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM