gpt4 book ai didi

java - 在Android后台服务中使用php Webservice

转载 作者:太空宇宙 更新时间:2023-11-04 12:33:39 25 4
gpt4 key购买 nike

我有以下代码来调用 webservice 并解析返回的 json 对象,但我需要在后台服务而不是 Activity 中执行它。因为我需要后台服务来推送返回数据的通知(例如新闻和聊天应用程序)。我的问题是我应该对此代码进行哪些修改才能在 android 后台服务中执行?

package com.androidexample.restfulwebservice;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class RestFulWebservice extends Activity {


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.rest_ful_webservice);

final Button GetServerData = (Button) findViewById(R.id.GetServerData);

GetServerData.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {

// WebServer Request URL
String serverURL = "http://androidexample.com/media/webservice/JsonReturn.php";

// Use AsyncTask execute Method To Prevent ANR Problem
new LongOperation().execute(serverURL);
}
});

}


// Class with extends AsyncTask class
private class LongOperation extends AsyncTask<String, Void, Void> {

// Required initialization

private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(RestFulWebservice.this);
String data ="";
TextView uiUpdate = (TextView) findViewById(R.id.output);
TextView jsonParsed = (TextView) findViewById(R.id.jsonParsed);
int sizeData = 0;
EditText serverText = (EditText) findViewById(R.id.serverText);


protected void onPreExecute() {
// NOTE: You can call UI Element here.

//Start Progress Dialog (Message)

Dialog.setMessage("Please wait..");
Dialog.show();

try{
// Set Request parameter
data +="&" + URLEncoder.encode("data", "UTF-8") + "="+serverText.getText();

} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

// Call after onPreExecute method
protected Void doInBackground(String... urls) {

/************ Make Post Call To Web Server ***********/
BufferedReader reader=null;

// Send data
try
{

// Defined URL where to send data
URL url = new URL(urls[0]);

// Send POST data request

URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();

// Get the server response

reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;

// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + "\n");
}

// Append Server Response To Content String
Content = sb.toString();
}
catch(Exception ex)
{
Error = ex.getMessage();
}
finally
{
try
{

reader.close();
}

catch(Exception ex) {}
}

/*****************************************************/
return null;
}

protected void onPostExecute(Void unused) {
// NOTE: You can call UI Element here.

// Close progress dialog
Dialog.dismiss();

if (Error != null) {

uiUpdate.setText("Output : "+Error);

} else {

// Show Response Json On Screen (activity)
uiUpdate.setText( Content );

/****************** Start Parse Response JSON Data *************/

String OutputData = "";
JSONObject jsonResponse;

try {

/****** Creates a new JSONObject with name/value mappings from the JSON string. ********/
jsonResponse = new JSONObject(Content);

/***** Returns the value mapped by name if it exists and is a JSONArray. ***/
/******* Returns null otherwise. *******/
JSONArray jsonMainNode = jsonResponse.optJSONArray("Android");

/*********** Process each JSON Node ************/

int lengthJsonArr = jsonMainNode.length();

for(int i=0; i < lengthJsonArr; i++)
{
/****** Get Object for each JSON node.***********/
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);

/******* Fetch node values **********/
String name = jsonChildNode.optString("name").toString();
String number = jsonChildNode.optString("number").toString();
String date_added = jsonChildNode.optString("date_added").toString();


OutputData += " Name : "+ name +" \n "
+ "Number : "+ number +" \n "
+ "Time : "+ date_added +" \n "
+"--------------------------------------------------\n";

//Log.i("JSON parse", song_name);
}
/****************** End Parse Response JSON Data *************/

//Show Parsed Output on screen (activity)
jsonParsed.setText( OutputData );


} catch (JSONException e) {

e.printStackTrace();
}


}
}

}

}

最佳答案

请完成以下操作

  1. 使用START_STICKY创建服务,以便其在后台运行。由于服务在主线程上运行,因此您还需要线程。请点击服务链接service doc

  2. 您需要将代码移动到线程运行方法内的服务

  3. 注册服务时需要在android list 中进行更改
  4. onclick您需要启动服务,当收到结果时,广播Intent和结果

  5. 然后您需要一个可以从服务接收结果的广播接收器。您还需要在 android maifest 中注册它,或者也可以使用本地广播

  6. 注册您的 Activity 以进行注册并捕获结果,设置为 texy View 。

请检查link用于服务

关于java - 在Android后台服务中使用php Webservice,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37570480/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com