I am new for android.make one video player code the video play from url and user can download the video from the apps. i make until download and push Notification and using service. the issue i is when download one video the user click download another video is overwrite the 1st download. any one can give me solution..
package crazysing.crazyweb.my.fragment;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.NetworkImageView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import crazysing.crazyweb.my.MainActivity;
import crazysing.crazyweb.my.R;
import crazysing.crazyweb.my.adater.CustomListAdapter;
import crazysing.crazyweb.my.app.AppController;
import crazysing.crazyweb.my.model.Movie;
import crazysing.crazyweb.my.service.NLService;
/**
* Created by LENOVO on 14/02/2017.
*/
public class SongPlayerFragment extends Fragment {
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
String videopath = "http://crazysing.crazyweb.my/upload/vid/";
NotificationCompat.Builder mBuilder;
NotificationManager mNotifyManager;
int id = 1;
int counter = 0;
private NotificationReceiver nReceiver;
String sdCard = Environment.getExternalStorageDirectory().toString();
File myDir = new File(sdCard, "Video/CrazySing");
VideoView videov;
MediaController mediaC;
NetworkImageView videothumbNail;
// Movies json url
private static final String url = "http://crazysing.crazyweb.my/api/songlist.php";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
class NotificationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String event = intent.getExtras().getString(NLService.NOT_EVENT_KEY);
Log.i("NotificationReceiver", "NotificationReceiver onReceive : " + event);
if (event.trim().contentEquals(NLService.NOT_REMOVED)) {
killTasks();
}
}
}
private void killTasks() {
mNotifyManager.cancelAll();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.song_player_fragment, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
videov = (VideoView) view.findViewById(R.id.videov);
mediaC = new MediaController(getActivity());
listView = (ListView) view.findViewById(R.id.list);
adapter = new CustomListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
// Register the ListView for Context menu
registerForContextMenu(listView);
listView.setOnItemClickListener(new ItemList());
videothumbNail = (NetworkImageView) view.findViewById(R.id.placeholder);
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("title"));
movie.setFileName(obj.getString("filename"));
movie.setVideoPath(obj.getString("video_path"));
movie.setSingerName(obj.getString("singer_name"));
movie.setSongId(obj.getInt("songId"));
movie.setDuration(obj.getString("duration"));
movie.setThumbnailUrl(obj.getString("image"));
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
videoView(" ", " "," ");
}
public void videoView(String videopath,String fileName, String imageName) {
// videopath = videopath + filename;
if (imageName == " ") {
videothumbNail.setDefaultImageResId(R.drawable.sing);
videothumbNail.setErrorImageResId(R.drawable.sing);
videothumbNail.setVisibility(View.VISIBLE);
videov.setVisibility(View.INVISIBLE);
Log.d(TAG, "empty vedeio");
} else {
videothumbNail.setImageUrl(imageName, imageLoader);
videothumbNail.setVisibility(View.VISIBLE);
videov.setVisibility(View.INVISIBLE);
File file = new File(myDir, fileName);
if (file.exists()){
Uri uri = Uri.parse(myDir+"/"+fileName);
videov.setVideoURI(uri);
videov.setMediaController(mediaC);
mediaC.setAnchorView(videov);
videov.start();
videov.setVisibility(View.VISIBLE);
videov.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
videothumbNail.setVisibility(View.GONE);
}
});
}else {
try {
Uri uri = Uri.parse(videopath);
videov.setVideoURI(uri);
videov.setMediaController(mediaC);
mediaC.setAnchorView(videov);
videov.start();
videov.setVisibility(View.VISIBLE);
videov.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
videothumbNail.setVisibility(View.GONE);
}
});
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getActivity().getMenuInflater();
inflater.inflate(R.menu.song_list_menu, menu);
menu.setHeaderTitle("Options");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
int index = info.position;
View view = info.targetView;
String VideoPath = ((Movie) movieList.get(index)).getVideoPath();
String FileName = ((Movie) movieList.get(index)).getFileName();
String urlsToDownload[] = {VideoPath,FileName};
switch (item.getItemId()) {
case R.id.download:
NotificationManager(urlsToDownload);
Log.d(TAG, "value=" + VideoPath);
return true;
default:
return super.onContextItemSelected(item);
}
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
killTasks();
getActivity().unregisterReceiver(nReceiver);
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
class ItemList implements AdapterView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
view.setSelected(true);
String videoUrl = ((Movie) movieList.get(position)).getVideoPath();
String fileName = ((Movie) movieList.get(position)).getFileName();
String bitmap = ((Movie) movieList.get(position)).getThumbnailUrl();
Toast.makeText(SongPlayerFragment.this.getActivity(), videoUrl, Toast.LENGTH_SHORT).show();
videoView(videoUrl,fileName, bitmap);
}
}
private void downloadImagesToSdCard(String downloadUrl, String videoName) {
FileOutputStream fos;
InputStream inputStream = null;
try {
URL url = new URL(downloadUrl);
/* making a directory in sdcard */
/* if specified not exist create new */
if (!myDir.exists()) {
myDir.mkdir();
Log.v("", "inside mkdir");
}
/* checks the file and if it already exist delete */
String fname = videoName;
File file = new File(myDir, fname);
Log.d("file===========path", "" + file);
if (file.exists())
file.delete();
/* Open a connection */
URLConnection ucon = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) ucon;
httpConn.setRequestMethod("GET");
httpConn.connect();
inputStream = httpConn.getInputStream();
/*
* if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
* inputStream = httpConn.getInputStream(); }
*/
fos = new FileOutputStream(file);
// int totalSize = httpConn.getContentLength();
// int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fos.write(buffer, 0, bufferLength);
// downloadedSize += bufferLength;
// Log.i("Progress:", "downloadedSize:" + downloadedSize +
// "totalSize:" + totalSize);
}
inputStream.close();
fos.close();
Log.d("test", "Video Saved in sdcard..");
} catch (IOException io) {
inputStream = null;
fos = null;
io.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
private class ImageDownloader extends AsyncTask<String, String, Void> {
#Override
protected Void doInBackground(String... param) {
downloadImagesToSdCard(param[0], param[1]);
return null;
}
protected void onProgressUpdate(String... values) {
}
#Override
protected void onPreExecute() {
Log.i("Async-Example", "onPreExecute Called");
}
#Override
protected void onPostExecute(Void result) {
Log.i("Async-Example", "onPostExecute Called");
mBuilder.setContentTitle("Done.");
mBuilder.setContentText("Download complete")
// Removes the progress bar
.setProgress(0, 0, false);
mNotifyManager.notify(id, mBuilder.build());
}
}
private void NotificationManager(String... param){
mNotifyManager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(getActivity());
mBuilder.setContentTitle("Downloading Video...").setContentText("Download in progress").setSmallIcon(R.mipmap.ic_launcher);
//add sound
Uri nUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mBuilder.setSound(nUri);
//vibrate
long[] v = {500,1000};
mBuilder.setVibrate(v);
// Start a lengthy operation in a background thread
mBuilder.setProgress(0, 0, true);
mNotifyManager.notify(id, mBuilder.build());
mBuilder.setAutoCancel(true);
ImageDownloader imageDownloader = new ImageDownloader();
imageDownloader.execute(param);
ContentResolver contentResolver = getActivity().getContentResolver();
String enabledNotificationListeners = Settings.Secure.getString(contentResolver, "enabled_notification_listeners");
String packageName = getActivity().getPackageName();
// check to see if the enabledNotificationListeners String contains our
// package name
if (enabledNotificationListeners == null || !enabledNotificationListeners.contains(packageName)) {
// in this situation we know that the user has not granted the app
// the Notification access permission
// Check if notification is enabled for this application
Log.i("ACC", "Dont Have Notification access");
Intent intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
startActivity(intent);
} else {
Log.i("ACC", "Have Notification access");
}
nReceiver = new NotificationReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(NLService.NOT_TAG);
getActivity().registerReceiver(nReceiver, filter);
}
}
Instead of using only
File myDir = new File(sdCard, "Video/CrazySing");
use
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Video" + n + ".mp4";
File file = new File(myDir, fname);
This will generate a unique file name for each time.
Instead .mp4 you can use your video extension
Related
I am trying to download pdf using DownloadManager.
I am passing parameter in link and from server pdf file generated and downloaded into device. so my download link would be some what like this
http://example.com/gen.php?data={......}
My Code :
final Request request = new Request(Uri.parse(fromUrl));
request.setMimeType("application/pdf");
request.setNotificationVisibility(Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(path, "ELALA_MANIFEST_" + System.currentTimeMillis() + ".pdf");
final DownloadManager dm = (DownloadManager) context
.getSystemService(Context.DOWNLOAD_SERVICE);
try {
try {
dm.enqueue(request);
} catch (SecurityException e) {
request.setNotificationVisibility(Request.VISIBILITY_VISIBLE);
Log.e("Error", e.toString());
dm.enqueue(request);
}
}
// if the download manager app has been disabled on the device
catch (IllegalArgumentException e) {
openAppSettings(context,
AdvancedWebView.PACKAGE_NAME_DOWNLOAD_MANAGER);
}
This works fine in device with api level 21 (lollipop) and above. but in lower version pdf not getting downloaded. and notification pops like,
<untitled> download unsuccessful
I know it something has to do with setMimeType, but don't know what.
Any Help will be appreciated.
When You get <untitled> download unsuccessful, usually it means Your url was not correct or empty or null. So first of all please be sure url is OK.
Look at my small example with DownloadManager which runs in 4.4 (pre-lolipop).
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import java.io.File;
public class MainActivity extends AppCompatActivity {
private DownloadManager dm;
private String url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
url = "https://collegereadiness.collegeboard.org/pdf/psat-nmsqt-practice-test-1.pdf";
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (TextUtils.isEmpty(url)) {
throw new IllegalArgumentException("url cannot be empty or null");
}
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
if (isExternalStorageWritable()) {
String uriString = v.getContext().getExternalFilesDir(null) + "";
File file = new File(uriString, Uri.parse(url).getLastPathSegment());
Uri destinationUri = Uri.fromFile(file);
request.setDestinationUri(destinationUri);
dm.enqueue(request);
}
}
});
registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
Log.d(TAG, "onReceive() returned: " + action);
// TODO: 2016-10-12
} else if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(action)) {
Log.d(TAG, "onReceive() returned: " + action);
// TODO: 2016-10-12
}
}
};
private static final String TAG = "MainActivity";
//...
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(state);
}
public boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state);
}
}
It uses permissions:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
It is important to handle all conditions. Also try use app directory instead messing around i.e on Your sd card. This example saves downloaded files in
/sdcard/Android/data/{your app package name}/files/. Previously I check if I have mounted sdcard and if I can write on directory.
Sample:
Okay, here is my sample with resolving filename if header has "Content-Disposition` field. You said it is on YOur server, so You will be able do it :)
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private DownloadManager dm;
private String url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
url = "http://dl1.shatelland.com/files/07610a8d-a73f-45bb-8868-6fd33299bda7/6e33639f-0ce0-43ef-86e4-43492db1be86";
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
new Thread(new Runnable() {
#Override
public void run() {
downloadFileInTask(v.getContext(), url);
}
}).start();
}
});
registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
private void downloadFileInTask(Context v, String url) {
if (TextUtils.isEmpty(this.url)) {
throw new IllegalArgumentException("url cannot be empty or null");
}
/*when redirecting from hashed url and found headerField "Content-Disposition"*/
String resolvedFile = resolveFile(url, "unknown_file");
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
if (isExternalStorageWritable()) {
File file = new File(v.getExternalFilesDir(null), resolvedFile);
Uri destinationUri = Uri.fromFile(file);
request.setDestinationUri(destinationUri);
dm.enqueue(request);
}
}
private String resolveFile(String url, String defaultFileName) {
String filename = defaultFileName;
HttpURLConnection con = null;
try {
con = (HttpURLConnection) new URL(url).openConnection();
con.setInstanceFollowRedirects(true);
con.connect();
String contentDisposition = con.getHeaderField("Content-Disposition");
if (!TextUtils.isEmpty(contentDisposition)) {
String[] splittedCD = contentDisposition.split(";");
for (int i = 0; i < splittedCD.length; i++) {
if (splittedCD[i].trim().startsWith("filename=")) {
filename = splittedCD[i].replaceFirst("filename=", "").trim();
break;
}
}
}
con.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
return filename;
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
Log.d(TAG, "onReceive() returned: " + action);
// TODO: 2016-10-12
} else if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(action)) {
Log.d(TAG, "onReceive() returned: " + action);
// TODO: 2016-10-12
}
}
};
private static final String TAG = "MainActivity";
//...
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(state);
}
public boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state);
}
}
I am developing an app to uploading ,displaying and downloading files from G Drive. Unfortunately When downloading I am getting
com.google.api.client.http.HttpResponseException: 401 Unauthorized.
Please help me to solve this problem.
Here I am assigning
credential = GoogleAccountCredential.usingOAuth2(this,DriveScopes.DRIVE);
service=new Drive.Builder(AndroidHttp.newCompatibleTransport(),new GsonFactory(),credential).build();
My Code Is:
package com.example.googledrive;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;
import com.google.api.client.http.FileContent;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.Drive.Children;
import com.google.api.services.drive.Drive.Files;
import com.google.api.services.drive.Drive.Files.Get;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.ChildList;
import com.google.api.services.drive.model.ChildReference;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
static final int REQUEST_ACCOUNT_PICKER = 1;
static final int REQUEST_AUTHORIZATION = 2;
static final int CAPTURE_IMAGE = 3;
private static Uri fileUri;
private static Drive service;
private ProgressDialog progressDialog;
private GoogleAccountCredential credential;
String fileId;
String fileName;
String downloadUrl;
ListView listView;
Activity activity;
String sdCardPadth;
List<File> allFileList;
ArrayList<String> fileType;
ArrayList<String> mainTitleList;
ArrayList<String> fileIdList;
ArrayList<String> alternateUrlList;
ArrayList<Integer> fileSizeList;
FileTitlesAdapter myAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.uploadedFilesList);
allFileList = new ArrayList<File>();
mainTitleList = new ArrayList<String>();
alternateUrlList = new ArrayList<String>();
fileSizeList = new ArrayList<Integer>();
fileType = new ArrayList<String>();
fileIdList=new ArrayList<String>();
progressDialog=new ProgressDialog(getApplicationContext());
progressDialog.setTitle("Please Wait....");
progressDialog.setCancelable(false);
activity = this;
credential = GoogleAccountCredential.usingOAuth2(this,DriveScopes.DRIVE);
startActivityForResult(credential.newChooseAccountIntent(),REQUEST_ACCOUNT_PICKER);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View view, final int arg2,long arg3) {
// String str=itemArray.get(arg2).toString().trim();
System.out.println("mainTitleList size==="+mainTitleList.size());
System.out.println("arg2==="+arg2);
fileName = (String)mainTitleList.get(arg2);
mainTitleList.clear();
//fileSizeList.clear();
final String fileTypeStr=fileType.get(arg2);
fileType.clear();
if(fileTypeStr.contains("application/vnd.google-apps.folder"))
{
Thread t = new Thread(new Runnable() {
#Override
public void run() {
boolean b=true;
try {
String dirUrl=alternateUrlList.get(arg2);
alternateUrlList.clear();
System.out.println("Folder Name Is:"+fileName);
System.out.println("Folder Type Is:"+fileTypeStr);
System.out.println("Folder URL Is:"+dirUrl);
String fileId=fileIdList.get(arg2);
System.out.println("Folder Id Is:"+fileId);
//retrieveAllFilesFromDir(service, fileId, b);
//retrieveAllFiles1(service, b, fileId);
//Files.List request = service.children().get(fileId, null);
Files.List request = service.files().list().setQ("'" + fileId + "' in parents ");
retrieveAllFiles(service,request,b);
//retrieveAllFiles(service, b);
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("Exception In retrieveAllFiles Dir Is:"+e);
e.printStackTrace();
}
}
});t.start();
}
else
{
try {
System.out.println("fileSizeList size===="+fileSizeList.size());
System.out.println("arg2===="+arg2);
Integer fileSize = (int) fileSizeList.get(arg2);
downloadUrl = alternateUrlList.get(arg2);
byte[] size = new byte[fileSize];
int byteRead = 0, byteWritten = 0;
sdCardPadth = Environment.getExternalStorageDirectory().getPath();
System.out.println("Download Url==="+downloadUrl);
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
InputStream inStream=downloadFile(service, downloadUrl);
java.io.File inFile=new java.io.File(sdCardPadth+"/"+fileName+"1");
System.out.println("File Succesfully Stored");
}
}).start();
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("Exception In get Integer Is:" + e);
e.printStackTrace();
}
}
}
});
}
#Override
protected void onActivityResult(final int requestCode,
final int resultCode, final Intent data) {
switch (requestCode) {
case REQUEST_ACCOUNT_PICKER:
if (resultCode == RESULT_OK && data != null
&& data.getExtras() != null) {
String accountName = data
.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
if (accountName != null) {
credential.setSelectedAccountName(accountName);
service = getDriveService(credential);
final boolean b=false;
Thread t=new Thread(new Runnable() {
#Override
public void run() {
try
{
Files.List request = service.files().list().setQ("hidden="+b);
retrieveAllFiles(service,request,b);
} catch (Exception e) {
System.out.println("Exception Is:"+e);
e.printStackTrace();
}
}
}) ;t.start();
}
}
break;
case REQUEST_AUTHORIZATION:
if (resultCode == Activity.RESULT_OK) {
System.out.println("REQUEST_AUTHORIZATION case Is:"
+ REQUEST_AUTHORIZATION);
saveFileToDrive();
} else {
startActivityForResult(credential.newChooseAccountIntent(),
REQUEST_ACCOUNT_PICKER);
}
break;
case CAPTURE_IMAGE:
if (resultCode == Activity.RESULT_OK) {
System.out.println("CAPTURE_IMAGE case Is:" + CAPTURE_IMAGE);
saveFileToDrive();
}
}
}
private void saveFileToDrive() {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
// File's binary content
System.out.println("run method");
java.io.File fileContent = new java.io.File(fileUri.getPath());
FileContent mediaContent = new FileContent("image/jpeg",fileContent);
// File's metadata.
File body = new File();
body.setTitle(fileContent.getName());
body.setMimeType("image/jpeg");
File file=null;
try {
file = service.files().insert(body, mediaContent).execute();
} catch (Exception e) {
System.out.println("Exception In Insert File Is"+e);
e.printStackTrace();
}
if (file != null) {
showToast("Photo uploaded: " + file.getTitle());
System.out.println("photo sucessfullly uploaded:"+ fileId);boolean b=false;
Files.List request = service.files().list().setQ("hidden="+b);
retrieveAllFiles(service,request,b);
}
} catch (UserRecoverableAuthIOException e) {
startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
} catch (IOException e) {
e.printStackTrace();
}
}
});
t.start();
}
private Drive getDriveService(GoogleAccountCredential credential) {
return new Drive.Builder(AndroidHttp.newCompatibleTransport(),
new GsonFactory(), credential).build();
}
public void showToast(final String toast) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), toast,Toast.LENGTH_SHORT).show();
}
});
}
private List<File> retrieveAllFiles(Drive service,Files.List request,boolean b) throws IOException {
List<File> result = new ArrayList<File>();
final ArrayList<String> titleList = new ArrayList<String>();
String fileUrl = "";
do {
try {
FileList files = request.execute();
result.addAll(files.getItems());
request.setPageToken(files.getNextPageToken());
for (int i = 0; i < result.size(); i++) {
File tempFile = result.get(i);
String fileTypeStr = tempFile.getMimeType();
String fileName = tempFile.getTitle();
titleList.add(fileName);
fileId = tempFile.getId();
fileIdList.add(fileId);
fileUrl = tempFile.getAlternateLink();
System.out.println("<><>< fileUrl Is:" + fileUrl);
alternateUrlList.add(fileUrl);
fileType.add(fileTypeStr);
mainTitleList.add(fileName);
try {
Integer fileSize =tempFile.getFileSize()==null?100:(int) (long) tempFile.getFileSize();
fileSizeList.add(fileSize);
System.out.println("<><>< fileSize Is:" + fileSize);
} catch (Exception e) {
fileSizeList.add(2000);
e.printStackTrace();
}
}
try {
runOnUiThread(new Runnable() {
public void run() {
myAdapter = new FileTitlesAdapter(activity,
fileType, mainTitleList, alternateUrlList,
fileSizeList);
listView.setAdapter(myAdapter);
}
});
} catch (Exception e) {
System.out.println("Exception Setting ListView Is:" + e);
e.printStackTrace();
}
} catch (IOException e) {
System.out.println("An error occurred in retrieveAllFiles:"+ e);
request.setPageToken(null);
}
} while (request.getPageToken() != null
&& request.getPageToken().length() > 0);
return result;
}
private static InputStream downloadFile(Drive service, String url) {
System.out.println("downloadFile is called service=="+service);
if (url != null && url.length() > 0) {
try {
System.out.println("downloadFile is called try");
HttpResponse resp =service.getRequestFactory().buildGetRequest(new GenericUrl(url)).execute();
System.out.println("resp.getContent()===="+resp.getContent());
return resp.getContent();
} catch (Exception e) {
System.out.println("Exception Is:"+e);
e.printStackTrace();
return null;
}
} else {
System.out.println("No Exception No Output");
return null;
}
}
}
This is code that I use to download File from google Drive
new AsyncTask<Void, Integer, Boolean>() {
#Override
protected Boolean doInBackground(Void... params) {
try {
File file = service.files().get("path in drive").execute();
java.io.File toFile = new java.io.File("where you want to store");
toFile.createNewFile();
HttpDownloadManager downloader = new HttpDownloadManager(file, toFile);
downloader.setListener(new HttpDownloadManager.FileDownloadProgressListener() {
public void downloadProgress(long bytesRead, long totalBytes) {
Log.i("chauster",totalBytes);
Log.i("chauster",bytesRead);
}
#Override
public void downloadFinished() {
// TODO Auto-generated method stub
}
#Override
public void downloadFailedWithError(Exception e) {
// TODO Auto-generated method stub
}
});
return downloader.download(service);
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
};
}.execute();
HttpDownloadManager.java
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpResponse;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.model.File;
import com.grandex.ShareInfomation.ShareData;
import com.grandex.ShareInfomation.ShareData.ToolTapState;
public class HttpDownloadManager {
private String donwloadUrl;
private String toFile;
private FileDownloadProgressListener listener;
private long totalBytes;
public void setListener(FileDownloadProgressListener listener) {
this.listener = listener;
}
public HttpDownloadManager(File sourceFile, java.io.File destinationFile) {
super();
this.donwloadUrl = sourceFile.getDownloadUrl();
this.toFile = destinationFile.toString();
this.totalBytes = sourceFile.getFileSize();
}
public static interface FileDownloadProgressListener {
public void downloadProgress(long bytesRead, long totalBytes);
public void downloadFinished();
public void downloadFailedWithError(Exception e);
}
public boolean download(Drive service) {
HttpResponse respEntity = null;
try {
// URL url = new URL(urlString);
respEntity = service.getRequestFactory()
.buildGetRequest(new GenericUrl(donwloadUrl)).execute();
InputStream in = respEntity.getContent();
if(totalBytes == 0) {
totalBytes = respEntity.getContentLoggingLimit();
}
try {
FileOutputStream f = new FileOutputStream(toFile) {
#Override
public void write(byte[] buffer, int byteOffset,
int byteCount) throws IOException {
// TODO Auto-generated method stub
super.write(buffer, byteOffset, byteCount);
}
}
};
byte[] buffer = new byte[1024];
int len1 = 0;
long bytesRead = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
if (listener != null) {
bytesRead += len1;
listener.downloadProgress(bytesRead, totalBytes);
}
}
f.close();
} catch (Exception e) {
if (listener != null) {
listener.downloadFailedWithError(e);
}
return false;
}
if (listener != null) {
listener.downloadFinished();
}
return true;
} catch (IOException ex) {
if (listener != null) {
listener.downloadFailedWithError(ex);
return false;
}
} finally {
if(respEntity != null) {
try {
respEntity.disconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return false;
}
}
Nowhere in your code are you setting the Authorization header.
You need something like
setRequestProperty("Authorization", "OAuth " + "***ACCESS_TOKEN***");
For any 401/403 errors it's well worth getting your request working on the Oauth. Try this out
Please check below code for download apk file from google drive
implementation 'com.google.android.material:material:1.0.0'
Add uses permission
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
Create a file provider
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path
name="external"
path="." />
<external-files-path
name="external_files"
path="." />
<files-path
name="files"
path="." />
Now declare the file provider inside the manifest
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_provider_paths" />
Add some value inside strings.xml file
<resources>
<string name="app_name">Download APK</string>
<string name="downloading">Downloading...</string>
<string name="title_file_download">APK is downloading</string>
<string name="storage_access_required">Storage access is required to downloading the file.</string>
<string name="storage_permission_denied">Storage permission request was denied.</string>
<string name="ok">OK</string>
Create a download controller
package com.hktpayment.mytmoney.pos.mauritius.util
import android.app.Dialog
import android.app.DownloadManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.util.Log
import android.widget.ProgressBar
import android.widget.Toast
import androidx.core.content.FileProvider
import com.hktpayment.mytmoney.pos.mauritius.BuildConfig
import com.hktpayment.mytmoney.pos.mauritius.R
import java.io.File
class DownloadController(
private val context: Context,
private val url: String,
private val progressBar: Dialog
) {
companion object {
private const val FILE_NAME = "SampleDownloadApp.apk"
private const val FILE_BASE_PATH = "file://"
private const val MIME_TYPE = "application/vnd.android.package-archive"
private const val PROVIDER_PATH = ".provider"
private const val APP_INSTALL_PATH = "application/vnd.android.package-
archive"
}
private lateinit var downloadManager: DownloadManager
fun enqueueDownload() {
var destination =
context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).toString()
+ "/"
destination += FILE_NAME
val uri = Uri.parse("$FILE_BASE_PATH$destination")
val file = File(destination)
if (file.exists()) file.delete()
downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as
DownloadManager
val downloadUri = Uri.parse(url)
val request = DownloadManager.Request(downloadUri)
request.setMimeType(MIME_TYPE)
request.setTitle(context.getString(R.string.title_file_download))
request.setDescription(context.getString(R.string.downloading))
// set destination
request.setDestinationUri(uri)
showInstallOption(destination, uri)
// Enqueue a new download and same the referenceId
downloadManager.enqueue(request)
Toast.makeText(context, context.getString(R.string.downloading),
Toast.LENGTH_LONG)
.show()
}
private fun showInstallOption(
destination: String,
uri: Uri
) {
// set BroadcastReceiver to install app when .apk is downloaded
progressBar.show()
val onComplete = object : BroadcastReceiver() {
override fun onReceive(
context: Context,
intent: Intent
) {
progressBar.dismiss()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
val contentUri = FileProvider.getUriForFile(
context,
BuildConfig.APPLICATION_ID + PROVIDER_PATH,
File(destination)
)
val install = Intent(Intent.ACTION_VIEW)
install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
install.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
install.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true)
install.data = contentUri
context.startActivity(install)
context.unregisterReceiver(this)
// finish()
} else {
val install = Intent(Intent.ACTION_VIEW)
install.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
install.setDataAndType(
uri,
APP_INSTALL_PATH
)
context.startActivity(install)
context.unregisterReceiver(this)
// finish()
}
}
}
context.registerReceiver(onComplete, IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE))
}
}
In this activity, we are checking storage permission first. If permission is granted than calling download function otherwise requesting for storage permission.
val apkUrl = "https://download .apk"
downloadController = DownloadController(this, apkUrl)
downloadController.enqueueDownload()
i am working on wallpaper app in which i am downloading image, but now i want to show download process while downloading a image.
what i want is: see this screenshot: http://www.techfeb.com/wp-content/uploads/2012/03/download-facebook-photos-on-android-smartphone-2.jpg
this is my code:
Utils.java
package info.androidhive.awesomewallpapers.util;
import info.androidhive.awesomewallpapers.R;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Random;
import android.annotation.SuppressLint;
import android.app.WallpaperManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.os.Environment;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;
import android.widget.Toast;
#SuppressLint("NewApi")
public class Utils {
private String TAG = Utils.class.getSimpleName();
private Context _context;
private PrefManager pref;
// constructor
public Utils(Context context) {
this._context = context;
pref = new PrefManager(_context);
}
/*
* getting screen width
*/
#SuppressWarnings("deprecation")
public int getScreenWidth() {
int columnWidth;
WindowManager wm = (WindowManager) _context
.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
final Point point = new Point();
try {
display.getSize(point);
} catch (java.lang.NoSuchMethodError ignore) {
// Older device
point.x = display.getWidth();
point.y = display.getHeight();
}
columnWidth = point.x;
return columnWidth;
}
public void saveImageToSDCard(Bitmap bitmap) {
String dirname = "/Amazing Wallpapers/";
File myDir = new File(Environment
.getExternalStorageDirectory().getPath() + dirname);
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Wallpaper-" +n+".jpg";
File file = new File(myDir, fname);
if (file.exists())
file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
Toast.makeText(
_context,
_context.getString(R.string.toast_saved).replace("#",
"\"" + pref.getGalleryName() + "\""),
Toast.LENGTH_LONG).show();
Log.d(TAG, "Wallpaper saved to:" + file.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(_context,
_context.getString(R.string.toast_saved_failed),
Toast.LENGTH_SHORT).show();
}
}
public void setAsWallpaper(Bitmap bitmap) {
try {
WallpaperManager wm = WallpaperManager.getInstance(_context);
wm.setBitmap(bitmap);
Toast.makeText(_context,
_context.getString(R.string.toast_wallpaper_set),
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(_context,
_context.getString(R.string.toast_wallpaper_set_failed),
Toast.LENGTH_SHORT).show();
}
}
}
FullScreenActivity.java
package info.androidhive.awesomewallpapers;
import info.androidhive.awesomewallpapers.app.AppController;
import info.androidhive.awesomewallpapers.picasa.model.Wallpaper;
import info.androidhive.awesomewallpapers.util.Utils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageContainer;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.android.volley.toolbox.JsonObjectRequest;
public class FullScreenViewActivity extends Activity implements OnClickListener {
private static final String TAG = FullScreenViewActivity.class
.getSimpleName();
public static final String TAG_SEL_IMAGE = "selectedImage";
private Wallpaper selectedPhoto;
private ImageView fullImageView;
private LinearLayout llSetWallpaper, llDownloadWallpaper;
private Utils utils;
private ProgressBar pbLoader;
// Picasa JSON response node keys
private static final String TAG_ENTRY = "entry",
TAG_MEDIA_GROUP = "media$group",
TAG_MEDIA_CONTENT = "media$content", TAG_IMG_URL = "url",
TAG_IMG_WIDTH = "width", TAG_IMG_HEIGHT = "height";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen_image);
fullImageView = (ImageView) findViewById(R.id.imgFullscreen);
llSetWallpaper = (LinearLayout) findViewById(R.id.llSetWallpaper);
llDownloadWallpaper = (LinearLayout) findViewById(R.id.llDownloadWallpaper);
pbLoader = (ProgressBar) findViewById(R.id.pbLoader);
// hide the action bar in fullscreen mode
getActionBar().hide();
utils = new Utils(getApplicationContext());
// layout click listeners
llSetWallpaper.setOnClickListener(this);
llDownloadWallpaper.setOnClickListener(this);
// setting layout buttons alpha/opacity
llSetWallpaper.getBackground().setAlpha(70);
llDownloadWallpaper.getBackground().setAlpha(70);
Intent i = getIntent();
selectedPhoto = (Wallpaper) i.getSerializableExtra(TAG_SEL_IMAGE);
// check for selected photo null
if (selectedPhoto != null) {
// fetch photo full resolution image by making another json request
fetchFullResolutionImage();
} else {
Toast.makeText(getApplicationContext(),
getString(R.string.msg_unknown_error), Toast.LENGTH_SHORT)
.show();
}
}
/**
* Fetching image fullresolution json
* */
private void fetchFullResolutionImage() {
String url = selectedPhoto.getPhotoJson();
// show loader before making request
pbLoader.setVisibility(View.VISIBLE);
llSetWallpaper.setVisibility(View.GONE);
llDownloadWallpaper.setVisibility(View.GONE);
// volley's json obj request
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET, url,
null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG,
"Image full resolution json: "
+ response.toString());
try {
// Parsing the json response
JSONObject entry = response
.getJSONObject(TAG_ENTRY);
JSONArray mediacontentArry = entry.getJSONObject(
TAG_MEDIA_GROUP).getJSONArray(
TAG_MEDIA_CONTENT);
JSONObject mediaObj = (JSONObject) mediacontentArry
.get(0);
String fullResolutionUrl = mediaObj
.getString(TAG_IMG_URL);
// image full resolution widht and height
final int width = mediaObj.getInt(TAG_IMG_WIDTH);
final int height = mediaObj.getInt(TAG_IMG_HEIGHT);
Log.d(TAG, "Full resolution image. url: "
+ fullResolutionUrl + ", w: " + width
+ ", h: " + height);
ImageLoader imageLoader = AppController
.getInstance().getImageLoader();
// We download image into ImageView instead of
// NetworkImageView to have callback methods
// Currently NetworkImageView doesn't have callback
// methods
imageLoader.get(fullResolutionUrl,
new ImageListener() {
#Override
public void onErrorResponse(
VolleyError arg0) {
Toast.makeText(
getApplicationContext(),
getString(R.string.msg_wall_fetch_error),
Toast.LENGTH_LONG).show();
}
#Override
public void onResponse(
ImageContainer response,
boolean arg1) {
if (response.getBitmap() != null) {
// load bitmap into imageview
fullImageView
.setImageBitmap(response
.getBitmap());
adjustImageAspect(width, height);
// hide loader and show set &
// download buttons
pbLoader.setVisibility(View.GONE);
llSetWallpaper
.setVisibility(View.VISIBLE);
llDownloadWallpaper
.setVisibility(View.VISIBLE);
}
}
});
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
getString(R.string.msg_unknown_error),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
// unable to fetch wallpapers
// either google username is wrong or
// devices doesn't have internet connection
Toast.makeText(getApplicationContext(),
getString(R.string.msg_wall_fetch_error),
Toast.LENGTH_LONG).show();
}
});
// Remove the url from cache
AppController.getInstance().getRequestQueue().getCache().remove(url);
// Disable the cache for this url, so that it always fetches updated
// json
jsonObjReq.setShouldCache(false);
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
/**
* Adjusting the image aspect ration to scroll horizontally, Image height
* will be screen height, width will be calculated respected to height
* */
#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
private void adjustImageAspect(int bWidth, int bHeight) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
if (bWidth == 0 || bHeight == 0)
return;
int sHeight = 0;
if (android.os.Build.VERSION.SDK_INT >= 13) {
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
sHeight = size.y;
} else {
Display display = getWindowManager().getDefaultDisplay();
sHeight = display.getHeight();
}
int new_width = (int) Math.floor((double) bWidth * (double) sHeight
/ (double) bHeight);
params.width = new_width;
params.height = sHeight;
Log.d(TAG, "Fullscreen image new dimensions: w = " + new_width
+ ", h = " + sHeight);
fullImageView.setLayoutParams(params);
}
/**
* View click listener
* */
#Override
public void onClick(View v) {
Bitmap bitmap = ((BitmapDrawable) fullImageView.getDrawable())
.getBitmap();
switch (v.getId()) {
// button Download Wallpaper tapped
case R.id.llDownloadWallpaper:
utils.saveImageToSDCard(bitmap);
break;
// button Set As Wallpaper tapped
case R.id.llSetWallpaper:
utils.setAsWallpaper(bitmap);
break;
default:
break;
}
}
}
A very good toturial to do so here..
http://www.androidbegin.com/tutorial/android-download-image-from-url/\
A snippet of the code from the site is below:
private class DownloadImage extends AsyncTask<String, Void, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Download Image Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Bitmap doInBackground(String... URL) {
String imageURL = URL[0];
Bitmap bitmap = null;
try {
// Download Image from URL
InputStream input = new java.net.URL(imageURL).openStream();
// Decode Bitmap
bitmap = BitmapFactory.decodeStream(input);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
// Set the bitmap into ImageView
image.setImageBitmap(result);
// Close progressdialog
mProgressDialog.dismiss();
}
}
You can use ProgressDialog within the onCreate method.
mProgressDialog = new ProgressDialog(YourActivity.this);
You can then add other attributes like a message and so on like this:
mProgressDialog.setMessage("A message");
You can also add listeners like this:
mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
// Do stuff on Cancel
}
});
Check this link:
Download a file with Android, and showing the progress in a ProgressDialog
i am new in android and i am making a application to download the file from local server and i almost done.But now i want to add progress bar in this code and i am trying to do it. can anyone help me out. just help me if you can dont leave other comments like grammer mistake and other
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import org.apache.http.util.ByteArrayBuffer;
import android.support.v7.app.ActionBarActivity;
import android.widget.Button;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends ActionBarActivity
{
Button b1;
String FileDownloadPath="http://192.168.1.25/dinesh/di.mp3";
//String FileSavePath="/dinesh2/lecture3.pdf";
//String DownloadUrl = "http://myexample.com/android/";
String fileName = "di.mp3";
//myFile = new File(path,"/mysdfile.xml");
ProgressDialog dialog=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener(){
public void onClick(View arg0)
{
dialog=ProgressDialog.show(MainActivity.this,"", "downloading",true);
new Thread(new Runnable()
{
public void run()
{
downlaodfile(FileDownloadPath,fileName);
}
}).start();
}
});
}
public void downlaodfile(String FileDownloadPath, String fileName) {
try {
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/sdcard/myclock/databases");
if(dir.exists() == false){
dir.mkdirs();
}
URL url = new URL("http://192.168.1.25/dinesh/di.mp3");
File file = new File(dir,fileName);
long startTime = System.currentTimeMillis();
Log.d("DownloadManager" , "download url:" +url);
Log.d("DownloadManager" , "download file name:" + fileName);
URLConnection uconn = url.openConnection();
/* uconn.setReadTimeout(TIMEOUT_CONNECTION);
uconn.setConnectTimeout(TIMEOUT_SOCKET);*/
InputStream is = uconn.getInputStream();
BufferedInputStream bufferinstream = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(5000);
int current = 0;
while((current = bufferinstream.read()) != -1){
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream( file);
fos.write(baf.toByteArray());
fos.flush();
fos.close();
Log.d("DownloadManager" , "download ready in" + ((System.currentTimeMillis() - startTime)/1000) + "sec");
int dotindex = fileName.lastIndexOf('.');
if(dotindex>=0){
fileName = fileName.substring(0,dotindex);
}
}
catch(IOException e) {
Log.d("DownloadManager" , "Error:" + e);
}
catch(Exception e )
{
e.printStackTrace();
}
}
private void hideProgressIndicator() {
// TODO Auto-generated method stub
runOnUiThread(new Runnable(){
public void run()
{
dialog.dismiss();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
You should use AsyncTask<...> for your downloading process and use ProgressDialog.
private class ClassName extends AsyncTask<String, Void, String>
{
ProgressDialog progressDialog;
#Override
protected void onPreExecute()
{
progressDialog = ProgressDialog.show(context, "Downloading", "Please Wait...");
}
#Override
protected String doInBackground(String... params)
{
//Your downloading code here
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
progressDialog.dismiss();
//dismiss the progress dialog in onPost and do remaining stuff after downloading....
}
}
hope this will help you...
I am trying to upload a sqlite database file to dropbox. This is my code:
public void uploadDb(){
File public_db_file = null;
try {
public_db_file = writeDbToPublicDirectory();
} catch (IOException e2) {
e2.printStackTrace();
}
DbxFileSystem dbxFs = null;
try {
dbxFs = DbxFileSystem.forAccount(mAccount);
} catch (Unauthorized e1) {
e1.printStackTrace();
}
DbxFile testFile = null;
try {
testFile = dbxFs.create(new DbxPath("database_sync.txt"));
} catch (InvalidPathException e1) {
e1.printStackTrace();
} catch (DbxException e1) {
e1.printStackTrace();
}
try {
testFile.writeFromExistingFile(public_db_file, false);
} catch (IOException e) {
e.printStackTrace();
} finally {
testFile.close();
}
}
EDIT (More code)
This function copies my database from the app private dir to a public dir so that I can upload it:
private File writeDbToPublicDirectory() throws IOException {
// TODO Auto-generated method stub
File sd = Environment.getExternalStorageDirectory();
File backupDB = null;
if (sd.canWrite()) {
String backupDBPath = "copied_database.db";
File currentDB = context.getDatabasePath("private_database");
backupDB = new File(sd, backupDBPath);
if (currentDB.exists()) {
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
}
}
return backupDB;
}
The problem is that when I check on my device dropbox, the file size is 0 bytes. The file is created on dropbox, but my database data is not. What am I doing wrong? Thank you in advance
EDIT
I have decided that using Google Drive may be a better option, but I can only upload text files by using the sample applications. Is there any good tutorial or resource that I can use to upload a sqlite database file? I am really badly stuck on this. Please help me with either of these, thank you in advance
I was able to backup the database using Google Drive API. I have used the byte array to copy the contents. Following is the Activity code, which creates a new file on Google Drive root folder and copies the sqlite db content. I've added comments wherever required. Let me know whether it helps.
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.drive.Contents;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveFile;
import com.google.android.gms.drive.DriveApi.ContentsResult;
import com.google.android.gms.drive.DriveFolder.DriveFileResult;
import com.google.android.gms.drive.MetadataChangeSet;
import android.app.Activity;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.webkit.MimeTypeMap;
public class MainActivity extends Activity implements ConnectionCallbacks, OnConnectionFailedListener {
private static final String TAG = "MainActivity";
private GoogleApiClient api;
private boolean mResolvingError = false;
private DriveFile mfile;
private static final int DIALOG_ERROR_CODE =100;
private static final String DATABASE_NAME = "person.db";
private static final String GOOGLE_DRIVE_FILE_NAME = "sqlite_db_backup";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create the Drive API instance
api = new GoogleApiClient.Builder(this).addApi(Drive.API).addScope(Drive.SCOPE_FILE).
addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
}
#Override
public void onStart() {
super.onStart();
if(!mResolvingError) {
api.connect(); // Connect the client to Google Drive
}
}
#Override
public void onStop() {
super.onStop();
api.disconnect(); // Disconnect the client from Google Drive
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.v(TAG, "Connection failed");
if(mResolvingError) { // If already in resolution state, just return.
return;
} else if(result.hasResolution()) { // Error can be resolved by starting an intent with user interaction
mResolvingError = true;
try {
result.startResolutionForResult(this, DIALOG_ERROR_CODE);
} catch (SendIntentException e) {
e.printStackTrace();
}
} else { // Error cannot be resolved. Display Error Dialog stating the reason if possible.
ErrorDialogFragment fragment = new ErrorDialogFragment();
Bundle args = new Bundle();
args.putInt("error", result.getErrorCode());
fragment.setArguments(args);
fragment.show(getFragmentManager(), "errordialog");
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == DIALOG_ERROR_CODE) {
mResolvingError = false;
if(resultCode == RESULT_OK) { // Error was resolved, now connect to the client if not done so.
if(!api.isConnecting() && !api.isConnected()) {
api.connect();
}
}
}
}
#Override
public void onConnected(Bundle connectionHint) {
Log.v(TAG, "Connected successfully");
/* Connection to Google Drive established. Now request for Contents instance, which can be used to provide file contents.
The callback is registered for the same. */
Drive.DriveApi.newContents(api).setResultCallback(contentsCallback);
}
final private ResultCallback<ContentsResult> contentsCallback = new ResultCallback<ContentsResult>() {
#Override
public void onResult(ContentsResult result) {
if (!result.getStatus().isSuccess()) {
Log.v(TAG, "Error while trying to create new file contents");
return;
}
String mimeType = MimeTypeMap.getSingleton().getExtensionFromMimeType("db");
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle(GOOGLE_DRIVE_FILE_NAME) // Google Drive File name
.setMimeType(mimeType)
.setStarred(true).build();
// create a file on root folder
Drive.DriveApi.getRootFolder(api)
.createFile(api, changeSet, result.getContents())
.setResultCallback(fileCallback);
}
};
final private ResultCallback<DriveFileResult> fileCallback = new ResultCallback<DriveFileResult>() {
#Override
public void onResult(DriveFileResult result) {
if (!result.getStatus().isSuccess()) {
Log.v(TAG, "Error while trying to create the file");
return;
}
mfile = result.getDriveFile();
mfile.openContents(api, DriveFile.MODE_WRITE_ONLY, null).setResultCallback(contentsOpenedCallback);
}
};
final private ResultCallback<ContentsResult> contentsOpenedCallback = new ResultCallback<ContentsResult>() {
#Override
public void onResult(ContentsResult result) {
if (!result.getStatus().isSuccess()) {
Log.v(TAG, "Error opening file");
return;
}
try {
FileInputStream is = new FileInputStream(getDbPath());
BufferedInputStream in = new BufferedInputStream(is);
byte[] buffer = new byte[8 * 1024];
Contents content = result.getContents();
BufferedOutputStream out = new BufferedOutputStream(content.getOutputStream());
int n = 0;
while( ( n = in.read(buffer) ) > 0 ) {
out.write(buffer, 0, n);
}
in.close();
mfile.commitAndCloseContents(api, content).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status result) {
// Handle the response status
}
});
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
private File getDbPath() {
return this.getDatabasePath(DATABASE_NAME);
}
#Override
public void onConnectionSuspended(int cause) {
// TODO Auto-generated method stub
Log.v(TAG, "Connection suspended");
}
public void onDialogDismissed() {
mResolvingError = false;
}
public static class ErrorDialogFragment extends DialogFragment {
public ErrorDialogFragment() {}
public Dialog onCreateDialog(Bundle savedInstanceState) {
int errorCode = this.getArguments().getInt("error");
return GooglePlayServicesUtil.getErrorDialog(errorCode, this.getActivity(), DIALOG_ERROR_CODE);
}
public void onDismiss(DialogInterface dialog) {
((MainActivity) getActivity()).onDialogDismissed();
}
}
}
I modified #Manish Mulimani's code. I make use of some modules in com.google.android.gms.drive.sample.demo which is available from Google Drive API Website. The modules are BaseDemoActivity, ApiClientAsyncTask and EditContentsActivity. Here are the code.
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.webkit.MimeTypeMap;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveApi;
import com.google.android.gms.drive.DriveContents;
import com.google.android.gms.drive.DriveFile;
import com.google.android.gms.drive.DriveFolder;
import com.google.android.gms.drive.MetadataChangeSet;
import com.google.android.gms.drive.DriveApi.DriveContentsResult;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class gDriveActivity extends BaseDemoActivity {
private final static String TAG = "gDriveActivity";
#Override
public void onConnected(Bundle connectionHint) {
super.onConnected(connectionHint);
// create new contents resource.
Drive.DriveApi.newDriveContents(getGoogleApiClient()).setResultCallback(driveContentsCallback);
}
final private ResultCallback<DriveApi.DriveContentsResult> driveContentsCallback =
new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
//if failure
showMessage("Error while trying to create new file contents");
return;
}
//change the metadata of the file. by setting title, setMimeType.
String mimeType = MimeTypeMap.getSingleton().getExtensionFromMimeType("db");
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle("mydb")
.setMimeType(mimeType)
.build();
Drive.DriveApi.getAppFolder(getGoogleApiClient())
.createFile(getGoogleApiClient(), changeSet, result.getDriveContents()).setResultCallback(fileCallBack);
}
};
final ResultCallback<DriveFolder.DriveFileResult> fileCallBack = new ResultCallback<DriveFolder.DriveFileResult>() {
#Override
public void onResult(DriveFolder.DriveFileResult driveFileResult) {
if (!driveFileResult.getStatus().isSuccess()) {
Log.v(TAG, "Error while trying to create the file");
return;
}
//Initialize mFile to be processed in AsyncTask
DriveFile mfile = driveFileResult.getDriveFile();
new EditContentsAsyncTask(gDriveActivity .this).execute(mfile);
}
};
public class EditContentsAsyncTask extends ApiClientAsyncTask<DriveFile, Void, Boolean> {
public EditContentsAsyncTask(Context context) {
super(context);
}
#Override
protected Boolean doInBackgroundConnected(DriveFile... args) {
DriveFile file = args[0];
try {
DriveContentsResult driveContentsResult = file.open(
getGoogleApiClient(), DriveFile.MODE_WRITE_ONLY, null).await();
if (!driveContentsResult.getStatus().isSuccess()) {
return false;
}
DriveContents driveContents = driveContentsResult.getDriveContents();
//edit the outputStream
DatabaseHandler db = new DatabaseHandler(gDriveActivity .this);
String inFileName = getApplicationContext().getDatabasePath(db.getDatabaseName()).getPath();
FileInputStream is = new FileInputStream(inFileName);
BufferedInputStream in = new BufferedInputStream(is);
byte[] buffer = new byte[8 * 1024];
BufferedOutputStream out = new BufferedOutputStream(driveContents.getOutputStream());
int n = 0;
while ((n = in.read(buffer)) > 0) {
out.write(buffer, 0, n);
}
in.close();
com.google.android.gms.common.api.Status status =
driveContents.commit(getGoogleApiClient(), null).await();
return status.getStatus().isSuccess();
} catch (IOException e) {
Log.e(TAG, "IOException while appending to the output stream", e);
}
return false;
}
#Override
protected void onPostExecute(Boolean result) {
if (!result) {
showMessage("Error while editing contents");
return;
}
showMessage("Successfully edited contents");
}
}
}
I think you could use the Storage API
https://developer.android.com/guide/topics/providers/document-provider.html
A useful tutorial on
http://www.techotopia.com/index.php/An_Android_Storage_Access_Framework_Example