Создать пакет "DocUpload"
Добавить 2 класса FilePath.java и SingleUploadBroadcastReceiver.java
FilePath.java
----------------------------------------
public class FilePath
{
/**
* Method for return file path of Gallery image
*
* @param context
* @param uri
* @return path of the selected image file from gallery
*/
public static String getPath(final Context context, final Uri uri)
{
//check here to KITKAT or new version
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
String fileName = getFilePath(context, uri);
if (fileName != null) {
return Environment.getExternalStorageDirectory().toString() + "/Download/" + fileName;
}
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
/*
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);*/
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
public static String getFilePath(Context context, Uri uri) {
Cursor cursor = null;
final String[] projection = {
MediaStore.MediaColumns.DISPLAY_NAME
};
try {
cursor = context.getContentResolver().query(uri, projection, null, null,
null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DISPLAY_NAME);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @param selection (Optional) Filter used in the query.
* @param selectionArgs (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
Log.e("check","===========>"+uri);
/* if (uri.toString().trim().contains("downloads/public_downloads")) {
uri = Uri.parse(uri.toString().replace("downloads/public_downloads", "downloads/my_downloads"));
}
*/
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is Google Photos.
*/
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
}
SingleUploadBroadcastReceiver.java
public class SingleUploadBroadcastReceiver extends UploadServiceBroadcastReceiver {
public interface Delegate {
void onProgress(int progress);
void onProgress(long uploadedBytes, long totalBytes);
void onError(Exception exception);
void onCompleted(int serverResponseCode, byte[] serverResponseBody);
void onCancelled();
}
private String mUploadID;
private Delegate mDelegate;
public void setUploadID(String uploadID) {
mUploadID = uploadID;
}
public void setDelegate(Delegate delegate) {
mDelegate = delegate;
}
@Override
public void onProgress(String uploadId, int progress) {
if (uploadId.equals(mUploadID) && mDelegate != null) {
mDelegate.onProgress(progress);
}
}
@Override
public void onProgress(String uploadId, long uploadedBytes, long totalBytes) {
if (uploadId.equals(mUploadID) && mDelegate != null) {
mDelegate.onProgress(uploadedBytes, totalBytes);
}
}
@Override
public void onError(String uploadId, Exception exception) {
if (uploadId.equals(mUploadID) && mDelegate != null) {
mDelegate.onError(exception);
}
}
@Override
public void onCompleted(String uploadId, int serverResponseCode, byte[] serverResponseBody) {
if (uploadId.equals(mUploadID) && mDelegate != null) {
mDelegate.onCompleted(serverResponseCode, serverResponseBody);
}
}
@Override
public void onCancelled(String uploadId) {
if (uploadId.equals(mUploadID) && mDelegate != null) {
mDelegate.onCancelled();
}
}
}
Реализовать на фрагмент
implements View.OnClickListener, SingleUploadBroadcastReceiver.Delegate
private final SingleUploadBroadcastReceiver uploadReceiver =
new SingleUploadBroadcastReceiver();
добавить переменные
//------------------------------------------------------------------------------------------------------------------
//Image request code
private int PICK_DOC_REQUEST = 1;
private int PICK_VIDEO_REQUEST = 2;
//storage permission code
private static final int STORAGE_PERMISSION_CODE = 123;
//Uri to store the image uri
private Uri filePath = null, VideofilePath = null;
//------------------------------------------------------------------------------------------------------------------
если тип документа ------------- используйте showFileChooser (); при нажатии на кнопку еще, если вам нужна только загрузка видео, используйте showVideoFileChooser (); при нажатии кнопки
//method to show file chooser
private void showFileChooser() {
// Intent intent = new Intent();
// intent.setType("*/*");
// intent.setAction(Intent.ACTION_GET_CONTENT);
// startActivityForResult(Intent.createChooser(intent, "Select Pdf"), PICK_DOC_REQUEST);
String[] mimeTypes = {"application/pdf", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "application/msword"};
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
intent.setType(mimeTypes.length == 1 ? mimeTypes[0] : "*/*");
if (mimeTypes.length > 0) {
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
}
} else {
String mimeTypesStr = "";
for (String mimeType : mimeTypes) {
mimeTypesStr += mimeType + "|";
}
intent.setType(mimeTypesStr.substring(0, mimeTypesStr.length() - 1));
}
startActivityForResult(Intent.createChooser(intent, ""), PICK_DOC_REQUEST);
}
//method to show file chooser
private void showVideoFileChooser() {
// Intent intent = new Intent();
// intent.setType("*/*");
// intent.setAction(Intent.ACTION_GET_CONTENT);
// startActivityForResult(Intent.createChooser(intent, "Select Pdf"), PICK_DOC_REQUEST);
String[] mimeTypes = {"video/*"};
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
intent.setType(mimeTypes.length == 1 ? mimeTypes[0] : "*/*");
if (mimeTypes.length > 0) {
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
}
} else {
String mimeTypesStr = "";
for (String mimeType : mimeTypes) {
mimeTypesStr += mimeType + "|";
}
intent.setType(mimeTypesStr.substring(0, mimeTypesStr.length() - 1));
}
startActivityForResult(Intent.createChooser(intent, ""), PICK_VIDEO_REQUEST);
}
//handling the ima chooser activity result
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_DOC_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
String filename = "DOC_" + filePath.toString().substring(filePath.toString().lastIndexOf("/") + 1);
edtTeacherRegUploadDocument.setText(filename);
} else if (requestCode == PICK_VIDEO_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
VideofilePath = data.getData();
String filename = "VID_" + VideofilePath.toString().substring(VideofilePath.toString().lastIndexOf("/") + 1);
edtUploadVideo.setText(filename);
}
}
@Override
public void onClick(View view) {
}
@Override
public void onResume() {
super.onResume();
uploadReceiver.register(getActivity());
}
@Override
public void onPause() {
super.onPause();
uploadReceiver.unregister(getActivity());
}
@Override
public void onProgress(int progress) {
Log.e("progress", "progress " + progress);
}
@Override
public void onProgress(long uploadedBytes, long totalBytes) {
Log.e("uploadedBytes", "uploadedBytes " + uploadedBytes);
Log.e("totalBytes", "totalBytes " + totalBytes);
}
@Override
public void onError(Exception exception) {
Toast.makeText(getActivity(), "" + exception.toString(), Toast.LENGTH_SHORT).show();
Log.e("exception", "exception " + exception.toString());
}
@Override
public void onCompleted(int serverResponseCode, byte[] serverResponseBody) {
Log.e("serverResponseCode", "serverResponseCode " + serverResponseCode);
try {
String str = new String(serverResponseBody, "UTF-8");
Log.e("serverResponseBody", "serverResponseBody[] " + str);
// Toast.makeText(getActivity(), "" + str, Toast.LENGTH_SHORT).show();
//txt_error.setText(str);
try {
JSONObject jsonObject = new JSONObject(str);
String error_code = jsonObject.getString("error_code");
if (error_code.equalsIgnoreCase("1")) {
UtilityMethods.showSuccessToast(getActivity(), "Teacher registered successfully");
TeacherLoginFragment teacherLoginFragment = new TeacherLoginFragment();
Constants.mMainActivity.changeFragment(teacherLoginFragment, "TeacherLoginFragment");
} else if (error_code.equalsIgnoreCase("2")) {
UtilityMethods.tuchOn(relativeLayoutProgressBarTeacherRegistration);
UtilityMethods.showWarningToast(getActivity(), "Teacher already registered");
} else if (error_code.equalsIgnoreCase("3")) {
} else if (error_code.equalsIgnoreCase("4")) {
} else if (error_code.equalsIgnoreCase("5")) {
} else if (error_code.equalsIgnoreCase("10")) {
UtilityMethods.showErrorToast(getActivity(), "Something went wrong, please contact to admin");
} else if (error_code.equalsIgnoreCase("0")) {
UtilityMethods.showInfoToast(getActivity(), "Please enter all details");
}
} catch (Exception e) {
e.printStackTrace();
UtilityMethods.showToast(getActivity(), "Server Error");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
@Override
public void onCancelled() {
Log.e("onCancelled", "onCancelled ");
}