PDF file is not getting open after downloading by Download Manager - android

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

Related

Capturing stacked Notifications using Notification Listener

This question has been asked before but I could not find a working solution to it.
I'm trying to read notifications using NotificationListener Service. Here is the code
import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.util.Log;
import android.support.v4.content.LocalBroadcastManager;
import java.io.ByteArrayOutputStream;
public class NotificationService extends NotificationListenerService {
Context context;
#Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
String pack = sbn.getPackageName();
String ticker ="";
if(sbn.getNotification().tickerText !=null) {
ticker = sbn.getNotification().tickerText.toString();
}
Bundle extras = sbn.getNotification().extras;
String title = extras.getString("android.title");
String text = extras.getCharSequence("android.text").toString();
int id1 = extras.getInt(Notification.EXTRA_SMALL_ICON);
Bitmap id = sbn.getNotification().largeIcon;
Log.i("Package",pack);
Log.i("Ticker",ticker);
Log.i("Title",title);
Log.i("Text",text);
Intent msgrcv = new Intent("Msg");
msgrcv.putExtra("package", pack);
msgrcv.putExtra("ticker", ticker);
msgrcv.putExtra("title", title);
msgrcv.putExtra("text", text);
if(id != null) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
id.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
msgrcv.putExtra("icon",byteArray);
}
LocalBroadcastManager.getInstance(context).sendBroadcast(msgrcv);
}
#Override
public void onNotificationRemoved(StatusBarNotification sbn) {
Log.i("Msg","Notification Removed");
}
}
This works well but, when notifications get stacked, it does not capture the full notifications.
John:Hi
John:2 new messages
I have tried using the following but that too does not work.
sbn.getNotification().extras.getCharSequence(Notification.EXTRA_TEXT).toString();
The following method tries to get the extra text lines, if there are none it tries to fall back to the extra big text if it’s available.
CharSequence[] lines =
extras.getCharSequenceArray(Notification.EXTRA_TEXT_LINES);
if(lines != null && lines.length > 0) {
StringBuilder sb = new StringBuilder();
for (CharSequence msg : lines)
if (!TextUtils.isEmpty(msg)) {
sb.append(msg.toString());
sb.append('\n');
}
return sb.toString().trim();
}
CharSequence chars =
extras.getCharSequence(Notification.EXTRA_BIG_TEXT);
if(!TextUtils.isEmpty(chars))
return chars.toString();

UDP Client on Android

I have made an UDP Server on a Wi-Fi demo board and test it using and android App (UDP Sender).
I created my own UDP client apps on Android, but it doesn't work.
I created and configured well the socket port and the IPaddress but the app doesn't work and I don't know why.
PS : In the manifest I added the uses-permission to access to the Wi-Fi
her is my simple code
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Udp_Client extends Activity {
/** Called when the activity is first created. */
TextView txt5,txt1;
byte[] send_data = new byte[1024];
Button hello;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txt1 = (TextView)findViewById(R.id.textView1);
txt5 = (TextView)findViewById(R.id.textView5);
hello = (Button) findViewById(R.id.button1);
hello.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
try {
client();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public void client() throws IOException{
String str="Hello";
int port = 50000;
DatagramSocket client_socket = new DatagramSocket(port);
InetAddress IPAddress = InetAddress.getByName("192.168.0.1");
send_data = str.getBytes();
DatagramPacket send_packet = new DatagramPacket(send_data,str.length(), IPAddress, port);
//client_socket.setBroadcast(true);
client_socket.send(send_packet);
client_socket.close();
}
}
[1]: http://i.stack.imgur.com/aXPhf.png
I found the solution for the problem
The problem was in the manifest
Here is my new code and my manifest
The main in wich I call the UDP_Client :
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
private TextView sceen = null;
private Button launch = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sceen = (TextView)findViewById(R.id.textView1);
launch = (Button)findViewById(R.id.udpbutton);
launch.setOnClickListener(this);
launch.setOnClickListener((OnClickListener) this);
}
public void onClick(View v) {
//UDP Client erstellen
UDP_Client Client = new UDP_Client();
Client.Message = "Your message";
Client.NachrichtSenden();
}
}
The code of my UDP_Client
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Build;
public class UDP_Client
{
private InetAddress IPAddress = null;
private String message = "Hello Android!" ;
private AsyncTask<Void, Void, Void> async_cient;
public String Message;
#SuppressLint("NewApi")
public void NachrichtSenden()
{
async_cient = new AsyncTask<Void, Void, Void>()
{
#Override
protected Void doInBackground(Void... params)
{
DatagramSocket ds = null;
try
{
byte[] ipAddr = new byte[]{ (byte) 192, (byte) 168,43, (byte) 157};
InetAddress addr = InetAddress.getByAddress(ipAddr);
ds = new DatagramSocket(5000);
DatagramPacket dp;
dp = new DatagramPacket(Message.getBytes(), Message.getBytes().length, addr, 50000);
ds.setBroadcast(true);
ds.send(dp);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (ds != null)
{
ds.close();
}
}
return null;
}
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
}
};
if (Build.VERSION.SDK_INT >= 11) async_cient.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
else async_cient.execute();
}
}
The manifest :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.udp_server"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I added the part of code in my manifest
hope that it will help someone in the future ;)
I think you miss this:
public void connect (InetAddress address, int port)
Of the DataGramSocket Object.
Try:
client_socket.connect(IPAddress, port);
client_socket.send(send_packet);

Open gallery in specific video, without playing it

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

Android: Error installing an apk from Downloads folder

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

How do I download a file via default Android Downloader?

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.

Categories

Resources