如何从画廊中选择任何文件从uri获取文件名?

时间:2015-04-22 09:01:47

标签: java android eclipse

我在行上使用片段的上下文时获得空值

selectedPath = ImageFilePath.getPath(mContext, uri);

public class DeviceDetailFragment extends Fragment implements ConnectionInfoListener {

protected static final int CHOOSE_FILE_RESULT_CODE = 20;
private View mContentView = null;
private WifiP2pDevice device;
private WifiP2pInfo info;
ProgressDialog progressDialog = null;
private Context mContext;
public static String filename;

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);     
}

@Override
public void onAttach(Activity activity) {
    // TODO Auto-generated method stub
    super.onAttach(activity);
    mContext = getActivity().getApplicationContext();
}

@SuppressLint("InflateParams")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    mContentView = inflater.inflate(R.layout.device_detail, null);
    mContentView.findViewById(R.id.btn_connect).setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            WifiP2pConfig config = new WifiP2pConfig();
            config.deviceAddress = device.deviceAddress;
            config.wps.setup = WpsInfo.PBC;
            if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
            }
            progressDialog = ProgressDialog.show(getActivity(), "Press back to cancel",
                    "Connecting to :" + device.deviceAddress, true, true
                    );
            ((DeviceActionListener) getActivity()).connect(config);

        }
    });

    mContentView.findViewById(R.id.btn_disconnect).setOnClickListener(
            new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    ((DeviceActionListener) getActivity()).disconnect();
                }
            });

    mContentView.findViewById(R.id.btn_start_client).setOnClickListener(
            new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                    intent.setType("*/*");
                    startActivityForResult(intent, CHOOSE_FILE_RESULT_CODE);
                }
            });

    return mContentView;
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    Uri uri = data.getData();
    if (resultCode == Activity.RESULT_OK)
    {
     if (requestCode == CHOOSE_FILE_RESULT_CODE)
     {       
      String selectedPath;
      selectedPath = ImageFilePath.getPath(mContext, uri);
      filename = selectedPath.substring(selectedPath.lastIndexOf("/")+1);
     }
    }

    TextView statusText = (TextView) mContentView.findViewById(R.id.status_text);
    statusText.setText("Sending: " + uri);
    Log.d(WiFiDirectActivity.TAG, "Intent----------- " + uri);
    Intent serviceIntent = new Intent(getActivity(), FileTransferService.class);
    serviceIntent.setAction(FileTransferService.ACTION_SEND_FILE);
    serviceIntent.putExtra(FileTransferService.EXTRAS_FILE_PATH, uri.toString());
    serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_ADDRESS,
            info.groupOwnerAddress.getHostAddress());
    serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_PORT, 8988);
    getActivity().startService(serviceIntent);
}

@Override
public void onConnectionInfoAvailable(final WifiP2pInfo info) {
    if (progressDialog != null && progressDialog.isShowing()) {
        progressDialog.dismiss();
    }
    this.info = info;
    this.getView().setVisibility(View.VISIBLE);

    TextView view = (TextView) mContentView.findViewById(R.id.group_owner);
    view.setText(getResources().getString(R.string.group_owner_text)
            + ((info.isGroupOwner == true) ? getResources().getString(R.string.yes)
                    : getResources().getString(R.string.no)));

    view = (TextView) mContentView.findViewById(R.id.device_info);
    view.setText("Group Owner IP - " + info.groupOwnerAddress.getHostAddress());

    if (info.groupFormed && info.isGroupOwner) {
        new FileServerAsyncTask(getActivity(), mContentView.findViewById(R.id.status_text))
                .execute();
    } else if (info.groupFormed) {
        mContentView.findViewById(R.id.btn_start_client).setVisibility(View.VISIBLE);
        ((TextView) mContentView.findViewById(R.id.status_text)).setText(getResources()
                .getString(R.string.client_text));
    }

    mContentView.findViewById(R.id.btn_connect).setVisibility(View.GONE);
}

public void showDetails(WifiP2pDevice device) {
    this.device = device;
    this.getView().setVisibility(View.VISIBLE);
    TextView view = (TextView) mContentView.findViewById(R.id.device_address);
    view.setText(device.deviceAddress);
    view = (TextView) mContentView.findViewById(R.id.device_info);
    view.setText(device.toString());
}

