Unable to create directory in Android Error - android

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/" ;

Related

How to download file from Google Drive with link in Android?

I want to download file from google drive for which I am using dependency that is compile 'com.google.android.gms:play-services:8.4.0' and using this I am able to get link from meta data from below example.
mFileId = (DriveId) data.getParcelableExtra(
OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
final DriveFile file = Drive.DriveApi.getFile(mGoogleApiClient, mFileId);
new Thread(new Runnable() {
#Override
public void run() {
// DO your work here
DriveResource.MetadataResult mdRslt = file.getMetadata(mGoogleApiClient).await();
if (mdRslt != null && mdRslt.getStatus().isSuccess()) {
String link = mdRslt.getMetadata().getWebContentLink();
String name=mdRslt.getMetadata().getTitle();
Log.d("LINK", link);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && getApplication().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
{
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
else
{
new get_download_data(link,name).execute();
}
}
}
}).start();
}
After getting the link from Google Drive, I am calling async task to download that file from link. So my problem is when I am downloading file, it's not opening. After checking and debugging, I found that my files was not downloading properly.
For example, I have file name abc.pdf and the size is 400kb. I downloaded on my sdcard but abc.pdf is 56 kb only. I am using below code for downloading. I don't know where I was doing wrong. Please help. Thanks.
public class get_download_data extends AsyncTask<Void,Void,String>
{
File apkStorage = null;
File outputFile = null;
String link1="";
String name1="";
public get_database_data(String link, String name) {
this.link1=link;
this.name1=name;
}
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
try {
URL url = new URL(link1);//Create Download URl
HttpURLConnection c = (HttpURLConnection) url.openConnection();//Open Url Connection
c.setRequestMethod("GET");//Set Request Method to "GET" since we are grtting data
c.setDoInput(true);
c.connect();//connect the URL Connection
//If Connection response is not OK then show Logs
if (c.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.e(TAG, "Server returned HTTP " + c.getResponseCode()
+ " " + c.getResponseMessage());
}else{
Log.e(TAG, "Server returned HTTP " + c.getResponseCode()
+ " " + c.getResponseMessage());
}
//Get File if SD card is present
if (new CheckForSDCard().isSDCardPresent()) {
apkStorage = new File(
Environment.getExternalStorageDirectory() + "/"
+ "checkdb");
} else
Toast.makeText(getApplication(), "Oops!! There is no SD Card.", Toast.LENGTH_SHORT).show();
//If File is not present create directory
if (!apkStorage.exists()) {
apkStorage.mkdir();
Log.e(TAG, "Directory Created.");
}
outputFile = new File(apkStorage, name1);//Create Output file in Main File
//Create New File if not present
if (!outputFile.exists()) {
outputFile.createNewFile();
Log.e(TAG, "File Created");
}
OutputStream fos = new FileOutputStream(outputFile);//Get OutputStream for NewFile Location
InputStream is = c.getInputStream();//Get InputStream for connection
BufferedInputStream inStream = new BufferedInputStream(is, 1024);
byte[] buffer = new byte[1024];//Set buffer type
int len1 = 0;//init length
while ((len1 = inStream.read(buffer)) != -1) {
fos.write(buffer, 0, len1);//Write new file
}
//Close all connection after doing task
fos.flush();
fos.close();
is.close();
} catch (Exception e) {
//Read exception if something went wrong
e.printStackTrace();
outputFile = null;
Log.e(TAG, "Download Error Exception " + e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String result_1) {
super.onPostExecute(result_1);
String downlodepath = Environment.getExternalStorageState()+"/"+name1;
Log.e("Sdpath",""+imagePath);
Toast.makeText(getApplication(), "download"+downlodepath, Toast.LENGTH_SHORT).show();
}
}
I found this link here but some how I don't have idea how to implement this. Please let me know where I was wrong. Thanks.
After some work around and trying so many examples, I found the answer for this.
Here are the dependencies which I have added in my project:
compile 'com.google.android.gms:play-services-auth:11.8.0'
compile 'com.google.android.gms:play-services-drive:11.8.0'
Here is my manifest file:
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="false"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_api_key" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</application>
</manifest>
Here is my MainActivity:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private ActivityMainBinding binding;
private static final String TAG = "Google drive";
private static final String SIGN_IN = "Sign In";
private static final String DOWNLOAD_FILE = "Download file";
private static final int REQUEST_CODE_SIGN_IN = 0;
private static final int REQUEST_CODE_OPEN_ITEM = 1;
private static final int REQUEST_WRITE_STORAGE = 112;
private GoogleSignInAccount signInAccount;
private Set<Scope> requiredScopes;
private DriveClient mDriveClient;
private DriveResourceClient mDriveResourceClient;
private OpenFileActivityOptions openOptions;
private TaskCompletionSource<DriveId> mOpenItemTaskSource;
private File storageDir;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
initialize();
requestPermission();
signInAccount = GoogleSignIn.getLastSignedInAccount(this);
binding.btnSubmit.setOnClickListener(this);
if (signInAccount != null && signInAccount.getGrantedScopes().containsAll(requiredScopes)) {
initializeDriveClient(signInAccount);
binding.btnSubmit.setText(DOWNLOAD_FILE);
} else {
binding.btnSubmit.setText(SIGN_IN);
}
}
private void showMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CODE_SIGN_IN:
if (resultCode == RESULT_OK) {
Task<GoogleSignInAccount> getAccountTask = GoogleSignIn.getSignedInAccountFromIntent(data);
if (getAccountTask.isSuccessful()) {
initializeDriveClient(getAccountTask.getResult());
showMessage("Sign in successfully.");
binding.btnSubmit.setText(DOWNLOAD_FILE);
} else {
showMessage("Sign in failed.");
}
} else {
showMessage("Sign in failed.");
}
break;
case REQUEST_CODE_OPEN_ITEM:
if (resultCode == RESULT_OK) {
DriveId driveId = data.getParcelableExtra(OpenFileActivityOptions.EXTRA_RESPONSE_DRIVE_ID);
mOpenItemTaskSource.setResult(driveId);
} else {
mOpenItemTaskSource.setException(new RuntimeException("Unable to open file"));
}
break;
}
}
private void initialize() {
requiredScopes = new HashSet<>(2);
requiredScopes.add(Drive.SCOPE_FILE);
requiredScopes.add(Drive.SCOPE_APPFOLDER);
openOptions = new OpenFileActivityOptions.Builder()
.setSelectionFilter(Filters.eq(SearchableField.MIME_TYPE, "application/pdf"))
.setActivityTitle("Select file")
.build();
}
private void initializeDriveClient(GoogleSignInAccount signInAccount) {
mDriveClient = Drive.getDriveClient(getApplicationContext(), signInAccount);
mDriveResourceClient = Drive.getDriveResourceClient(getApplicationContext(), signInAccount);
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.btnSubmit) {
String text = (String) ((Button) view).getText();
if (text.equals(SIGN_IN)) {
signIn();
} else {
onDriveClientReady();
}
}
}
private void signIn() {
GoogleSignInOptions signInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestScopes(Drive.SCOPE_FILE)
.requestScopes(Drive.SCOPE_APPFOLDER)
.build();
GoogleSignInClient googleSignInClient = GoogleSignIn.getClient(this, signInOptions);
startActivityForResult(googleSignInClient.getSignInIntent(), REQUEST_CODE_SIGN_IN);
}
private void onDriveClientReady() {
mOpenItemTaskSource = new TaskCompletionSource<>();
mDriveClient.newOpenFileActivityIntentSender(openOptions)
.continueWith(new Continuation<IntentSender, Void>() {
#Override
public Void then(#NonNull Task<IntentSender> task) throws Exception {
startIntentSenderForResult(
task.getResult(), REQUEST_CODE_OPEN_ITEM, null, 0, 0, 0);
return null;
}
});
Task<DriveId> tasks = mOpenItemTaskSource.getTask();
tasks.addOnSuccessListener(this,
new OnSuccessListener<DriveId>() {
#Override
public void onSuccess(DriveId driveId) {
retrieveContents(driveId.asDriveFile());
}
})
.addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
showMessage("File not selected.");
}
});
}
private void retrieveContents(final DriveFile file) {
// [START open_file]
final Task<DriveContents> openFileTask = mDriveResourceClient.openFile(file, DriveFile.MODE_READ_ONLY);
// [END open_file]
// [START read_contents]
openFileTask.continueWithTask(new Continuation<DriveContents, Task<Void>>() {
#Override
public Task<Void> then(#NonNull Task<DriveContents> task) throws Exception {
DriveContents contents = task.getResult();
Log.v(TAG, "File name : " + contents.toString());
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
InputStream input = contents.getInputStream();
try {
File file = new File(getExternalFilesDir(null), "umesh.pdf");
Log.v(TAG, storageDir + "");
OutputStream output = new FileOutputStream(file);
try {
try {
byte[] buffer = new byte[4 * 1024]; // or other buffer size
int read;
while ((read = input.read(buffer)) != -1) {
output.write(buffer, 0, read);
}
output.flush();
} finally {
output.close();
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
showMessage("Download file successfully.");
return mDriveResourceClient.discardContents(contents);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
showMessage("Unable to download file.");
}
});
// [END read_contents]
}
private void requestPermission() {
String dirPath = getFilesDir().getAbsolutePath() + File.separator + "PDF";
storageDir = new File(dirPath);
if (!storageDir.exists())
storageDir.mkdirs();}}
And here is the string file for the API key:
<resources>
<string name="app_name">GoogleDriveDemo</string>
<string name="google_api_key">"your-key"</string>
</resources>
The way I use webContentLink when downloading a file in Drive API is to open a new browser window in Javascript.
var webcontentlink = 'https://docs.google.com/a/google.com/uc?id='+fileId+'&export=download'
window.open( webcontentlink);
I'd suggest you do that in Android like the one mentioned in this post:
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(webcontentlink));
startActivity(browserIntent);
For someone who still stuck in this problem.
Somehow the download URL cannot be returned right after driveResourceClient.createFile()
driveResourceClient?.createFile(appFolder, metadataChangeSet, contents)
}?.addOnSuccessListener(this
) { driverFile -> //we cannot get webContentLink here }
At this time we can only get the file name (this one may already defined)
In my case, I don't really need the URL right after upload but when user click a copy URL button
driveResourceClient?.query(Query.Builder()
.addFilter(Filters.eq(SearchableField.TITLE, sharedFileName))
.build())
?.addOnSuccessListener {
url = it.first().webContentLink
}
?.{
}
I've just success with this.
You can easily do that using chrome custom tabs just paste the url in the custom tabs and it will show the drive website and one can download the file
Refer this official documentation for chrome custom tabs https://developer.chrome.com/multidevice/android/customtabs it's an really superb feature and a best alternative for webview
Simplest way to download a file through Google Drive URL in Android is by navigating to browser. In this way we can download any data like .apk, .mp4, .txt..
In kotlin
val driveIntent = Intent(Intent.ACTION_VIEW, Uri.parse(DRIVE_URL))//Link can have any data link .apk, .mp4 ..
val browserChooserIntent = Intent.createChooser(driveIntent, "Choose browser")
startActivity(browserChooserIntent)

Programmatically Downloading and Installing APK [duplicate]

This question already has answers here:
Android: install .apk programmatically [duplicate]
(4 answers)
Closed 5 years ago.
I've seen a few answers related to this but can't quite seem to find what I'm looking for. Say I have a self hosted app. Now say I've made some changes to that app and would like to let the user know within the app that there is an update available. I can get the app to successfully download the apk file and begin installing it. After the installation is "finished" the app closes out. When I restart the app none of the changes I've made have been applied. So it appears the installation has failed, but there was no apparent crash. However, when I install the apk that was downloaded from the Downloads manager it installs just fine and the changes I have made are applied. Any ideas? Here is the section of code I use to download and install programmatically:
String destination = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
String fileName = "TheApp.apk";
destination += fileName;
final Uri uri = Uri.parse("file://" + destination);
String url = "myapplocation";
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDescription("Downloading necessary update files.");
request.setTitle("Updating The App");
final DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
final long downloadId = manager.enqueue(request);
BroadcastReceiver onComplete = new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
Intent install = new Intent(Intent.ACTION_VIEW);
install.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
install.setDataAndType(uri,
manager.getMimeTypeForDownloadedFile(downloadId));
startActivityForResult(install, 0);
unregisterReceiver(this);
}
};
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
Get VersionName and VersionCode for current Running application.
code:
try {
PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
Common.VersionName = pInfo.versionName;
Common.VersionCode = pInfo.versionCode;
Log.e("VersionCode", ">>>>>>>>>>" + Common.VersionCode + Common.VersionName);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
**Check the Version Names**
if (!Common.VersionName.equals(Common.VersionNamefromWebApi)) {
AlertDialogUpdate(MakeTransactionActivity.this, Common.AppUpdateTitle, "YokoYepi Version" + Common.VersionNamefromWebApi + " available.");
}
**Alert Dialog Box**
public void AlertDialogUpdate(Activity activity, String title, CharSequence message) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setCancelable(false);
if (title != null) builder.setTitle(title);
builder.setMessage(message);
builder.setPositiveButton("UPDATE", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
new DownloadNewVersion().execute();
dialog.dismiss();
}
});
builder.show();
}
**Download and Install the .apk file from URL**
class DownloadNewVersion extends AsyncTask<String, Integer, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
bar = new ProgressDialog(MakeTransactionActivity.this);
bar.setCancelable(false);
bar.setMessage("Downloading...");
bar.setIndeterminate(true);
bar.setCanceledOnTouchOutside(false);
bar.show();
stoptimertask();
}
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
bar.setIndeterminate(false);
bar.setMax(100);
bar.setProgress(progress[0]);
String msg = "";
if (progress[0] > 99) {
msg = "Finishing... ";
} else {
msg = "Downloading... " + progress[0] + "%";
}
bar.setMessage(msg);
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
startTimer();
bar.dismiss();
if (result) {
Toast.makeText(getApplicationContext(), "Update Done",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Error: Try Again",
Toast.LENGTH_SHORT).show();
}
}
#Override
protected Boolean doInBackground(String... arg0) {
Boolean flag = false;
try {
String PATH;
Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
if (isSDPresent) {
PATH = Environment.getExternalStorageDirectory() + "/Download/";
} else {
PATH = Environment.getDataDirectory() + "/Download/";
}
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "yokoyepi.apk");
if (outputFile.exists()) {
outputFile.delete();
}
// Download File from url
URL u = new URL(Common.AppUpdateURL);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(outputFile));
fos.write(buffer);
fos.flush();
fos.close();
// Install dowloaded Apk file from Devive----------------
OpenNewVersion(PATH);
flag = true;
} catch (MalformedURLException e) {
Log.e(TAG, "Update Error: " + e.getMessage());
flag = false;
} catch (IOException e) {
Log.e(TAG, "Update Error: " + e.getMessage());
flag = false;
} catch (Exception e) {
Log.e(TAG, "Update Error: " + e.getMessage());
flag = false;
}
return flag;
}
}
void OpenNewVersion(String location) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(location + "yokoyepi.apk")),
"application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
// if your not install u should call the function in onResume().
// again it will check whether apk updated or not.

