How can I download files using Android downloader? (The downloader that WebBrowser is using that too).
I tried something like this :
Intent i = new Intent(Intent.ACTION_VIEW , Uri.parse("MyUrl"));
startActivity(i);
Any better way?
Edit
I am using Android 2.2
Here you go.
import android.app.Activity;
import android.app.DownloadManager;
import android.app.DownloadManager.Query;
import android.app.DownloadManager.Request;
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.Bundle;
import android.view.View;
import android.widget.ImageView;
public class DownloadManagerActivity extends Activity {
private long enqueue;
private DownloadManager dm;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, 0);
Query query = new Query();
query.setFilterById(enqueue);
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int columnIndex = c
.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c
.getInt(columnIndex)) {
ImageView view = (ImageView) findViewById(R.id.imageView1);
String uriString = c
.getString(c
.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
view.setImageURI(Uri.parse(uriString));
}
}
}
}
};
registerReceiver(receiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
public void onClick(View view) {
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
Request request = new Request(
Uri.parse("url for file to download"));
enqueue = dm.enqueue(request);
}
public void showDownload(View view) {
Intent i = new Intent();
i.setAction(DownloadManager.ACTION_VIEW_DOWNLOADS);
startActivity(i);
}
}
Don't forget to add android.permission.internet in manifest.
If you want to download it onto the user's SD card from an URL, you can just open it in the phone's default internet browser.
String url = "https://appharbor.com/assets/images/stackoverflow-logo.png";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
(Code from this question)
The android browser will then start and the file (in this case an image) will be downloaded.
You need to use HttpUrlConnection to do this on Android 2.2 and below. There is a very detailed tutorial on the internet that shows you how to do this (with a progress dialog box too).
Remember you must use an AsyncTask or a Thread to ensure that you do not block the UI thread during the actual download!
Yes, you cant perform network operation in the main thread. You can look up to this repository to download file.
Related
So I am stuck on a issue with my webapp that runs inside a webview from android studio.
I want download like pdf file to be downloaded and opend in the native app on the phone. This work fine by using the download manager from android studio.
How ever I also have links that start with "mailto:" and "tel:" those links give me an error when I don't override the method "shouldOverrideUrlLoading" where I can check what kind of url it is. And then open the propper inten.
So when I combine the 2 the downloadmanager and the custom NavigationHandler that extends the WebViewClient, it doesn't work as expected.
For a better understanding of what is happening.
When I hit a button with a pdf file it downloads the file gives a toast message and opens the file with the native app on the phone. This is without overriding the "shouldOverrideURLLoading" and without my class that extends the WebViewClient.
When I also use my own NavigationHandler witch extends from WebViewClient,
my urls with "mailto:" and "tel:" open with native apps on the phone.
When I now hit a button with a pdf file it is opend in a browser to be downloaded. Witch I don't want. I have tried numerous things to solf the problem but until now without succes.
I run a website app inside of a WebViewClient.
P.S. sorry for the shitty code but it's new to me and haven't find my way jet in coding in Android Studio.
My NavigationHandler class
package nl.firejob.selector;
import android.content.Intent;
import android.net.Uri;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class NavigationHandler extends WebViewClient {
private static final String TEL_PREFIX = "tel:";
private static final String MAILTO_PREFIX = "mailto:";
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if ( url.startsWith( TEL_PREFIX ) ) {
// This is a tel link, which should be opened with the native thing.
Intent tel = new Intent( Intent.ACTION_DIAL, Uri.parse( url ) );
view.getContext().startActivity( tel );
return true;
} else if ( url.startsWith( MAILTO_PREFIX ) ) {
// This is a mail link, which should be opened with the other native thing.
Intent mail = new Intent(Intent.ACTION_SENDTO);
mail.setType("message/rfc822");
mail.setData(Uri.parse( url ));
view.getContext().startActivity( mail );
return true;
} else if ( Uri.parse(url).getHost().startsWith("myurl.com") ) {
// This is what we want to show in the app, so let the WebView handle it.
return false;
}
// Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse( url ) );
view.getContext().startActivity( intent );
return true;
}
}
My MainActivity Class
package nl.firejob.selector;
import android.Manifest;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Toast;
import java.io.File;
public class MainActivity extends AppCompatActivity {
private WebView mWebView;
private DownloadManager dm;
private Long myDownloadReference;
private BroadcastReceiver receiveDownloadComplete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.webView);
// Allow webview to use javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
// Stop local links/redirects from opening in browser instead of WebView
mWebView.setWebViewClient(new NavigationHandler() {
#Override
public void onPageFinished(WebView view, String url) {
// Show the webview
findViewById(R.id.webView).setVisibility(View.VISIBLE);
// Hide splashscreen objects
findViewById(R.id.imageLogo).setVisibility(View.GONE);
findViewById(R.id.textLogo).setVisibility(View.GONE);
}
});
mWebView.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
if( haveStoragePermission()) {
Log.i("download url",url);
//for downloading directly through download manager
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.allowScanningByMediaScanner();
request.setVisibleInDownloadsUi(true);
request.setDescription("Doorvoerboek").setTitle("doorvoerboek.pdf");
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "doorvoerboek.pdf");
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
myDownloadReference = dm.enqueue(request);
IntentFilter intentFilter = new IntentFilter( dm.ACTION_DOWNLOAD_COMPLETE);
receiveDownloadComplete = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
long reference = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
if (myDownloadReference == reference) {
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(reference);
Cursor cursor = dm.query(query);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
int status = cursor.getInt(columnIndex);
int fileNameIndex = cursor.getColumnIndex(DownloadManager.COLUMN_TITLE);
String saveFilePath = cursor.getString(fileNameIndex);
Log.i("filename",saveFilePath);
int columnReason = cursor.getColumnIndex(DownloadManager.COLUMN_REASON);
int reason = cursor.getInt(columnReason);
switch (status){
case DownloadManager.STATUS_SUCCESSFUL:
Toast.makeText(MainActivity.this, "Download Complete", Toast.LENGTH_LONG).show();
Log.i("dir", Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() );
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() +"/doorvoerboek.pdf");
Intent intentView = new Intent(Intent.ACTION_VIEW);
intentView.setDataAndType(Uri.fromFile(file),"application/pdf");
intentView.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intentView);
break;
}
}
}
};
registerReceiver(receiveDownloadComplete,intentFilter);
}
}
});
mWebView.loadUrl("http://myurl.com/");
}
public boolean haveStoragePermission() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.e("Permission error","You have permission");
return true;
} else {
Log.e("Permission error","You have asked for permission");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
}
else { //you dont need to worry about these stuff below api level 23
Log.e("Permission error","You already have the permission");
return true;
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
//if Back key pressed and webview can navigate to previous page
mWebView.goBack();
// go back to previous page
return true;
}
else
{
finish();
// finish the activity
}
return super.onKeyDown(keyCode, event);
}
}
This code downloads any file.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview = (WebView) findViewById(R.id.webView);
spinner = (ProgressBar) findViewById(R.id.progressBar1);
webview.setWebViewClient(new CustomWebViewClient());
webview.getSettings().setUseWideViewPort(true);
webview.getSettings().setLoadWithOverviewMode(true);
webview.getSettings().setBuiltInZoomControls(true);
webview.getSettings().setDisplayZoomControls(false);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setDomStorageEnabled(true);
webview.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
webview.loadUrl("http://www.website.com");
//Download file code stackoverflow.com
webview.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
DownloadManager dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getApplicationContext(), "downloading",
Toast.LENGTH_LONG).show();
}
});
// Download section of code
} // Close of onCreate
// mailto code stackoverflow.com
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if( url.startsWith("http:") || url.startsWith("https:") ) {
return false;
}
// Otherwise allow the OS to handle it
else if (url.startsWith("tel:")) {
Intent tel = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
startActivity(tel);
return true;
}
else if (url.startsWith("mailto:")) {
String body = "Enter your Question, Enquiry or Feedback below:\n\n";
Intent mail = new Intent(Intent.ACTION_SEND);
Intent intent = mail.setType("application/octet-stream");
MailTo recipient = MailTo.parse(url);
mail.putExtra(Intent.EXTRA_EMAIL, new String[]{recipient.getTo()});
mail.putExtra(Intent.EXTRA_SUBJECT, "Contact");
mail.putExtra(Intent.EXTRA_TEXT, body);
startActivity(mail);
return true;
}
return true;
}
}
// mailto section of code
Good day everyone. Please am trying to play videos from a youtube channel. Let me break it down
1:On the first activity you get a list of users in a listview
2:When you click on the user,it loads their videos in another listview.
Everything is working perfectly to this point,But i don't know how to play the video,when that particular video is clicked. Here is my code.
package com.talagbe.videofeeds;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;
public class YoutubeVideos extends Activity {
ListView listv;
YoutubeAdapter yadapter;
ArrayList<Youtube> y_list;
String url;
String Channel;
Context context=null;
ProgressDialog mprogress;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.youtube);
y_list= new ArrayList<Youtube>();
listv = (ListView) findViewById(R.id.list2);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
Channel = bundle.getString("Channel");
init();
}
public void init(){
Log.d("Chan",Channel);
AsyncHttpClient LoadVideos = new AsyncHttpClient();
LoadVideos.get("https://gdata.youtube.com/feeds/api/users/"+ Channel +"/uploads?v=2&alt=jsonc", new AsyncHttpResponseHandler(){
public void onSuccess(String data){
try {
JSONObject videoObj = new JSONObject(data);
//JSONArray jsonArray = json.getJSONObject("data").getJSONArray("items");
JSONArray videosarray = videoObj.getJSONObject("data").getJSONArray("items");;
for(int i=0; i<videosarray.length();i++){
Youtube yvideos = new Youtube();
JSONObject video = videosarray.getJSONObject(i);
String videourl = video.getJSONObject("player").getString("mobile");
yvideos.setVideoTitle(video.getString("title"));
yvideos.setThumbs(video.getJSONObject("thumbnail").getString("sqDefault"));
//yvideos.setVideourl(videourl);
y_list.add(yvideos);
Log.d("Title",video.getString("title"));
Log.d("Video",videourl);
Log.d("Thumb",video.getJSONObject("thumbnail").getString("sqDefault"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
YoutubeAdapter Adapter = new YoutubeAdapter(getApplicationContext(),R.layout.videos,y_list);
listv.setAdapter(Adapter);
}
public void onStart(){
mprogress = ProgressDialog.show(YoutubeVideos.this, "Connecting...", "Retrieveing Videos");
}
public void onFinish(){
mprogress.dismiss();
}
public void onFailure(Throwable error, String content)
{
//Log.e("Error", content);
Toast.makeText(getBaseContext(), "Error Connecting to the internet", Toast.LENGTH_LONG).show();
}
});
}
}
You can make use of "YouTube Android Player API" provided by Google to play YouTube videos.
The YouTube Android Player API enables you to incorporate video
playback functionality into your Android applications. The API defines
methods for loading and playing YouTube videos (and playlists) and for
customizing and controlling the video playback experience.
Here's a sample app that utilizes YouTube Android Player API.
You can follow YouTube API
https://developers.google.com/youtube/android/player/reference/com/google/android/youtube/player/YouTubeIntents
or you can direct intent default YouTube player by calling :
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube://" + id));
startActivity(intent);
The id is the identifier after the questionmark in the url. For example: youtube.com/watch?v=ID
Another way is:
Intent videoIntent = new Intent(Intent.ACTION_VIEW);
videoIntent.setData(url);
videoIntent.setClassName("com.google.anddroid.youtube", "com.google.android.youtube.WatchActivity");
startActivity(videoIntent);
I am implementing Download Manager in my app i wanted to open the pdf file after downloading by Download Manager. File is getting downloaded but not getting opened. I am not able to figure it out whats wrong in my below written code.
import in.b.app.constant.BConstant;
import in.b.app.databasemanagement.SDatabaseHandler;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class AnnouncementDetailsActivity extends Activity implements
OnClickListener {
private static String nid;
private static String announcementTitle;
private static String announcementDetails;
private static String announcementCreatedDate;
private static String cookie;
private static String token;
SharedPreferences sharedPreferences;
TextView title;
TextView details;
TextView createdDate;
TextView createdMonth;
Typeface tf;
Typeface announcementDetailsFont;
ArrayList<String> returnsAnnouncementFilesids = new ArrayList<String>();
SDatabaseHandler sDatabaseHandler;
Button downloadFile;
private long lastDownload = -1L;
private DownloadManager downloadManager = null;
#SuppressLint("SimpleDateFormat")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.announcement_details_page);
downloadFile = (Button) findViewById(R.id.get_file);
tf = Typeface.createFromAsset(this.getAssets(),
BConstant.FONTS_GOTHAM_BOLD_WEBFONT);
sDatabaseHandler = new SDatabaseHandler(this);
announcementDetailsFont = Typeface.createFromAsset(this.getAssets(),
BConstant.FONTS_GOTHAM_BOOK_WEBFONT);
sharedPreferences = getSharedPreferences(
BConstant.B_LOGIN_CHECK, BConstant.PRIVATE_MODE);
cookie = sharedPreferences.getString(
BConstant.WEB_SERVICES_COOKIES, "");
token = sharedPreferences.getString(BConstant.TOKEN, "");
Intent intent = getIntent();
nid = intent.getStringExtra(BConstant.PRODUCT_NODE_ID);
announcementTitle = intent
.getStringExtra(BConstant.ANNOUNCEMENT_TITLE);
announcementDetails = intent
.getStringExtra(BConstant.ANNOUNCEMENT_DETAILS);
announcementCreatedDate = intent
.getStringExtra(BConstant.CREATED_DATE);
returnsAnnouncementFilesids = sDatabaseHandler
.getAnnouncementURLsFID(nid);
// File file = new File(getExternalFilesDir("Rupesh") + "Rupesh.png");
///IntentFilter filter = new IntentFilter();
// filter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
// filter.addAction(DownloadManager.ACTION_NOTIFICATION_CLICKED);
/////filter.addAction(DownloadManager.ACTION_VIEW_DOWNLOADS);
//registerReceiver(onComplete, filter);
//registerReceiver(onNotificationClick, filter);
downloadManager=(DownloadManager)getSystemService(DOWNLOAD_SERVICE);
registerReceiver(onComplete,
new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
registerReceiver(onNotificationClick,
new IntentFilter(DownloadManager.ACTION_NOTIFICATION_CLICKED));
createdDate = (TextView) findViewById(R.id.getAnnouncementDate);
title = (TextView) findViewById(R.id.getAnnouncementName);
details = (TextView) findViewById(R.id.getAnnouncementDetails);
createdMonth = (TextView) findViewById(R.id.getMonth);
title.setTypeface(tf);
details.setTypeface(announcementDetailsFont);
long cDate = Long.parseLong(announcementCreatedDate);
final Calendar c = Calendar.getInstance();
c.setTimeInMillis(cDate * 1000L);
Date d = c.getTime();
SimpleDateFormat simpleDateformat = new SimpleDateFormat("dd");
SimpleDateFormat simpleMonthformat = new SimpleDateFormat("MMM");
String date = simpleDateformat.format(d);
String month = simpleMonthformat.format(d);
createdDate.setText(date);
createdMonth.setText(month);
title.setText(announcementTitle);
details.setText(Html.fromHtml(announcementDetails));
downloadFile.setOnClickListener(this);
}
#Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(R.anim.right_in_details,
R.anim.right_out_left_in_details);
}
BroadcastReceiver onComplete = new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
Toast.makeText(ctxt, "File Downloaded Successfully!!",
Toast.LENGTH_LONG).show();
};
BroadcastReceiver onNotificationClick = new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
Toast.makeText(ctxt, "File Downloaded Successfully!!",
Toast.LENGTH_LONG).show();
}
};
public void viewDownload() {
Intent mView = new Intent();
mView.setAction(DownloadManager.ACTION_VIEW_DOWNLOADS);
startActivity(mView);
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(onComplete);
unregisterReceiver(onNotificationClick);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(onComplete);
unregisterReceiver(onNotificationClick);
}
#Override
public void onClick(View v) {
downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
Uri Download_Uri = Uri
.parse("https://www.cl.cam.ac.uk/~ib249/teaching/Lecture1.handout.pdf");
DownloadManager.Request request = new DownloadManager.Request(
Download_Uri);
request.addRequestHeader(BConstant.WEB_SERVICES_COOKIES, cookie);
request.addRequestHeader(BConstant.WEB_SERVICES_TOKEN_HEADER,
token);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI
| DownloadManager.Request.NETWORK_MOBILE);
request.setAllowedOverRoaming(false);
request.setTitle("Downloading Attachment...");
request.setDestinationInExternalFilesDir(this, "Rupesh", "Rupesh"
+ ".png");
lastDownload = downloadManager.enqueue(request);
// v.setEnabled(false);
}
}
ManiFest File :
<activity
android:name="in.b.app.AnnouncementDetailsActivity"
android:label="#string/app_name"
android:noHistory="true"
android:parentActivityName="in.b.app.HomePageActivity"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="file" />
<data android:mimeType="*/*" />
<data android:pathPattern=".*\\.pdf" />
</intent-filter>
</activity>
I got the same error but with a video file.
Download Manager open the file based on the mime Type of the file.
You should check that the MIME type is application/pdf and not application/octet-stream or something else
Just to add to #rodeleon's answer.
Download Manager in few devices open a file based on Length of file along MIME Type of the file.
Sometimes the MIME type will be known but Download is unsuccessful because of the Length.
Working case: Length: 485449 (474K) [application/pdf]
and not: Length: unspecified [application/octet-stream] or Length: unspecified [application/pdf]
we can get the details of the url using wget:
wget url
I have a camera application that can also record video. (Im developing on samsung S3)
I want to be able to open the gallery on the last recorded video.
I use this code:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(file.getAbsolutePath()), "video/3gpp");
startActivity(intent);
The problem with that code is that the video immediately starts, and when it ends
the gallery activity close.
I want to be able to open the video without playing it, exactly like in my samsung S3.
thanks in advance!
To open particular image we can use this .. and its worked .
so please check with your requirement. Hope this will helps you..
import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.MediaScannerConnectionClient;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class SDCARD123Activity extends Activity implements MediaScannerConnectionClient{
public String[] allFiles;
private String SCAN_PATH ;
private static final String FILE_TYPE="image/*";
private MediaScannerConnection conn;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
File folder = new File("/sdcard/Photo/");
allFiles = folder.list();
// uriAllFiles= new Uri[allFiles.length];
for(int i=0;i<allFiles.length;i++)
{
Log.d("all file path"+i, allFiles[i]+allFiles.length);
}
// Uri uri= Uri.fromFile(new File(Environment.getExternalStorageDirectory().toString()+"/yourfoldername/"+allFiles[0]));
SCAN_PATH=Environment.getExternalStorageDirectory().toString()+"/Photo/"+allFiles[0];
System.out.println(" SCAN_PATH " +SCAN_PATH);
Log.d("SCAN PATH", "Scan Path " + SCAN_PATH);
Button scanBtn = (Button)findViewById(R.id.scanBtn);
scanBtn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
startScan();
}});
}
private void startScan()
{
Log.d("Connected","success"+conn);
if(conn!=null)
{
conn.disconnect();
}
conn = new MediaScannerConnection(this,this);
conn.connect();
}
#Override
public void onMediaScannerConnected() {
Log.d("onMediaScannerConnected","success"+conn);
conn.scanFile(SCAN_PATH, FILE_TYPE);
}
#Override
public void onScanCompleted(String path, Uri uri) {
try {
Log.d("onScanCompleted",uri + "success"+conn);
System.out.println("URI " + uri);
if (uri != null)
{
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
}
} finally
{
conn.disconnect();
conn = null;
}
}
}
I am downloading files from server using the DownloadManager class as mentioned here. The image downloaded can be accessed from the Downloads folder on android. When I click the downloaded image from the Downloads, the image is displayed. But if it try to downlaod an apk instead of an image, the downloaded apk cannot be installed from the Downloads folder, a problem parsing the package error appears. Why?
Here is what I am doing (the same as mentioned in the link above):
import android.app.Activity;
import android.app.DownloadManager;
import android.app.DownloadManager.Query;
import android.app.DownloadManager.Request;
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.Bundle;
import android.view.View;
import android.widget.ImageView;
public class DownloadManagerActivity extends Activity {
private long enqueue;
private DownloadManager dm;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
/* long downloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, 0);*/
Query query = new Query();
query.setFilterById(enqueue);
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int columnIndex = c
.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c
.getInt(columnIndex)) {
/* ImageView view = (ImageView) findViewById(R.id.imageView1);
String uriString = c
.getString(c
.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
view.setImageURI(Uri.parse(uriString));*/
}
}
}
}
};
registerReceiver(receiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
public void onClick(View view) {
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
Request request = new Request(
Uri.parse("http://xxx.xxx.x.xxx/MyApp.apk"));
enqueue = dm.enqueue(request);
}
public void showDownload(View view) {
Intent i = new Intent();
i.setAction(DownloadManager.ACTION_VIEW_DOWNLOADS);
startActivity(i);
}
}