这是我的代码。
公共类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从THREAD获取通知然后运行此代码。)仅在通知后执行代码?
编辑:我了解AsyncTask可以让我的生活更轻松。但由于需求描述,我无法使用AsyncTask。所以请为AsyncTask建议我最好的选择。
答案 0 :(得分:0)
这没有任何意义:
startProgress(url);
// ONCE GET NOTIFICATION FROM THREAD then run this code.
...
我假设“一旦从线程获得通知”应该意味着等待为另一个线程。
启动新线程永远没有任何意义,然后立即等待它完成。多线程的重点是两个(或更多)线程可以同时执行不同的事情。
多线程的简单用例如下所示:
startBackgroundThread(...);
doSomethingElseWhileBackgroundThreadIsRunning(...);
waitForResultFromBackgroundThread(...);
如果在后台线程运行时你不打算做其他事情,那么最好简化程序并在一个线程中完成所有工作。
P.S。,如果您想将后台任务中的单个结果传递给前台线程,您可以尝试使用java.util.concurrent.SynchronousQueue
实例。