2013-04-09 41 views
5

Tôi đang sử dụng code để làm cho thiết bị Android trở thành máy chủ FTP (Bộ nhớ trong của Android). Tôi nhận được ngoại lệ là os.android.NetworkOnMainThread. Tôi đã cố gắng để đưa mã onStart trong AsyncTask nhưng ứng dụng không bao giờ thực thi và gặp sự cố khi khởi chạy. Bất kỳ trợ giúp nào liên quan đến máy chủ FTP trên Android sẽ tuyệt vời vì tôi không biết làm thế nào để nó hoạt động.Máy chủ FTP Android

Đây là Bộ luật MainActivity

package com.googlecode.simpleftp; 

import java.io.IOException; 
import java.net.ServerSocket; 
import java.net.Socket; 
import java.util.concurrent.ExecutorService; 
import java.util.concurrent.Executors; 

import android.app.Activity; 
import android.app.AlertDialog; 
import android.app.Dialog; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.MenuInflater; 
import android.view.MenuItem; 
import android.widget.TextView; 
import android.widget.Toast; 


public class FTPServer extends Activity { 
    private static int COMMAND_PORT = 2121; 
    static final int DIALOG_ALERT_ID = 0; 
    private static ExecutorService executor = Executors.newCachedThreadPool(); 

/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
} 

@Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
      MenuInflater inflater = getMenuInflater(); 
      inflater.inflate(R.menu.my_menu, menu); 
      return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) {  
      // Handle item selection  
      switch (item.getItemId()) { 
        case R.id.new_game:  
          System.out.println("New game button is pressed!"); 
          //newGame();   
          return true;  
        case R.id.quit:   
          System.out.println("Quit button is pressed!"); 
          showDialog(DIALOG_ALERT_ID);   
          return true;  
        default:   
          return super.onOptionsItemSelected(item); } 
    } 

    @Override 
    protected Dialog onCreateDialog(int id){ 
      AlertDialog.Builder builder = new AlertDialog.Builder(this); 
      builder.setMessage("Are you sure you want to exit?") 
      .setCancelable(false).setPositiveButton("yes", new DialogInterface.OnClickListener(){ 
        @Override 
        public void onClick(DialogInterface dialog, int id){ 
          FTPServer.this.finish(); 
        } 
      }) 
      .setNegativeButton("No", new DialogInterface.OnClickListener() { 
        @Override 
        public void onClick(DialogInterface dialog, int which) { 
          dialog.cancel(); 

        } 
      }); 
      AlertDialog alert = builder.create(); 
      return alert; 
    } 

Đây là mã ServerPI

import java.io.BufferedReader; 
import java.io.File; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.io.PrintWriter; 
import java.net.Socket; 

public class ServerPI implements Runnable{ 
    private Socket clientSocket; 
    private BufferedReader in; 
    private PrintWriter out; 

    private String baseDir; 
    private String relativeDir; 
    private String absoluteDir; 
    private String fileName; 
    private String filePath; 

    public ServerPI(Socket incoming) throws IOException{ 
      this.clientSocket = incoming; 
      in = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream())); 
      out = new PrintWriter(this.clientSocket.getOutputStream(), true); 

      baseDir = new File("").getAbsolutePath(); 

      relativeDir = "/"; 
      absoluteDir = baseDir + relativeDir; 
      fileName = ""; 
      filePath = absoluteDir + "/" + fileName; 
    } 

    private void readCommandLoop() throws IOException { 
      String line = null; 
      reply(220, "Welcome to the SimpleFTP server!"); 
      while((line = in.readLine()) != null){ 
        int replyCode = executeCommand(line.trim()); 
        if(replyCode == 221){ 
          return; 
        } 
      } 
    } 

    private int executeCommand(String trim) { 
      // TODO Auto-generated method stub 
      return 0; 
    } 

    public int reply(int statusCode, String statusMessage){ 
      out.println(statusCode + " " + statusMessage); 
      return statusCode; 
    } 

    @Override 
    public void run(){ 
      try{ 
        this.readCommandLoop(); 
      } catch (IOException e){ 
        e.printStackTrace(); 
      } 
      finally { 
        try { 
          if(in != null){ 
            in.close(); 
            in = null; 
          } 
          if(out != null){ 
            out.close(); 
            out = null; 
          } 
          if (clientSocket != null){ 
            clientSocket.close(); 
            clientSocket = null; 
          } 
        } 
        catch (IOException e){ 
          e.printStackTrace(); 
        } 
      } 
    } 
    } 

Tôi đã đặt mã trong AsyncTask, ở đây nó là

private class LongOperation extends AsyncTask<String, Void, String> { 

     @Override 
     protected String doInBackground(String... params) { 
      ServerSocket s = null; 
    Socket incoming = null; 

    try{ 
      s = new ServerSocket(COMMAND_PORT); 
      String ip = (s.getInetAddress()).getHostAddress(); 
      Context context = this.getApplicationContext(); 
      CharSequence text = ip; 
      int duration = Toast.LENGTH_LONG; 

      Toast toast = Toast.makeText(context, text, duration); 
      Thread.sleep(1000); 
      toast.show(); 
      while(true){ 
        incoming = s.accept(); 
        executor.execute(new ServerPI(incoming)); 
      } 
    } 
    catch(Exception e){ 
      System.out.println(e.toString()); 
      e.printStackTrace(); 
    } 
    finally{ 
      try 
        { 
          if(incoming != null)incoming.close(); 
        } 
        catch(IOException ignore) 
        { 
          //ignore 
        } 

        try 
        { 
          if (s!= null) 
          { 
            s.close(); 
          } 
        } 
        catch(IOException ignore) 
        { 
          //ignore 
        } 
    } 

      return "Executed"; 
     }  