public void resetViews() {
    mContentView.findViewById(R.id.btn_connect).setVisibility(View.VISIBLE);
    TextView view = (TextView) mContentView.findViewById(R.id.device_address);
    view.setText(R.string.empty);
    view = (TextView) mContentView.findViewById(R.id.device_info);
    view.setText(R.string.empty);
    view = (TextView) mContentView.findViewById(R.id.group_owner);
    view.setText(R.string.empty);
    view = (TextView) mContentView.findViewById(R.id.status_text);
    view.setText(R.string.empty);
    mContentView.findViewById(R.id.btn_start_client).setVisibility(View.GONE);
    this.getView().setVisibility(View.GONE);
}

  public static class FileServerAsyncTask extends AsyncTask<Void, Void, String> {

    private Context context;
    private TextView statusText;

    public FileServerAsyncTask(Context context, View statusText) {
        this.context = context;
        this.statusText = (TextView) statusText;
    }

    @Override
    protected String doInBackground(Void... params) {
        try {
            ServerSocket serverSocket = new ServerSocket(8988);
            Log.d(WiFiDirectActivity.TAG, "Server: Socket opened");
            Socket client = serverSocket.accept();
            Log.d(WiFiDirectActivity.TAG, "Server: connection done");

            final File f = new File(Environment.getExternalStorageDirectory() + "/"
                    + context.getPackageName() + "/" + filename);       

            File dirs = new File(f.getParent());
            if (!dirs.exists())
                dirs.mkdirs();
            f.createNewFile();

            Log.d(WiFiDirectActivity.TAG, "server: copying files " + f.toString());
            InputStream inputstream = client.getInputStream();
            copyFile(inputstream, new FileOutputStream(f));
            serverSocket.close();
            return f.getAbsolutePath();   
        } catch (IOException e) {
            Log.e(WiFiDirectActivity.TAG, e.getMessage());
            return null;
        }            
    }

    @Override
    protected void onPostExecute(String result) {
        if (result != null) {
            statusText.setText("File copied - " + result);
            Intent intent = new Intent();
            intent.setAction(android.content.Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.parse("file://" + result), "*/*");
            context.startActivity(intent);
        }

    }

    @Override
    protected void onPreExecute() {
        statusText.setText("Opening a server socket");
    }
}

public static boolean copyFile(InputStream inputStream, OutputStream out) {
    byte buf[] = new byte[1024];
    int len;
    long startTime=System.currentTimeMillis();

    try {
        while ((len = inputStream.read(buf)) != -1) {
            out.write(buf, 0, len);
        }
        out.close();
        inputStream.close();
        long endTime=System.currentTimeMillis()-startTime;
        Log.v("","Time taken to transfer all bytes is : "+endTime);

    } catch (IOException e) {
        Log.d(WiFiDirectActivity.TAG, e.toString());
        return false;
    }
    return true;
}

}

这是FileNamePath

的代码
public class FileTransferService extends IntentService {

private static final int SOCKET_TIMEOUT = 5000;
public static final String ACTION_SEND_FILE = "com.example.android.wifidirect.SEND_FILE";
public static final String EXTRAS_FILE_PATH = "file_url";
public static final String EXTRAS_GROUP_OWNER_ADDRESS = "go_host";
public static final String EXTRAS_GROUP_OWNER_PORT = "go_port";

public FileTransferService(String name) {
    super(name);
}

public FileTransferService() {
    super("FileTransferService");
}

/*
 * (non-Javadoc)
 * @see android.app.IntentService#onHandleIntent(android.content.Intent)
 */
@Override
protected void onHandleIntent(Intent intent) {

    Context context = getApplicationContext();
    if (intent.getAction().equals(ACTION_SEND_FILE)) {
        String fileUri = intent.getExtras().getString(EXTRAS_FILE_PATH);
        String host = intent.getExtras().getString(EXTRAS_GROUP_OWNER_ADDRESS);
        Socket socket = new Socket();
        int port = intent.getExtras().getInt(EXTRAS_GROUP_OWNER_PORT);

        try {
            Log.d(WiFiDirectActivity.TAG, "Opening client socket - ");
            socket.bind(null);
            socket.connect((new InetSocketAddress(host, port)), SOCKET_TIMEOUT);

            Log.d(WiFiDirectActivity.TAG, "Client socket - " + socket.isConnected());
            OutputStream stream = socket.getOutputStream();
            ContentResolver cr = context.getContentResolver();
            InputStream is = null;
            try {
                is = cr.openInputStream(Uri.parse(fileUri));
            } catch (FileNotFoundException e) {
                Log.d(WiFiDirectActivity.TAG, e.toString());
            }
            DeviceDetailFragment.copyFile(is, stream);
            Log.d(WiFiDirectActivity.TAG, "Client: Data written");
        } catch (IOException e) {
            Log.e(WiFiDirectActivity.TAG, e.getMessage());
        } finally {
            if (socket != null) {
                if (socket.isConnected()) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        // Give up
                        e.printStackTrace();
                    }
                }
            }
        }

    }
}
}   

我无法获取文件名并且只能获取空值。

0 个答案:

没有答案
相关问题