0

我想开始我的异步任务:

package com.androidhive.xmlparsing;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;


public class onoff extends AsyncTask<String, Void, String> {

    private static final int REGISTRATION_TIMEOUT = 3 * 1000;
    private static final int WAIT_TIMEOUT = 30 * 1000;
    private final HttpClient httpclient = new DefaultHttpClient();

    final HttpParams params = httpclient.getParams();
    HttpResponse response;
    private String content =  null;
    private boolean error = false;

    private Context mContext;
    private int NOTIFICATION_ID = 1;
    private Notification mNotification;
    private NotificationManager mNotificationManager;

    public onoff(Context context){

        this.mContext = context;

        //Get the notification manager
        mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);

    }

    protected void onPreExecute() {
        createNotification("Data download is in progress","");
    }

    protected String doInBackground(String... urls) {
       String URL = null; 
       String param1 = null;
       String param2 = null; 
       String param3 = null;
        try {

            //URL passed to the AsyncTask 
            URL = urls[0];
            param1 = urls[1];
            param2 = urls[2];
            param3 = urls[3];
            HttpConnectionParams.setConnectionTimeout(params, REGISTRATION_TIMEOUT);
            HttpConnectionParams.setSoTimeout(params, WAIT_TIMEOUT);
            ConnManagerParams.setTimeout(params, WAIT_TIMEOUT);


            HttpPost httpPost = new HttpPost(URL);

            //Any other parameters you would like to set
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
            nameValuePairs.add(new BasicNameValuePair("token",param1));
            nameValuePairs.add(new BasicNameValuePair("deviceid",param2));
            nameValuePairs.add(new BasicNameValuePair("actionid",param3));
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

            //Response from the Http Request
            response = httpclient.execute(httpPost);

            StatusLine statusLine = response.getStatusLine();
            //Check the Http Request for success
            if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                response.getEntity().writeTo(out);
                out.close();
                content = out.toString();
                Log.d("test", content);
            }
            else{
                //Closes the connection.
                Log.w("HTTP1:",statusLine.getReasonPhrase());
                response.getEntity().getContent().close();
                throw new IOException(statusLine.getReasonPhrase());
            }


        } catch (ClientProtocolException e) {
            Log.w("HTTP2:",e );
            content = e.getMessage();
            error = true;
            cancel(true);
        } catch (IOException e) {
            Log.w("HTTP3:",e );
            content = e.getMessage();
            error = true;
            cancel(true);
        }catch (Exception e) {
            Log.w("HTTP4:",e );
            content = e.getMessage();
            error = true;
            cancel(true);
        }

        return content;
    }

    protected void onCancelled() {
        createNotification("Es ist ein Problem aufgetreten(2)!",content);
    }

    protected void onPostExecute(String content) {
        if (error) {
            createNotification("Es ist ein Problem aufgetreten(1)!",content);
        } else {
            createNotification("Gerät erfolgreich geschaltet(3)!","");
        }
    }

    private void createNotification(String contentTitle, String contentText) {

        //Build the notification using Notification.Builder
        Notification.Builder builder = new Notification.Builder(mContext)
        .setSmallIcon(android.R.drawable.stat_sys_download)
        .setAutoCancel(true)
        .setContentTitle(contentTitle)
        .setContentText(contentText);

        //Get current notification
        mNotification = builder.getNotification();

        //Show the notification
        mNotificationManager.notify(NOTIFICATION_ID, mNotification);
    }

}

在 ListActivity 的 onclicklistener 中:

package com.androidhive.xmlparsing;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class SingleMenuItemActivity  extends Activity {

    // XML node keys
    static final String KEY_NAME = "name";
    static final String KEY_COST = "cost";
    static final String KEY_DESC = "description";
    static final String KEY_ID = "deviceid";
    static final String KEY_texton = "texton";
    static final String KEY_textoff = "textoff";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.single_list_item);

        // getting intent data
        Intent in = getIntent();

        // Get XML values from previous intent
        String name = in.getStringExtra(KEY_NAME);
        String cost = in.getStringExtra(KEY_COST);
        String description = in.getStringExtra(KEY_DESC);
        String deviceid = in.getStringExtra(KEY_ID);
        String on = in.getStringExtra(KEY_texton);
        String off = in.getStringExtra(KEY_textoff);

        // Displaying all values on the screen
        TextView lblName = (TextView) findViewById(R.id.name_label);
        TextView lblCost = (TextView) findViewById(R.id.cost_label);
        TextView lblDesc = (TextView) findViewById(R.id.description_label);
        TextView lblid = (TextView) findViewById(R.id.id_label);
       // TextView lblon = (Button) findViewById(R.id.on);
       // TextView lbloff = (Button) findViewById(R.id.off);
        Button lblon = (Button)findViewById(R.id.on);
        lblon.getText().toString();
        lblon.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    String[] url={"http://url.de/", "url","/" + KEY_ID,"/" + KEY_COST};
                    new onoff(this).execute(url);

                }
                });
        Button lbloff = (Button)findViewById(R.id.off);
        lbloff.getText().toString();
        lbloff.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {

                }
                });



        lblName.setText(name);
        lblCost.setText(cost);
        lblDesc.setText(description);
        lblid.setText(deviceid);
        lblon.setText(on);
        lbloff.setText(off);

    }
}

xml解析器:

package com.androidhive.xmlparsing;

import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.util.Log;

public class XMLParser {

    // constructor
    public XMLParser() {

    }

    /**
     * Getting XML from URL making HTTP request
     * @param url string
     * */
    public String getXmlFromUrl(String url) {
        String xml = null;

        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            xml = EntityUtils.toString(httpEntity);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // return XML
        return xml;
    }

    /**
     * Getting XML DOM element
     * @param XML string
     * */
    public Document getDomElement(String xml){
        Document doc = null;
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {

            DocumentBuilder db = dbf.newDocumentBuilder();

            InputSource is = new InputSource();
                is.setCharacterStream(new StringReader(xml));
                doc = db.parse(is); 

            } catch (ParserConfigurationException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            } catch (SAXException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            } catch (IOException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            }

            return doc;
    }

    /** Getting node value
      * @param elem element
      */
     public final String getElementValue( Node elem ) {
         Node child;
         if( elem != null){
             if (elem.hasChildNodes()){
                 for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
                     if( child.getNodeType() == Node.TEXT_NODE  ){
                         return child.getNodeValue();
                     }
                 }
             }
         }
         return "";
     }

     /**
      * Getting node value
      * @param Element node
      * @param key string
      * */
     public String getValue(Element item, String str) {     
            NodeList n = item.getElementsByTagName(str);        
            return this.getElementValue(n.item(0));
        }
}

但我在 onoff(这个)时出错了?构造函数 onoff 未定义我想在单击按钮时启动 http 请求。有人能帮我吗?

4

1 回答 1

0

new onoff(this)中,this指的是 的实例OnClickListener

改变

new onoff(this).execute(url);

new onoff(SingleMenuItemActivity.this).execute(url);

于 2013-07-04T20:46:20.640 回答