如果我的 Android 应用程序中有这个后台工作文件,并且它从我的数据库获取数据,我如何将字符串“结果”传递给另一个类?
后台工作人员连接到我的服务器,然后使用 php 连接到数据库。
public class BackgroundWorker extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker (Context ctx) {
context = ctx;
}
@Override
public String doInBackground(String... params) {
String type = params[0];
String specials_url = "";
if(type.equals("venue click")) {
try {
//String user_name = params[1];
URL url = new URL(specials_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
// String post_data = URLEncoder.encode("user_name","UTF-8")+"="+URLEncoder.encode(user_name,"UTF-8");
// bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result="";
String line="";
while((line = bufferedReader.readLine())!= null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Info");
}
@Override
protected void onPostExecute(String result) {
alertDialog.setMessage(result);
alertDialog.show();
// String temp = "login success";
// if (result.equals(temp)) {
// Intent intent = new Intent(context, Register.class);
// context.startActivity(intent);
// }
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
你需要一个倾听者。这将使您能够在以下情况时收到通知:AsyncTask
已经完成了。
通过创建接口来定义侦听器,如下所示:
public interface IListener
{
void onCompletedTask(String result);
}
在任务上存储对侦听器的引用。
private IListener mListener;
// Pass the reference to the constructor.
public BackgroundWorker(IListener listener)
{
mListener = listener;
}
然后你像这样通知听众。
@Override
protected void onPostExecute(String result)
{
mListener.onCompletedTask(result);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)