繁体   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