android app从sdcard中选择一个文件并使用socket上传到服务器

时间:2015-05-01 09:44:29

标签: java android android-studio

我正在尝试开发一个可以将文件从手机上传到我的笔记本电脑的Android应用程序。我有两个活动:

  1. SimpleClientActivity
  2. 文件选择器活动
  3. 我正在尝试浏览Filechooser活动中的文件,并通过putExtra和getExtra传递文件目录,但无法上传。但是,如果我对文件目录进行硬编码,它将成功上传文件。

    这是代码。由于我是初学者,请详细说明你的答案。

    简单客户活动

    public class SlimpleTextClientActivity extends Activity {
    
    public Socket client;
    public PrintWriter printwriter;
    public EditText textField;
    public Button button1,button2;
    public String messsage;
    public  String file_path;
    public int count=1;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_slimple_text_client);
    
        textField = (EditText) findViewById(R.id.editText1); // reference to the text field
        button1 = (Button) findViewById(R.id.button1); // reference to the filechoosing button
        button2 = (Button) findViewById(R.id.button2);//reference to send button
        // Button press event listener
        button1.setOnClickListener(new View.OnClickListener() {
    
           public void onClick(View v) {
    
               Intent i = new Intent(SlimpleTextClientActivity.this, FileChooser.class);
               startActivity(i);
               Intent intent=getIntent();
               String directory1;
               Bundle b = getIntent().getExtras();
               try {
                   directory1 = b.getString("directory");
                   file_path = directory1;
               } catch (Exception e) {
    
                   textField.setText(e.getMessage());
                   directory1="returned nothon";
               }
    
               if (file_path == null) {
                   file_path = "no file choosen";
               }
    
              textField.setText(directory1);
           }
                                   }
    
        );
       button2.setOnClickListener(new View.OnClickListener() {
    
       public void onClick(View v) {
    
          SendMessage sendMessageTask = new SendMessage();
          sendMessageTask.execute();
    
    
       }
       }
        );
    
    
    }
    private class SendMessage extends AsyncTask<Void, Void, Void> {
        private FileInputStream fileInputStream;
        private BufferedInputStream bufferedInputStream;
        private OutputStream outputStream;
        private Button button;
    
    
        @Override
        protected Void doInBackground(Void... params) {
    
            Socket socket;
            try
            {int count=0;
                socket = new Socket("192.168.137.1", 4444);
                if(!socket.isConnected())
                    textField.setText("Socket Connection Not established");
                else
                    System.out.println("Socket Connection established : "+socket.getInetAddress()); File myfile = new File(file_path);
       //local file path.
                if(!myfile.exists())
                    System.out.println("File Not Existing.");
                else
                    System.out.println("File Existing.");
    
                byte[] byteArray = new byte[100];
    
                FileInputStream fis = new FileInputStream(myfile);
                BufferedInputStream bis = new BufferedInputStream(fis);
                OutputStream os = socket.getOutputStream();
                int trxBytes =0;
                while((trxBytes = bis.read(byteArray, 0, byteArray.length)) !=-1)
                {
                    os.write(byteArray, 0, byteArray.length);
                    System.out.println("Transfering bytes : "+trxBytes );
                }
                os.flush();
                bis.close();
                socket.close();
    
                System.out.println("File Transfered...");
            }
            catch(Exception e)
            {
                System.out.println("Client Exception : "+e.getMessage());
            }
            return null;
        }
    }
    @Override
        public boolean onCreateOptionsMenu (Menu menu){
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.menu_slimple_text_client, menu);
            return true;
        }
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // Check if the key event was the Back button and if there's history
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                    this);
    
            // set title
            alertDialogBuilder.setTitle("Dude are you serious???");
    
            // set dialog message
            alertDialogBuilder
                    .setMessage("Do you want to quit??")
                    .setCancelable(false)
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            SlimpleTextClientActivity.this.finish();
    
    
                        }
                    })
                    .setNegativeButton("No", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // if this button is clicked, just close
                            // the dialog box and do nothing
                            dialog.cancel();
                        }
                    });
    
            // create alert dialog
            AlertDialog alertDialog = alertDialogBuilder.create();
    
            // show it
            alertDialog.show();
    
            //super.onBackPressed();
    
            // return true;
        }
        return false;
    }}
    

    2.FileChooser活动

    public class FileChooser extends ListActivity {
    //Intent intentchooser=getIntent();
    public String directory;
    private List<String> item = null;
    private List<String> path = null;
    private String root;
    private TextView myPath;
    public EditText textField;
    final Context context = this;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.file);
       myPath = (TextView)findViewById(R.id.path);
      //   textField=(EditText)findViewById(R.id.small);
        root = Environment.getExternalStorageDirectory().getPath();
        getDir(root);
    }
    public File f;
    private void getDir(String dirPath)
    {
        myPath.setText("Location: " + dirPath);
        item = new ArrayList<String>();
        path = new ArrayList<String>();
        f = new File(dirPath);
       File[] files = f.listFiles();
        if(!dirPath.equals(root))
        {
            item.add(root);
            path.add(root);
            item.add("../");
            path.add(f.getParent());
        }
        for(int i=0; i < files.length; i++)
        {
            File file = files[i];
    
            if(!file.isHidden() && file.canRead()){
                path.add(file.getPath());
                if(file.isDirectory()){
                    item.add(file.getName() + "/");
                }else{
                    item.add(file.getName());
                }
            }
        }
    
        ArrayAdapter<String> fileList =
                new ArrayAdapter<String>(this, R.layout.row, item);
        setListAdapter(fileList);
    }
    
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        // TODO Auto-generated method stub
        File file = new File(path.get(position));
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                context);
        if (file.isDirectory())
        {
            if(file.canRead()){
                getDir(path.get(position));
    
            }else{
                new AlertDialog.Builder(this)
                        .setIcon(R.drawable.ic_launcher)
                        .setTitle("[" + file.getName() + "] folder can't be     read!")
                        .setPositiveButton("OK", null).show();
    
               // this.finish();
            }
        }else {
           final File filetemp=file;
            AlertDialog.Builder alertDialogBuilder1 = new AlertDialog.Builder(
                    context);
    
            // set title
            alertDialogBuilder.setTitle("Ready to upload???");
    
            // set dialog message
            alertDialogBuilder1
                    .setMessage("Do you want upload??")
                    .setCancelable(false)
                    .setPositiveButton("OK",new    DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int id) {
                            // if this button is clicked, close
                            // current activity
                            FileChooser.this.finish();
                            Intent in=new    Intent(FileChooser.this,SlimpleTextClientActivity.class);
                            in.putExtra("directory",filetemp.getAbsolutePath());
                                 System.out.println("\n\n\n\n\n\n"+filetemp.getAbsolutePath()+"\n\n\n\n\n");
                           // textField.setText(filetemp.getAbsolutePath());
    
                            startActivity(in);
    
    
                        }
                    })
                    .setNegativeButton("No",new   DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int id) {
                            // if this button is clicked, just close
                            // the dialog box and do nothing
                            dialog.cancel();
                        }
                    });
    
            // create alert dialog        
    AlertDialog alertDialog = alertDialogBuilder1.create();
    
              // show it
            alertDialog.show();
            textField.setText("file.getAbsolutePath()");
            Intent in=new Intent(FileChooser.this,SlimpleTextClientActivity.class);
    
    
            startActivity(in);
    
           finish();
        }
    }
     public boolean onKeyDown(int keyCode, KeyEvent event)
     {
        // Check if the key event was the Back button and if there's history
        if ((keyCode == KeyEvent.KEYCODE_BACK))
        {
            AlertDialog.Builder alertDialogBuilder = ne`enter code here`w    AlertDialog.Builder(
                    context);
    // set title
            alertDialogBuilder.setTitle("Dude are you serious???");
    
            // set dialog message
            alertDialogBuilder
                    .setMessage("Do you want to cancel file uploading??")
                    .setCancelable(false)
                    .setPositiveButton("Yes",new   DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int id) {
                            // if this button is clicked, close
                            // current activity
                          FileChooser.this.finish();
                            Intent in=new   Intent(FileChooser.this,SlimpleTextClientActivity.class);
                            in.putExtra("directory","yo baby ");
    
                            startActivity(in);
    
    
                        }
                      })
                      .setNegativeButton("No",new   DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int id) {
                            // if this button is clicked, just close
                            // the dialog box and do nothing
                            dialog.cancel();
                        }
                    });
    
            // create alert dialog
            AlertDialog alertDialog = alertDialogBuilder.create();
    
            // show it
            alertDialog.show();
    
            //super.onBackPressed();
    
    
            // return true;
        }
         return false;
    }
    }
    

    如果我不处理异常

    ,这就是应用程序崩溃的地方
      try {
                   directory1 = b.getString("directory");
                   file_path = directory1;
               } catch (Exception e) {
                   textField.setText(e.getMessage());
                   directory1="returned nothin";
               }
    

    这是我的xml文件。

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="shiva.com.filesenderlakj;"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="19" />
    <uses-permission android:name="android.permission.INTERNET" >
    </uses-permission>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" >
    </uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" >
    </uses-permission>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="shiva.com.filesenderlakj.SlimpleTextClientActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
    
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.SEND" />
    
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="shiva.com.filesenderlakj.FileChooser"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
    
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.SEND" />
    
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    

