5

ファイルとデータをPHPサーバーに送信する必要があります。そのためのスレッドと15分ごとに実行されるサービスを使用しています。ネットワークが利用可能な場合は正常に動作していますが、ネットワークに接続されていない場合はファイルの送信を停止します(ファイルのサイズが比較的大きいです。ログを適用すると、サーバーからの応答がフェッチされていないことがわかりました。また、strukが発生しました。さらに、ファイルを初めて送信しようとすると、Unknownhost例外が送信されます。問題になりますか?助けてください。

コードは次のとおりです:-

public void run(){


    while (keepRunning){
        isRunning = true;

        SystemClock.sleep(900000);



        File tempFile = new File(Environment.getExternalStorageDirectory() + "/Android/data/com.wherephone.helloandroid/log_files/", "barcode_log");
        File tempFile1 = new File(Environment.getExternalStorageDirectory() + "/Android/data/com.wherephone.helloandroid/log_files/", "data_log.txt");


        if(tempFile.exists())
        {           

        Log.d(TAG," in keep running");  

        String[] files =  (new File(Environment.getExternalStorageDirectory() + PATH)).list();

        Log.d(TAG," below file list");  

        SimpleDateFormat df3 = new SimpleDateFormat("yyyyMMdd_HHmmss");
        Date curDate = new Date();
        String s= "data_log";//df3.format(curDate);


        Log.d("log",files[0]);


        File file = new File(Environment.getExternalStorageDirectory() + "/Android/data/com.wherephone.helloandroid/log_files/","barcode_log");

        String new_file_name =s+".txt";
        // File (or directory) with new name
        File file2 = new File(Environment.getExternalStorageDirectory() + "/Android/data/com.wherephone.helloandroid/log_files/",new_file_name);
        // Rename file (or directory)
        if(!tempFile1.exists()){

            boolean success = file.renameTo(file2);
            Log.d(TAG," file name created");


            if (success) {
                // File was not successfully renamed

                Log.d(TAG," file rename success");
            }
            else
            {
                Log.d(TAG," file not rename success");
            }
        } 

        ts.writeBarcodeToFile(" S L", "");
        HttpURLConnection connection = null;
        DataOutputStream outputStream = null;
        DataInputStream inputStream = null;

        String pathToOurFile = Environment.getExternalStorageDirectory() + "/Android/data/com.wherephone.helloandroid/log_files/"+new_file_name;//zipName;
        String urlServer = "http://xyz.com/xyz.php?fname="+s+".txt";
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary =  "V2ymHFg03ehbqgZCaKO6jy";

        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 2*1024*1024;

        FileInputStream fileInputStream=null;

        try
        {


        ts.writeBarcodeToFile(" in try sl", "");
        fileInputStream = new FileInputStream(new File(pathToOurFile) );

        InetAddress iAddr = InetAddress.getByName("http://xyz.com");
        URL url = new URL(urlServer);
        connection = (HttpURLConnection) url.openConnection();

        // Allow Inputs & Outputs
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        // Enable POST method
        connection.setRequestMethod("POST");

        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

        connection.setConnectTimeout(20000);

        outputStream = new DataOutputStream( connection.getOutputStream() );
        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
        outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile +"\"" + lineEnd);
        outputStream.writeBytes(lineEnd);




        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        // Read file
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);

        ts.writeBarcodeToFile("before while sl ", "");
        while (bytesRead > 0)
        {
        outputStream.write(buffer, 0, bufferSize);
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        outputStream.writeBytes(lineEnd);
        outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        ts.writeBarcodeToFile("after while sl ", "");
        // Responses from the server (code and message)

        try{
        int serverResponseCode = connection.getResponseCode();
        String serverResponseMessage = connection.getResponseMessage();
        if(serverResponseCode==200)
        {
            ts.writeBarcodeToFile("in if server response ", "");
            //ts.writeBarcodeToFile("L S", ""); 
            tempFile1.delete();
        }
        else
        {
            ts.writeBarcodeToFile("in else server response ", "");
            ts.writeBarcodeToFile(serverResponseCode+"", "");

        }

        }
        catch(Exception e)
        {
            try{

                outputStream.flush();
                outputStream.close();
                }
                catch(Exception ex)
                {

                }

            ts.writeBarcodeToFile("in url catch response "+e.toString(), "");
            connection.disconnect();

        }

        ts.writeBarcodeToFile("after server  sl ", "");
        fileInputStream.close();
        outputStream.flush();
        outputStream.close();
        ts.writeBarcodeToFile("after close  sl ", "");
        }
        catch (java.net.SocketTimeoutException e) {
            try{
                fileInputStream.close();
            outputStream.flush();
            outputStream.close();
            }
            catch(Exception ex)
            {

            }
            ts.writeBarcodeToFile("in socketex  sl "+e.toString(), "");
            connection.disconnect();
            } 
        catch (java.io.IOException e) 
            {
            try{
                fileInputStream.close();
                outputStream.flush();
                outputStream.close();
                connection.disconnect();
                }
                catch(Exception ex)
                {

                }
            ts.writeBarcodeToFile("in ioex  sl "+e.toString(), "");

            }
        catch (Exception ex)
        {
            try{
                fileInputStream.close();
                outputStream.flush();
                outputStream.close();
                }
                catch(Exception exy)
                {

                }
            ts.writeBarcodeToFile("in catch  sl "+ex.toString(), "");
            connection.disconnect();
        //Exception handling
        }

        //System.gc();
        }




    }
    isRunning = false;
}
4

3 に答える 3

3

この問題は接続に関連しています。Wi-Fiを使用しているときにも確認しましたが、不明なホストの例外エラーは発生していません(デバイスのプラグを抜いた場合を除く)。デバイスが3g/4gのみで動作している場合、不明なホスト例外エラーが発生します。

HTTPを使用して同様のスレッドの履歴書のアップロードを再開するための再開可能なサポートを試すことができますか?

または、独自のプロトコルを作成します(チャンクアップロード)。

于 2013-01-25T06:05:22.270 に答える
1

Androidバージョン3.x以降のネットワーク操作にはAsyncTaskを使用する必要があります。メインスレッドではネットワーク操作を使用できません。ファイルサイズが大きい場合は、サービスでwake_lockを使用する必要があります。ネットワークが利用できない場合は、単にAsyncTaskを閉じて、サービスで言っているように15分後にもう一度確認してください...このコードを使用して、AsyncTaskでネットワークの利用可能性を確認してください

public boolean isOnline() {
   if(MyService.CONTEXT !=null){
       ConnectivityManager cm = (ConnectivityManager) MyService.CONTEXT.getSystemService(Context.CONNECTIVITY_SERVICE);
       NetworkInfo netInfo = cm.getActiveNetworkInfo();
       if (netInfo != null && netInfo.isConnectedOrConnecting()) {
       return true;
       }
    }
  return false 
}
于 2013-01-21T10:21:39.840 に答える
1

Androidの上位バージョンははるかに高速である必要があります。AsynTaskbacgroundメソッドでdoを使用することをお勧めします。

protected class GetTask extends AsyncTask<Void, Void, Integer> {

    protected void onPreExecute() {
        mProgressDialog = ProgressDialog.show(MainActivity.this,
                "Loading", "Please wait");
    }

    @Override
    protected Integer doInBackground(Void... params) {
        // TODO Auto-generated method stub

        /// Do your stuf

        return 0;
    }

    protected void onPostExecute(Integer result) {
        super.onPostExecute(result);

    }
}

私は同じ問題に直面しました。バックグラウンドで使用されていましたが、現在は正常に機能しています

于 2013-01-25T07:49:01.617 に答える