Mi sto familiarizzando con il framework Android e Java e ho voluto creare una classe generale "NetworkHelper" che gestisse la maggior parte del codice di rete, permettendomi di chiamare solo pagine web da esso.Passaggio della funzione come parametro in java
Ho seguito questo articolo dal developer.android.com per creare la mia classe di rete: http://developer.android.com/training/basics/network-ops/connecting.html
Codice:
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);
}
}
}
Nella mia classe di attività Io uso la classe in questo modo :
connHelper = new NetworkHelper(this);
...
if (connHelper.checkConnection())
{
//connection ok, download the webpage from provided url
connHelper.downloadUrl(stringUrl);
}
problema che sto avendo è che dovrei in qualche modo fare un callback torna all'attività e dovrebbe essere definibile in "downloadURL) (" la funzione. Ad esempio al termine del download, la funzione "handleWebpage (String data)" pubblica in attività viene chiamata con la stringa caricata come parametro.
Ho fatto qualche ricerca su google e ho scoperto che avrei dovuto utilizzare in qualche modo le interfacce per ottenere questa funzionalità. Dopo aver esaminato alcune domande/risposte StackOverflow simili, non ho funzionato e non sono sicuro di aver compreso correttamente le interfacce: How do I pass method as a parameter in Java? Per essere onesto, l'utilizzo delle classi anonime è nuovo per me e non sono sicuro di dove o come dovrebbe applicare i frammenti di codice di esempio nel thread menzionato.
Quindi la mia domanda è come potrei passare la funzione di callback alla mia classe di rete e chiamarla dopo il download? Dove va la dichiarazione dell'interfaccia, implementa la parola chiave e così via? Nota che sono principiante con Java (ho un altro background di programmazione) quindi apprezzerei una spiegazione completa :) Grazie!
Grazie, questo mi ha aiutato a risolvere il problema e ora penso di capire le basi delle interfacce :) – Tumetsu
Interessante vedere come le interfacce svolgono un ruolo importante nella programmazione Java generale. –
Questo è così prima java 8 ... –