我正在使用以下code使 android 设备成为 ftp 服务器(Android 内部存储)。我得到了os.android.NetworkOnMainThread
的异常。我试图将 onStart 代码放在AsyncTask
中,但应用程序从未执行并在启动时崩溃。有关 Android 上的 ftp 服务器的任何帮助都会很好,因为我不知道如何使其正常工作。
这里是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.DialogIntece;
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 cl 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 on is pressed!");
//newGame();
return true;
case R.id.quit:
System.out.println("Quit on is pressed!");
swDialog(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 DialogIntece.OnClickListener(){
@Override
public void onClick(DialogIntece dialog, int id){
FTPServer.this.finish();
}
})
.setNegativeButton("No", new DialogIntece.OnClickListener() {
@Override
public void onClick(DialogIntece dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
return alert;
}
HEre 是 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 cl 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 metd 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();
}
}
}
}
我已经把代码在 AsyncTask,这里是
private cl 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.sw();
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 在 onCreate 方法中调用 longOpertation。应用程序在启动时崩溃的问题是什么
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen);
new LongOperation().execute();
}
也许是因为您没有在清单中设置权限?您必须为 Internet 使用设置权限。
如果这不起作用,请告诉我们哪一行是它抛出异常。
while(true){ incoming = s.accept(); ...}
你不能把它放在 OnStart () 中。那应该在一个线程中完成。所以ServerSocket s = null;
应该是你活动的一个变量。
所以我在我的应用程序中使用 Swiftp 应用程序(开源)作为服务,这帮助我完成了我的任务。感谢所有上前帮助的人。如果有人想跟随,这里是link
请在这里发布您的代码。
NetworkOnMainthreadException 发生,因为您可能在主 UI 线程上运行与网络相关的操作。您应该为此使用 asynctask
这仅适用于针对 Honeycomb SDK 或更高版本的应用程序。允许针对早期 SDK 版本的应用程序在其主事件循环线程上进行联网,但非常不鼓励这样做。
http://developer.android.com/reference/android/os/NetworkOnMainThreadException.htmlcl 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 ped a parameter
{
super.onPostExecute(result);
//dismiss progressdialog.
//update ui using the result returned form doInbackground()
}
}
http://developer.android.com/reference/android/os/AsyncTask.html。检查标题4 个步骤下的主题。
asynctask @To use the tutorial in android 4.0.3 if had to work with AsynxTasc but i still dont work?的工作示例。
上面在 doInBakckground()中进行 webserive 调用。返回结果并通过在 onPostExecute()中的 textview 中设置结果来更新 ui。
本站系公益性非盈利分享网址,本文来自用户投稿,不代表边看边学立场,如若转载,请注明出处
评论列表(1条)