1 个答案:

答案 0 :(得分:0)

如果您的代码在此处引发异常

try {
    directory1 = b.getString("directory");
    file_path = directory1;
} catch (Exception e) {
    textField.setText(e.getMessage());
    directory1="returned nothon";
}

这意味着您的意图中没有"directory"额外费用。

当你开始SimpleClientActivity时,你需要确保使用"directory"额外的意图。

编辑:我已经更多地查看了您的代码,并提出了一个架构建议。您不应该使用startActivity,因为您正在使用Client - &gt;选择器 - &gt;客户。 startActivity适用于非循环活动的启动。如果你想更正确的话,你应该考虑使用BroadcastReceiver或LocalBroadcastManager。

免责声明:我输入此代码时没有编译或进行任何检查。这仅仅是为了指导您如何将“正确”的处理方式集成到您的应用程序中。

要制作BroadcastReceiver,您可以执行以下操作:

BroadcastReceiver br = new BroadcastReceiver() {
    @Override
    onReceive(Context context, Intent intent) {
        Bundle b = intent.getExtras();
        if (b.hasExtra(DIRECTORY_EXTRA)) {
            textField.setText(b.getString(DIRECTORY_EXTRA));
        }
    }
}

这样做是因为当您的BroadcastReceiver收到一个意图时,onReceived()将使用接收器运行的上下文及其收到的意图进行调用。

要将BroadcastReceiver设置为接收意图,您需要使用意图过滤器为特定类型的意图注册它:

IntentFilter myIntentFilter = new IntentFilter("my.app.package.myintent");

然后,您可以将BrodacastReceiver与IntentFilter配对,以告知Android操作系统在发送意向广播时向您转发意图。

@Override
public void onCreate(Bundle savedInstanceState) {
    // <make the BroadcastReceiver>
    // <make the intent filter>
    registerReceiver (br, myIntentFilter);
}

现在,您可以使用sendBroadcast。而不是使用startActivity进行通信。

Intent myIntent = new Intent("my.app.package.myintent");
myIntent.putExtra(DIRECTORY_EXTRA, directoryString);
sendBroadcast(myIntent);