     @Override 
     protected void onPostExecute(String result) {    
     } 

     @Override 
     protected void onPreExecute() { 
     } 

     @Override 
     protected void onProgressUpdate(Void... values) { 
     } 
} 

Iam gọi longOpertation trong phương thức onCreate. Vấn đề mà ứng dụng gặp sự cố khi khởi chạy là gì.

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    setContentView(R.layout.activity_fullscreen); 
      new LongOperation().execute(); 
    } 

Trả lời

1

Sử dụng ứng dụng Swiftp (nguồn mở) làm dịch vụ trong ứng dụng của tôi đã giúp tôi đạt được nhiệm vụ của mình. Cảm ơn mọi người đã giúp đỡ. Dưới đây là link nếu ai đó muốn theo dõi

2

Có thể vì bạn không thiết lập quyền trong tệp kê khai? Bạn đã đặt quyền sử dụng Internet.

Nếu cách này không hiệu quả, vui lòng cho chúng tôi biết dòng nào là trường hợp ngoại lệ.

+0

Đã đặt quyền truy cập internet trong tệp kê khai. –

+0

Trường hợp ngoại lệ xảy ra trong khối catch try đầu tiên, có nghĩa là kết nối socket không bao giờ mở và ip được hiển thị là 0.0.0.0 –

+0

Dường như lệnh của bạn để lấy địa chỉ IP không hoạt động tốt. Tôi đã google và có vẻ như nó luôn luôn trở về 0.0.0.0. Kiểm tra bài đăng này. Bạn đã có câu trả lời về cách lấy địa chỉ ip http://stackoverflow.com/questions/7086734/how-to-get-my-ip-address – Reinherd

0

Vui lòng đăng mã của bạn tại đây.

NetworkOnMainthreadException xảy ra vì bạn có thể chạy Hoạt động liên quan đến mạng trên Giao diện người dùng chính. Bạn nên sử dụng asynctask cho mục đích này

Điều này chỉ được ném cho các ứng dụng nhắm mục tiêu SDK Honeycomb trở lên. Các ứng dụng nhắm mục tiêu các phiên bản SDK trước đó được phép thực hiện kết nối mạng trên các chuỗi sự kiện chính của chúng, nhưng nó không được khuyến khích nhiều.

http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

class TheTask extends AsyncTask<Void,Void,Void> 
{ 
protected void onPreExecute() 
    {   super.onPreExecute(); 
      //display progressdialog. 
    } 

protected void doInBackground(Void ...params)//return result here 
{ 
//http request. do not update ui here 
//call webservice 
//return result here 
return null; 
} 

protected void onPostExecute(Void result)//result of doInBackground is passed a parameter 
{  
    super.onPostExecute(result); 
    //dismiss progressdialog. 
    //update ui using the result returned form doInbackground() 
} 
} 

http://developer.android.com/reference/android/os/AsyncTask.html. Kiểm tra chủ đề dưới tiêu đề 4 bước.

Ví dụ hoạt động của asynctask @To use the tutorial in android 4.0.3 if had to work with AsynxTasc but i still dont work?.

Ở trên thực hiện cuộc gọi webserive trong doInBakckground(). Trả về kết quả và cập nhật ui bằng cách thiết lập kết quả trong textview trong onPostExecute().

+0

Xin cảm ơn, hãy để tôi thử nó –

+1

Vui lòng kiểm tra bản chỉnh sửa của tôi để biết thêm thông tin cập nhật. –

+0

đăng logcat là bạn nhận được bất kỳ ngoại lệ trong logcat – Raghunandan

0

Bạn không thể thực hiện thao tác mạng trong chuỗi chính trong Android 3.0 cao hơn. Sử dụng AsyncTask cho hoạt động mạng này. See this để được giải thích thêm

+0

Tôi đã cố gắng đặt mã trong tác vụ Async nền và được thi hành nó trong phương thức onCreate nhưng ứng dụng bị lỗi khi khởi động. –

+0

Trong trường hợp đó ngoại lệ bạn đang nhận được –

+0

Nó không bao giờ chạy các ứng dụng và do đó không thể cath ngoại lệ. Bạn có thể đăng bất kỳ mẫu làm việc nào của tác vụ Async hay chỉnh sửa mã của tôi ở trên để tôi có thể đi đúng hướng –

1

while(true){ incoming = s.accept(); ...} Bạn không thể đặt điều đó trong OnStart(). Điều đó nên được thực hiện trong một chủ đề. Vì vậy, ServerSocket s = null; nên là một biến của bạn hoạt động.

+0

Làm thế nào tôi nên đặt nó trong một chủ đề riêng biệt hoặc tác vụ Async. Bạn có thể chỉ cho tôi một ví dụ? –

+0

Tôi đã tạo ra một AsyncTask và tất cả các mã bây giờ là trong cơ quan nhiệm vụ đó, tôi đang gọi phương thức thực thi Async Task trong hàm onCreate(), nó có đúng không? Nó đang làm hỏng ứng dụng mà không cần khởi chạy. –

+0

Vui lòng kiểm tra chỉnh sửa của tôi để biết thêm nội dung cập nhật. –

Các vấn đề liên quan