Attaching a file of any type in Android applicatio

2019-05-03 07:19发布

I am building an application in which when a user press "Browse" button on the application I want to show folders from phone where user will select the file/image. Once the attachment is selected, application will show the file name in the attachments. What I am looking for is how the file attachment mechanism work in android so any code example or snippet in much appreciated.

Thanks in advance.

1条回答
来,给爷笑一个
2楼-- · 2019-05-03 07:58

What you actually want to do is execute Intent.ACTION_GET_CONTENT. If you specify type to be "file/*" then the file picker will allow you to select file of any type from the file system.

Here are a couple of reads:

This is the extracted source from the blog (courtesy of Android-er):

public class AndroidPick_a_File extends Activity {

 TextView textFile;

 private static final int PICKFILE_RESULT_CODE = 1;

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

       Button buttonPick = (Button)findViewById(R.id.buttonpick);
       textFile = (TextView)findViewById(R.id.textfile);

       buttonPick.setOnClickListener(new Button.OnClickListener(){

   @Override
   public void onClick(View arg0) {
    // TODO Auto-generated method stub

    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
             intent.setType("file/*");
       startActivityForResult(intent,PICKFILE_RESULT_CODE);

   }});
   }

 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  // TODO Auto-generated method stub
  switch(requestCode){
  case PICKFILE_RESULT_CODE:
   if(resultCode==RESULT_OK){
    String FilePath = data.getData().getPath();
    textFile.setText(FilePath);
   }
   break;

  }
 }
}

After acquiring path to the selected file it is up to you on how are you going to handle it: store path in a database, display it on screen, etc.

If you want to open the file with a default application, follow advices in this blog. Again, I extracted the code (courtesy of Hello World Codes):

First way:

String path="File Path";
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
File file = new File(path);

intent.setData(Uri.fromFile(file));

startActivity(intent);

Second way:

String path="File Path";   
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
File file = new File(path);

MimeTypeMap mime = MimeTypeMap.getSingleton();
String ext=file.getName().substring(file.getName().indexOf(".")+1);
String type = mime.getMimeTypeFromExtension(ext);

intent.setDataAndType(Uri.fromFile(file),type);

startActivity(intent);

Please remember to leave thanks to the guys who deserve it (-.

查看更多
登录 后发表回答