Tôi quen thuộc với khung công tác Android và Java và muốn tạo một lớp "NetworkHelper" chung để xử lý hầu hết mã mạng cho phép tôi chỉ gọi các trang web từ đó.Chuyển chức năng như một tham số trong java
Tôi đi theo bài viết này từ developer.android.com để tạo ra lớp mạng của tôi: http://developer.android.com/training/basics/network-ops/connecting.html
Code:
package com.example.androidapp;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.util.Log;
/**
* @author tuomas
* This class provides basic helper functions and features for network communication.
*/
public class NetworkHelper
{
private Context mContext;
public NetworkHelper(Context mContext)
{
//get context
this.mContext = mContext;
}
/**
* Checks if the network connection is available.
*/
public boolean checkConnection()
{
//checks if the network connection exists and works as should be
ConnectivityManager connMgr = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
{
//network connection works
Log.v("log", "Network connection works");
return true;
}
else
{
//network connection won't work
Log.v("log", "Network connection won't work");
return false;
}
}
public void downloadUrl(String stringUrl)
{
new DownloadWebpageTask().execute(stringUrl);
}
//actual code to handle download
private class DownloadWebpageTask extends AsyncTask<String, Void, String>
{
@Override
protected String doInBackground(String... urls)
{
// params comes from the execute() call: params[0] is the url.
try {
return downloadUrl(urls[0]);
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
// Given a URL, establishes an HttpUrlConnection and retrieves
// the web page content as a InputStream, which it returns as
// a string.
private String downloadUrl(String myurl) throws IOException
{
InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
int len = 500;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.d("log", "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
return contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
// Reads an InputStream and converts it to a String.
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException
{
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result)
{
//textView.setText(result);
Log.v("log", result);
}
}
}
Trong lớp hoạt động của tôi, tôi sử dụng lớp cách này :
connHelper = new NetworkHelper(this);
...
if (connHelper.checkConnection())
{
//connection ok, download the webpage from provided url
connHelper.downloadUrl(stringUrl);
}
Vấn đề tôi đang gặp phải là bằng cách nào đó tôi phải thực hiện gọi lại cho hoạt động và cần được xác định trong hàm "downloadUrl()". Ví dụ khi tải xuống kết thúc, công khai void "handleWebpage (String dữ liệu)" chức năng trong hoạt động được gọi là với chuỗi nạp như tham số của nó.
Tôi đã làm một số googling và thấy rằng tôi bằng cách nào đó nên sử dụng giao diện để đạt được chức năng này. Sau khi xem xét một số câu hỏi/câu trả lời tương tự như trên stackoverflow, tôi không hiểu nó hoạt động như thế nào và tôi không chắc liệu mình có hiểu được giao diện đúng hay không: How do I pass method as a parameter in Java? Thành thật mà nói, sử dụng các lớp ẩn danh là mới đối với tôi. nên áp dụng các đoạn mã ví dụ trong chuỗi đã đề cập.
Vì vậy, câu hỏi của tôi là làm thế nào tôi có thể vượt qua chức năng gọi lại đến lớp mạng của tôi và gọi nó sau khi tải xuống kết thúc? Trường hợp khai báo giao diện, thực hiện từ khóa, v.v ...? Xin lưu ý rằng tôi mới bắt đầu với Java (có nền tảng lập trình khác mặc dù) vì vậy tôi đánh giá cao một lời giải thích trong suốt :) Cảm ơn bạn!
Cảm ơn, điều này đã giúp tôi giải quyết vấn đề và tôi nghĩ bây giờ tôi đã hiểu các khái niệm cơ bản về giao diện :) – Tumetsu
Thú vị khi xem giao diện đóng một vai trò quan trọng trong lập trình java chung như thế nào. –
Điều này xảy ra trước khi java 8 ... –