使用服务从文本文件数据发送到服务器 [英] sending data to server from text file using a service

查看:119
本文介绍了使用服务从文本文件数据发送到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从文本文件中使用如下服务code发送数据到服务器。它通过线路发送数据线到服务器。我希望该服务在后台continuously.For本我写的AsyncTask运行。但它发送的所有数据一次,然后停止。

I am sending data from text file to server using service code given below. It sends data line by line to server. I want the service to run in background continuously.For this I have written asyncTask. But it sends all data once and then stops.

public class BackgroundService extends Service
    {
        private static final String TAG = "BackgroundService";
        String line=null;
        Context mContext = null;
        File file;RandomAccessFile in = null;
        StringEntity se ;
        HttpEntity entity=null;
        final static int SERVICE_NAME = 1;
        int WORK_TYPE;
    public BackgroundService()
    {
        //super(TAG);
    }
    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
        Toast.makeText(getApplicationContext(),"in BackgroundService",       Toast.LENGTH_LONG).show();
         mContext = getBaseContext();
         WORK_TYPE = 2;
         new BackgroundTask(mContext).execute();
         return super.onStartCommand(intent, flags, startId);
    }

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

        Context mContext = null;String response;

       public BackgroundTask(Context context)
    {
        mContext = context;
    }

    protected void onPreExecute()
    {
        Toast.makeText(getApplicationContext(),"1", Toast.LENGTH_LONG).show();
    }

    protected Void doInBackground(final String... args)
    {
        switch (WORK_TYPE)
        {
            case 2:
                 File file = new File(Environment.getExternalStorageDirectory(),"/BPCLTracker/gpsdata.txt");
                  int i=0;

                  RandomAccessFile in = null;
            try {
                in = new RandomAccessFile(file, "rw");
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                while ((line = in.readLine()) != null)
                  {
                     String input = line.toString();
                     response = sendDataToServer(input);
                     // JsonUtils.parseServerData(response, hashMapObj);
                  }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
                break;
        }//switch
        return null;
    }//doInBackground

    protected void onPostExecute(final Void unused)
    {
        Toast.makeText(getApplicationContext(),"3", Toast.LENGTH_LONG).show();
        switch (WORK_TYPE)
        {
            case 2:
                if (!"".equalsIgnoreCase(response) && response != null)
                {
                    //DeviceUtils.deviceRegistration(hashMapObj, mContext);   
                    callService(1);
                }
            try {
                if((line = in.readLine()) == null && entity!=null)
                {
                    file.delete();
                    new BackgroundTask(mContext).execute();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
                break;
        }
    }
}

public void callService(int work)
{
    WORK_TYPE = work;
    new BackgroundTask(mContext).execute();
}


public String sendDataToServer(String data)
{
    StringBuffer sb = new StringBuffer("");
    String serverUrl = "http://67.23.166.35:80/android/insert.php" ;
    try
    {
        URL url = new URL(serverUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setConnectTimeout(6 * 10 * 1000);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        conn.setRequestMethod("POST");

        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush();

        // Get the response
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));

        String line = "";
        while ((line = rd.readLine()) != null)
        {
            // Process line...
            sb.append(line);
        }

        wr.close();
        rd.close();
        return sb.toString();
    }
    catch (Exception e)
    {
        Log.d("Exception : ", e.getStackTrace().toString());
    }

    return sb.toString();
}
}

感谢您

推荐答案

我有修改您的code:

I have Modify your code:

查看我所有的code此会由一个给你发送线路一个想法。请不要逻辑其余这种方式。我也删除一些方法。

这还不是全部code,但它会给你的想法。

package com.example.getjson;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class backservice extends Service {

    private static final String TAG = "BackgroundService";
    String line = null;
    Context mContext = null;
    File file;
    RandomAccessFile in = null;
    StringEntity se;
    HttpEntity entity = null;
    final static int SERVICE_NAME = 1;
    int WORK_TYPE;
    String response;
    String input = "";

    public backservice() {
        // super(TAG);
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
        Toast.makeText(getApplicationContext(), "in BackgroundService",
                Toast.LENGTH_LONG).show();
        mContext = getBaseContext();
        WORK_TYPE = 2;
        // new BackgroundTask(mContext).execute();
        switch (WORK_TYPE) {
        case 2:
            File file = new File(Environment.getExternalStorageDirectory(),
                    "/BPCLTracker/gpsdata.txt");
            int i = 0;

            RandomAccessFile in = null;
            try {
                in = new RandomAccessFile(file, "rw");
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                while ((line = in.readLine()) != null) {
                    input = line.toString();
                    // response = sendDataToServer(input);
                    new BackgroundTask(mContext).execute();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            break;
        }
        return super.onStartCommand(intent, flags, startId);
    }

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

        Context mContext = null;

        public BackgroundTask(Context context) {
            mContext = context;
        }

        protected void onPreExecute() {
            Toast.makeText(getApplicationContext(), "1", Toast.LENGTH_LONG)
                    .show();
        }

        protected Void doInBackground(final String... args) {
            response = sendDataToServer(input);
            return null;
        }

        protected void onPostExecute(final Void unused) {

        }
    }

    public void callService(int work) {
        WORK_TYPE = work;
        new BackgroundTask(mContext).execute();
    }

    public String sendDataToServer(String data) {
        StringBuffer sb = new StringBuffer("");
        String serverUrl = "http://67.23.166.35:80/android/insert.php";
        try {
            URL url = new URL(serverUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setConnectTimeout(6 * 10 * 1000);
            conn.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded;charset=UTF-8");
            conn.setRequestMethod("POST");

            OutputStreamWriter wr = new OutputStreamWriter(
                    conn.getOutputStream());
            wr.write(data);
            wr.flush();

            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));

            String line = "";
            while ((line = rd.readLine()) != null) {
                // Process line...
                sb.append(line);
            }

            wr.close();
            rd.close();
            return sb.toString();
        } catch (Exception e) {
            Log.d("Exception : ", e.getStackTrace().toString());
        }

        return sb.toString();
    }
}

这篇关于使用服务从文本文件数据发送到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