繁体   English   中英

android应用程序从sdcard中选择一个文件并使用套接字上传到服务器

[英]android app to select a file from sdcard and upload to server using socket

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

  1. SimpleClientActivity
  2. 文件选择器活动

我正在尝试在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>

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

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

这意味着您的意图没有多余的"directory"

启动SimpleClientActivity ,需要确保您使用带"directory"额外内容的意图。

编辑:我看了更多您的代码,并有体系结构的建议。 您不应该使用startActivity,因为您正在执行客户端->选择器->客户端。 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 OS在发送意图广播时将意图转发给您。

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM