I am downloading audio files from a parse server. The results after running the code below is that when the client clicks the notification, it plays. However, when the client closes the music player, and opens it back up, it is no longer listed. My question is, where is this file located? I have seen methods for setting the external storage location, but I would like for it to download to the internal storage with the other downloads. How can I accomplish this?
private class DownloadFileTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
Toast.makeText(getActivity(), getString(R.string.downloading), Toast.LENGTH_SHORT).show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... urls) {
String currentSong = urls[0];
try {
downloadManager = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(currentSong);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
downloadManager.enqueue(request);
}
catch (Exception e) {
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
return currentSong;
}
#Override
protected void onPostExecute(String s) {
Toast.makeText(getActivity(), getString(R.string.download_complete), Toast.LENGTH_SHORT).show();
super.onPostExecute(s);
}
Related
I have this application wherein a feature of it will allow you to download a video. The download part is working, but I need to do another function right after the download has been completed. Currently, I am using AsyncTask, but whenever I try to toast on the PostExecute, nothing happens. I'd like to call another function to encrypt then delete the original file after the download has been completed.
And btw, the encryption part is working as well. The only thing I need is something that will allow me to know if the download has been completed.
This is the code where in I'll be downloading the file from a URL. But, I need to know if the download is complete to execute the AsyncTask
public void downloadTutorial() throws Exception {
myURL = "";
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(myURL));
request.setTitle(injuryType + " Video");
request.setDescription("File is being downloaded...");
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
String fileName = URLUtil.guessFileName(myURL, null, MimeTypeMap.getFileExtensionFromUrl(myURL));
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
DownloadManager manager = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
//if the download is complete execute this
//new JSONTask().execute();
}
The code of the AsyncTask is:
public class JSONTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
try {
Encrypter.encrypt(injuryType);
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Toast.makeText(getActivity(), "Download Done", Toast.LENGTH_SHORT).show();
}
}
So you want to access the file after downloading the file using Download Manager.
First you will need a Broadcast receiver which will inform you after downloading a file.
In Manifest :
<receiver
android:name="<your download receiver class extends Broadcast receiver>"
android:enabled="true"
android:protectionLevel= "signature"
>
<intent-filter>
<action android:name="android.intent.action.DOWNLOAD_COMPLETE" />
</intent-filter>
</receiver>
Now you will need to save the download reference id in sharedpref or database
Now save this download reference id in your sharedpref or database so that we can get it in broadcast receiver.
Uri uri = Uri.parse(content.url);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setDescription("Your App Title").setTitle(<file title>);
request.setDestinationInExternalFilesDir(getActivity(), Environment.DIRECTORY_DOWNLOADS, <file title>);
request.setVisibleInDownloadsUi(false); //the content will not shown in Download Manager App
mydownlodreference = downloadManager.enqueue(request);
Now the main part, in onReceive of BroadcastReceiver class
#Override
public void onReceive(Context context, Intent intent) {
DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
long reference = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
// take out the reference id from your sharedpref or database and check that referenceId with this reference
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(reference);
Cursor c = downloadManager.query(query);
c.moveToFirst();
int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
int status = c.getInt(columnIndex);
int fileNameIndex = c.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME);
String filePath = c.getString(fileNameIndex);
if (status == DownloadManager.STATUS_SUCCESSFUL) {
// do whatever you want here
}
}
I am trying to download file from server and store it in Storage but the code gives error - Unable to create directory. Please check for error
Task - File gets downloaded from server and then it is loaded in webview in android.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
try {
webView.loadUrl("file://" + Environment.getExternalStorageDirectory() + "/sponsors/"+ "dddd.html");
}
catch (Exception e)
{
Toast.makeText(MainActivity.this, "File Doesn't Exist", Toast.LENGTH_SHORT).show();
}
try {
myDownloadLast("http://192.168.76.1:8084/MyTest/dddd.html");
}
catch (Exception e)
{
Toast.makeText(this, e.getMessage()+"\n"+e.getCause(), Toast.LENGTH_SHORT).show();
}
}
public void myDownloadLast(String myURL) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(myURL));
request.setTitle("Updating TimeTable");
request.setDescription("Please Wait");
//request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
String nameOfFile = URLUtil.guessFileName(myURL, null, MimeTypeMap.getFileExtensionFromUrl(myURL));
File myFile = new File(String.valueOf(Environment.getExternalStoragePublicDirectory("/sponsors/")));
if(!myFile.exists()){
myFile.mkdir();
}
try {
request.setDestinationInExternalPublicDir(String.valueOf(myFile), nameOfFile);
}
catch (Exception e)
{
Toast.makeText(this, e.getMessage()+"\n"+e.getCause(), Toast.LENGTH_SHORT).show();
}
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
BroadcastReceiver onComplete = new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
//Toast.makeText(getActivity(), "Download Complete", Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "Update Complete\nFor Best Performance\nRestart The App", Toast.LENGTH_SHORT).show();
}
};
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
Your problem can be related to a few suspects
Make sure to have permissions on the Android Manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Also, refer to the external directory with the following :
String name = Environment.getExternalStorageDirectory().getAbsolutePath() + "/DirectoryNameYouWant/" ;
I am testing the Drive API for Android to upload a file that can show uploaded progress and be able to resume the upload if it fails (Files size > 30 MB.)
With the following questions:
Uploading Downloading of large size file to Google Drive giving error,
Upload progress listener not fired (Google drive API)
I was able to get the upload progress and they mention those are resumable uploads. However, I don't see any code that looks for an upload error and resume logic, thus if I kill the application and "resume" the upload, it simply starts from the beginning.
This is my code:
public class DriveScreen extends BaseDriveActivity {
private Drive service;
private Context context;
#Override
public void onConnected(Bundle connectionHint) {
super.onConnected(connectionHint);
context = this;
//https://stackoverflow.com/questions/17429798/usingoauth2-deprecated
GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(this, Arrays.asList(DriveScopes.DRIVE_FILE));
credential.setSelectedAccountName("accountNameHERE");
service = new Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential).build();
UploadFile();
}
public void UploadFile() {
AsyncTask<Void, Long, String> task = new AsyncTask<Void, Long, String>() {
java.io.File fileContent;
FileContent mediaContent;
com.google.api.services.drive.model.File body;
com.google.api.services.drive.model.File file;
private ProgressDialog mDialog;
long mFileLen;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
mDialog = new ProgressDialog(context);
mDialog.setMax(100);
mDialog.setMessage("Uploading ");
mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mDialog.setProgress(0);
mDialog.setButton("Cancel", new OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
});
mDialog.show();
}
class FileUploadProgressListener implements MediaHttpUploaderProgressListener {
#Override
public void progressChanged(MediaHttpUploader uploader) throws IOException {
Log.d("Percent ", String.valueOf(uploader.getProgress()));
switch (uploader.getUploadState()) {
case INITIATION_STARTED:
System.out.println("Initiation Started");
break;
case INITIATION_COMPLETE:
System.out.println("Initiation Completed");
break;
case MEDIA_IN_PROGRESS:
System.out.println("Upload in progress");
System.out.println("Upload percentage: " + uploader.getProgress());
mDialog.setProgress((int) (uploader.getProgress()*100));
break;
case MEDIA_COMPLETE:
System.out.println("Upload Completed!");
break;
case NOT_STARTED:
System.out.println("Upload Not Started!");
break;
}
}
}
#Override
protected String doInBackground(Void... arg0) {
try {
File folder = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES
);
File UPLOAD_FILE = new File(folder, "filePathHERE");
fileContent = new File(folder, "filePathHERE");
mFileLen = fileContent.length();
InputStreamContent mediaContent2 = new InputStreamContent("application/zip", new FileInputStream(UPLOAD_FILE));
mediaContent2.setLength(UPLOAD_FILE.length());
body = new com.google.api.services.drive.model.File();
body.setTitle(fileContent.getName());
body.setMimeType("application/zip");
//String parentId = null;
//int x = Files.List.setQ("mimeType = 'application/vnd.google-apps.folder' and title = 'ShareHim'");
//body.setParents(Arrays.asList(new ParentReference().setId(uploadFile.getFileHostFolderId())));
Files.Insert mInsert = service.files().insert(body, mediaContent2);
if(mFileLen > 5 * 1024 * 1024)
{
MediaHttpUploader uploader = mInsert.getMediaHttpUploader();
uploader.setDirectUploadEnabled(false);
uploader.setChunkSize(MediaHttpUploader.MINIMUM_CHUNK_SIZE);
uploader.setProgressListener(new FileUploadProgressListener());
file = mInsert.execute();
if (file != null) {
}
}
else {
mInsert.execute();
}
} catch (UserRecoverableAuthIOException e) {
System.out.println("login error");
Log.d("Error", "not login " + e);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
mDialog.dismiss();
};
};
task.execute();
}
}
Now, it is uploading by chunks, but how can we resume the upload from the last chunk sent. My first impression after watching Google Drive talks on youtube was that the resumable upload was handled automatically, but it doesn't seem to be the case.
Am I approaching this the wrong way? Is it worth considering using a DriveSyncAdapter to upload a file as an alternative? (Sorry for the bad code, this is just a test)
It looks like you are using the Java REST-ful API. If you use the Android-specific API, this is all handled for you. Just hand over the file, and the API will do resumable upload as appropriate. See creating files.
I am Trying to upload jpg Image to FTP server using SimpleFTP.
Following is My Code:
try
{
SimpleFTP ftp = new SimpleFTP();
ftp.connect("URL", 21, "User Name", "Password");
// Set binary mode.
ftp.bin();
// Change to a new working directory on the FTP server.
ftp.cwd("/demo1/RChatAPI/usrPhotos/");
// Upload some files.
ftp.stor(new File("/mnt/sdcard/aaa.jpg"));
// Quit from the FTP server.
ftp.disconnect();
}
catch (IOException e)
{
Log.v("Upload","Error Is:"+e);
}
And I got following error java.lang.NoClassDefFoundError
Have you included this jar to your lib folder?
Finally I Got the solution Of My Question.
public class MainActivity extends Activity
{
Button b1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0)
{
UploadVideo async = new UploadVideo();
async.execute();
}
});
}
class UploadVideo extends AsyncTask<String, Integer, String>
{
#Override
protected String doInBackground(String... params)
{
// ftpClient=uploadingFilestoFtp();
try
{
SimpleFTP ftp = new SimpleFTP();
ftp.connect("Your URL", 21, "User Name", "Password");
ftp.bin();
// Change to a new working directory on the FTP server.
ftp.cwd("/demo1/RChatAPI/usrPhotos/");
// Upload some files.
ftp.stor(new File("mnt/sdcard/aaa.jpg"));
// Quit from the FTP server.
ftp.disconnect();
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
// dialog.show();
}
#Override
protected void onPostExecute(String result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
Toast.makeText(MainActivity.this, "sent", Toast.LENGTH_LONG).show();
}
}
}
Thanks alot!
I need to deploy and update various enterprise applications to Android devices given to a limited number of users.
These applications are not supposed to be published on Google Play but must be distributed via a separate channel.
What I need to do is an "enterprise package manager" application to automatically check for new apps/updates and automatically trigger installation of new or updated APKs without asking user consent first.
I know that, by design, Android doesn't allow 3rd party applications to interact with installed applications. I also know that rooted phones don't have this problem because you can inject any APK into the device.
If I cook a ROM (even based on CWM) with the "enterprise package manager" installed as system application, but without su binary (it's still an enterprise phone...), will that program be able to install new apps automatically?
How am I supposed to install an application without asking for consent? I mean, I need a basic code sample and permissions, if required
Anyway, do system apps run as root user? I remember so
If you want to check for your application which is on somewhere on your server you have to check for Update in every 24 hour once, if there is any update available then it will navigate to the async task where your updated version build will get installed
public void checkforUpdate() {
/* Get Last Update Time from Preferences */
SharedPreferences prefs = getPreferences(0);
lastUpdateTime = prefs.getLong("lastUpdateTime", 0);
if ((lastUpdateTime + CommonString.timeCheckDuration) < System.currentTimeMillis() && System.currentTimeMillis()>lastUpdateTime) {
// Asynch task
new VersionCheckTask().execute();
}
else{
// do nothing
}
}
now it will navigate to:
private class VersionCheckTask extends AsyncTask<Void, Void, Void> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
try {
progressDialog = new ProgressDialog(Login.this, android.R.style.Theme_Holo_Light_Dialog);
//progressDialog.setTitle("AppName");
progressDialog.setMessage("Checking for updates...");
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(true);
progressDialog.show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected Void doInBackground(Void... params) {
/**
* Simulates a background job.
*/
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
HashMap<String, String> map = new HashMap<String, String>();
map.put("build",CommonString.buildVersion);
map.put("en", CommonString.en);
responce = CommonFunction.PostRequest("updateCheck", map);
return null;
}
#Override
protected void onPostExecute(Void result) {
if (progressDialog != null && progressDialog.isShowing())
progressDialog.dismiss();
if(!CommonFunction.isNetworkAvailable()){
Toast.makeText(ClaimColonyApplication.getAppContext(), CommonString.NO_NETWORK, Toast.LENGTH_SHORT).show();
return;
}
ParseUpdateResponse(responce);
if(rCodeUpdate == 100 && ApkLink.length() >0){
new AlertDialog.Builder(Login.this,android.R.style.Theme_Holo_Light_Dialog)
.setIcon(R.drawable.ic_launcher)
.setTitle("Update Available")
.setMessage(""+UpdateMessage)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//User clicked OK so do some stuff
new VersionCheckTaskDialog().execute();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//User clicked Cancel
finish();
}
})
.show();
}else{
if(rCodeUpdate == 100){
lastUpdateTime = System.currentTimeMillis();
SharedPreferences.Editor editor = getPreferences(0).edit();
editor.putLong("lastUpdateTime", lastUpdateTime);
editor.commit();
}
}
super.onPostExecute(result);
}
}
private class VersionCheckTaskDialog extends AsyncTask<Void, Void, Void> {
ProgressDialog progressDialogUpdate;
#Override
protected void onPreExecute() {
super.onPreExecute();
try {
progressDialogUpdate = new ProgressDialog(Login.this, android.R.style.Theme_Holo_Light_Dialog);
//progressDialog.setTitle("AppName");
progressDialogUpdate.setMessage("Fetching updates...");
progressDialogUpdate.setCancelable(false);
progressDialogUpdate.setIndeterminate(true);
progressDialogUpdate.show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected Void doInBackground(Void... params) {
/**
* Simulates a background job.
*/
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "pdf");
folder.mkdir();
File file = new File(folder, "AppName."+"apk");
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
/**
* replace url to ApkLink
*/
//DownloadFile(ApkLink, file);
DownloadFile("URL", file);
return null;
}
#Override
protected void onPostExecute(Void result) {
if (progressDialogUpdate != null && progressDialogUpdate.isShowing())
progressDialogUpdate.dismiss();
if(!CommonFunction.isNetworkAvailable()){
Toast.makeText(ClaimColonyApplication.getAppContext(), CommonString.NO_NETWORK, Toast.LENGTH_SHORT).show();
return;
}
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/pdf/" + "AppName.apk")), "application/vnd.android.package-archive");
startActivity(intent);
lastUpdateTime = System.currentTimeMillis();
SharedPreferences.Editor editor = getPreferences(0).edit();
editor.putLong("lastUpdateTime", lastUpdateTime);
editor.commit();
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("Exception in start intent for launch app-------: "+e.toString());
e.printStackTrace();
}
super.onPostExecute(result);
}
}
I am checking for update once in 24 hours, if there is any update available then it will show pop up to upgrade your application otherwise will save your last checking time in Preferences.
Now this will allow you to update and install your application and this will check for next update after 24 hours, you may need to work on conditions to check for update. Please change name of your .apk file and URL.
You will need following permissions:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Best of luck.