Download Manager Android: Download Complete

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
}
}

Download apk file. Work fine on AVD but on real phone dasn't

Hello i am trying to download apk file from web server to my android application (/download) dir.
The problem is: on AVD is working fine but on my real phone S2 do not download this apk file.
Please hellp :)
the code:`
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_apk);
BroadcastReceiver receiver = new BroadcastReceiver() {
#SuppressLint("NewApi")
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
// openFile();
}
}
};
registerReceiver(receiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
/*
//del old file
File fileUpdate = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+"/"+fileName);
if(fileUpdate != null){
fileUpdate.delete();
}*/
startDownload();
}
#SuppressLint("NewApi")
public void startDownload() {
try{
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
Request request = new Request(
Uri.parse("http://10.10.10.10/andr_test/download_new_version/appUpdate.apk"));
enqueue = dm.enqueue(request);
} catch (Exception e) {
Log.e("Can't download file", "Can't download file-" + e.getMessage());
}
}`
The host:10.10.10.10 is a real host that your real phone network can access? Or just a test host only can accessed by your desktop.

Android XMPP File Transfer

I'm newbie to Android programming. I'm trying to develop messenger application with file transfer feature. But having difficulties reagrding file transfer.
viewer.java**
Button transfer = (Button) findViewById(R.id.btnimage);
transfer.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
}
});
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
XMPPClient.getInstance().SendFile(to, selectedImagePath);
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
and then i Have XMPPCLIENT.java
public void ReceiveFile() {
Thread thread = new Thread() {
public void run() {
ServiceDiscoveryManager sdm = ServiceDiscoveryManager
.getInstanceFor(getConnection());
if (sdm == null)
sdm = new ServiceDiscoveryManager(getConnection());
sdm.addFeature("http://jabber.org/protocol/disco#info");
sdm.addFeature("jabber:iq:privacy");
// Create the file transfer manager
final FileTransferManager managerListner = new FileTransferManager(
getConnection());
FileTransferNegotiator.setServiceEnabled(getConnection(), true);
Log.i("File transfere manager", "created");
// Create the listener
managerListner
.addFileTransferListener(new FileTransferListener() {
public void fileTransferRequest(
final FileTransferRequest request) {
Log.i("Recieve File",
"new file transfere request new file transfere request new file transfere request");
Log.i("file request",
"from" + request.getRequestor());
IncomingFileTransfer transfer = request
.accept();
Log.i("Recieve File alert dialog", "accepted");
try {
transfer.recieveFile(new File("/sdcard/"
+ request.getFileName()));
while (!transfer.isDone()
|| (transfer.getProgress() < 1)) {
Thread.sleep(1000);
Log.i("Recieve File alert dialog",
"still receiving : "
+ (transfer
.getProgress())
+ " status "
+ transfer.getStatus());
if (transfer.getStatus().equals(
Status.error)) {
// Log.i("Error file",
// transfer.getError().getMessage());
Log.i("Recieve File alert dialog",
"cancelling still receiving : "
+ (transfer
.getProgress())
+ " status "
+ transfer
.getStatus());
transfer.cancel();
break;
}
}
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
};
thread.start();
}
public void SendFile(final String Receiver, final String Directory) {
Thread thread = new Thread() {
public void run() {
ServiceDiscoveryManager sdm = ServiceDiscoveryManager
.getInstanceFor(getConnection());
if (sdm == null)
sdm = new ServiceDiscoveryManager(getConnection());
sdm.addFeature("http://jabber.org/protocol/disco#info");
sdm.addFeature("jabber:iq:privacy");
// Create the file transfer manager
FileTransferManager manager = new FileTransferManager(
mConnection);
FileTransferNegotiator
.setServiceEnabled(getConnection(), true);
// Create the outgoing file transfer
OutgoingFileTransfer transfer = manager
.createOutgoingFileTransfer(getJIDofUserID(Receiver));
sendMessage(getJIDofUserID(Receiver), "image");
Log.i("transfere file", "outgoingfiletransfere is created");
try {
OutgoingFileTransfer.setResponseTimeout(30000);
transfer.sendFile(new File(Directory), "Description");
Log.i("transfere file", "sending file");
while (!transfer.isDone()) {
try {
Thread.sleep(1000);
Log.i("transfere file", "sending file status "
+ transfer.getStatus() + "progress: "
+ transfer.getProgress());
if (transfer.getStatus() == org.jivesoftware.smackx.filetransfer.FileTransfer.Status.error) {
transfer.cancel();
Log.e("",transfer.getError()+" error");
break;
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.e("aaaaaaaaaaaaaaa","aaaa"+e);
e.printStackTrace();
}
}
}
catch (XMPPException e) {
// TODO Auto-generated catch block
Log.e("aaaaaaaaaaaaaaa","aaaa"+e);
e.printStackTrace();
}
Log.i("transfere file", "sending file done");
}
};
thread.start();
}
So my questions are:
Is connection that i use is the same connection as chatting (default port: 5222)?
When I trigger sendfile(final String Receiver, final String Directory) function, when and how the receiver get any notification?
To answer your questions:
That depends on which method is used for file transfer. XMPP knows several. You can read more about it here https://github.com/igniterealtime/Smack/wiki/Smack-XMPP-File-Transfer and http://xmpp.org/xmpp-protocols/xmpp-extensions/
The receiving entity always has to confirm the file transfer first. But it depends on the other client how this is implemented e.g. if there is a pop-up windows saying that there is an incoming file transfer. It is also possible that the client on the other side is configured to auto-accept all requests.
First add following configuration in to your xmpp configuration class.
ProviderManager.getInstance().addIQProvider('query','http://jabber.org/protocol/bytestreams', new BytestreamsProvider());
2
ProviderManager.getInstance().addIQProvider('query','http://jabber.org/protocol/disco#items', new DiscoverItemsProvider());
3
ProviderManager.getInstance().addIQProvider('query','http://jabber.org/protocol/disco#info', new DiscoverInfoProvider());
Then add or edit following three properties in open fire server.
xmpp.proxy.enabled – true
xmpp.proxy.port – 7777
xmpp.proxy.externalip – [publicly accessible host or ip]
please make these changes and try again .

Categories

Resources