Отправить файл другому пользователю

Я хотел бы отправить файлы на смартфоне (файлы gpx) другому пользователю через свое приложение. Я не знаю, как это сделать. Как насчет отправки их по электронной почте или смс (используя намерения)?

Я реализовал файловый менеджер, поэтому я могу обрабатывать это в обработчике событий onFileLongClick в классе FileChooser.

Это коды классов FileChooser:

public class FileChooser extends ListActivity {

private File currentDir;
private FileArrayAdapter adapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    currentDir = Environment.getExternalStorageDirectory();
    fill(currentDir);
}
private void fill(File f)
{
    File[]dirs = f.listFiles();
    this.setTitle("Current Dir: "+f.getName());
    List<Item>dir = new ArrayList<Item>();
    List<Item>fls = new ArrayList<Item>();

    try {

        for(File ff: dirs) {

            Date lastModDate = new Date(ff.lastModified());
            DateFormat formater = DateFormat.getDateTimeInstance();
            String date_modify = formater.format(lastModDate);
            if(ff.isDirectory()) {

                File[] fbuf = ff.listFiles();
                int buf = 0;
                if(fbuf != null){
                    buf = fbuf.length;
                }
                else buf = 0;
                String num_item = String.valueOf(buf);
                if(buf == 0) num_item = num_item + " item";
                else num_item = num_item + " items";

                dir.add(new Item(ff.getName(),num_item,date_modify,ff.getAbsolutePath(),"directory_icon"));
            }
            else {
                fls.add(new Item(ff.getName(),ff.length() + " Byte", date_modify, ff.getAbsolutePath(),"file_icon"));
            }
        }
    }catch(Exception e) {
        e.printStackTrace();
    }
    Collections.sort(dir);
    Collections.sort(fls);
    dir.addAll(fls);
    if(!f.getName().equalsIgnoreCase("sdcard")) {
        dir.add(0,new Item("..","Parent Directory","",f.getParent(),"directory_up"));
    }
    adapter = new FileArrayAdapter(FileChooser.this,R.layout.row_custom_item, dir);
    this.setListAdapter(adapter);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    Item o = adapter.getItem(position);

    try {
        if(o.getImage().equalsIgnoreCase("directory_icon")||o.getImage().equalsIgnoreCase("directory_up")){
            currentDir = new File(o.getPath());
            fill(currentDir);
        }
        else {
            onFileClick(o);
        }
    }catch(NullPointerException e) {
        Toast.makeText(this, "There's no a parent directory!" , Toast.LENGTH_SHORT).show();
    }
}

private void onFileLongClick(Item o) {

    HERE
}

private void onFileClick(Item o)
{
    String name = o.getName();
    int index = name.lastIndexOf(".");

    if(index != -1) {

        String estensione =  name.substring(index);

        if(estensione.compareToIgnoreCase(".GPX") == 0) {
            Intent intent = new Intent();
            intent.putExtra("GetPath",currentDir.toString());
            intent.putExtra("GetFileName",o.getName());
            setResult(RESULT_OK, intent);
            finish();
        }
        else {
            Toast.makeText(this, "Puoi importare solo file con estensione .GPX" , Toast.LENGTH_SHORT).show();
        }
    }
    else {
        Toast.makeText(this, "Puoi importare solo file con estensione .GPX" , Toast.LENGTH_SHORT).show();
    }
}

Мне нужны ваши предложения!

Обновление: в ListActivity нет метода onLongListItemClick. :/


person Loris    schedule 25.01.2014    source источник


Ответы (3)


Вы можете отправить файл, запустив намерение электронной почты. Подробности смотрите в теме ниже

Попытка прикрепить файл с SD-карты к электронной почте

person Ajit Pratap Singh    schedule 25.01.2014
comment
Попробуйте этот код. Проверьте этот ответ. "> stackoverflow.com/questions/11068648/ File file = new File (filePath); Карта MimeTypeMap = MimeTypeMap.getSingleton(); Строка ext = MimeTypeMap.getFileExtensionFromUrl(file.getName()); Строковый тип = map.getMimeTypeFromExtension(ext); если (тип == ноль) тип = /; Намерение намерение = новое намерение (Intent.ACTION_VIEW); Данные Uri = Uri.fromFile(файл); намерение.setDataAndType (данные, тип); startActivity(намерение); - person Ajit Pratap Singh; 26.01.2014

Если вы хотите отправить свои файлы пользователям, которые находятся далеко от вас, вы можете прикрепить файлы к электронному письму и отправить его легко и быстро! Следуйте этим ссылкам, чтобы узнать, как отправлять электронную почту в Android и прикреплять: Как Я отправляю электронные письма из своего приложения Android? http://www.javacodegeeks.com/2013/10/send-email-with-attachment-in-android.html

Но если ваши пользователи находятся рядом с вами, вы можете использовать Bluetooth для отправки файлов.

person Seyed Hamed Shams    schedule 25.01.2014
comment
Есть ссылка на блютуз? - person Loris; 26.01.2014
comment
Здесь У Р! : javacodegeeks.com/2013/09/ stackoverflow.com/questions/12562875/android-bluetooth-example javatpoint.com/android-bluetooth-tutorial Предлагаю вам скачать эту книгу =› < i>Поваренная книга по разработке приложений для Android Это хороший справочник по программированию для Android. - person Seyed Hamed Shams; 26.01.2014

Хорошо, я сделал это ;)

Я написал это:

File fileToSend = new File(currentDir.getPath() + "/" + o.getName());
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("text/plain");
sendIntent.putExtra(Intent.EXTRA_SUBJECT, o.getName());
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(fileToSend));
sendIntent.putExtra(Intent.EXTRA_TEXT, "Enjoy the gpx file");
startActivity(Intent.createChooser(sendIntent, "Invia il file gpx"));

Но как я могу открыть только gmail?

person Loris    schedule 26.01.2014