Download manager not callback when the URL is HTTPS - android

Here is how I download the file, it works on http but when I use https, it does not callback, thanks for helping.
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(Constant.request_imageFolder + item.user_id + "/" + item.record_url));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
//request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
}
request.setDestinationUri(Uri.fromFile(tmp_record));
enqueue = mgr.enqueue(request);
The oncomplete code, which is not call when I use https
onComplete = new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
Query query = new Query();
query.setFilterById(enqueue);
if (query != null) {
Cursor c = mgr.query(query);
if (c.moveToFirst()) {
int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
String mediaType = c.getString(c.getColumnIndex(DownloadManager.COLUMN_MEDIA_TYPE));
if (mediaType.equals("image/jpeg")) {
pDialog.dismiss();
share.performClick();
} else if (mediaType.equals("video/mp4")) {
pDialog.dismiss();
play();
}
}
}
}
}
}
};
I tried to debug but the error detection message is at the callback so there is no hints about the root of problem , only knowing that it is caused by https. How can I fix it? thanks for helping?

Related

How can I make other apps play/pause music?

I'm making a media controller app similar to this example made by google. https://github.com/googlesamples/android-media-controller
However, I want to make a function that can resume playing music or pause given package name. I managed to return a list of package names.
PS. I'm using react native that's why I need a fucntion that I can call from the react side.
public void getMediaApps (Callback callback) {
// = getPackageManager();
ArrayList<MediaAppDetails> mediaApps = new ArrayList<MediaAppDetails>();
Intent mediaBrowserIntent = new Intent(MediaBrowserServiceCompat.SERVICE_INTERFACE);
List<ResolveInfo> services = packageManager.queryIntentServices(
mediaBrowserIntent,
PackageManager.GET_RESOLVED_FILTER
);
if (services != null && !services.isEmpty()) {
for (ResolveInfo info : services) {
mediaApps.add(
new MediaAppDetails(info.serviceInfo, packageManager, resources)
);
}
}
WritableArray waPackagenames = Arguments.createArray();
// ArrayList<String> packagenames = ArrayList<String>()
if(mediaApps != null && !mediaApps.isEmpty()){
for(MediaAppDetails mediaApp : mediaApps){
waPackagenames.pushString(mediaApp.packageName);
}
}
callback.invoke(waPackagenames);
}
I've been trying to do this for 3 days now, but no luck.
Probably won't make such of a difference but this is where I got so far with the play function.
#ReactMethod
public void play (String packageName) {
PackageManager pm = this.packageManager;
Resources res = this.resources;
ServiceInfo serviceInfo = MediaAppDetails.findServiceInfo(packageName, pm);
mMediaAppDetails = new MediaAppDetails(serviceInfo, pm, res);
MediaSessionCompat.Token token = mMediaAppDetails.sessionToken;
if (token == null) {
if (mMediaAppDetails.componentName != null) {
mBrowser = new MediaBrowserCompat(this.reactContext, mMediaAppDetails.componentName,
new MediaBrowserCompat.ConnectionCallback() {
#Override
public void onConnected() {
setupMediaController();
// mBrowseMediaItemsAdapter.setRoot(mBrowser.getRoot());
}
#Override
public void onConnectionSuspended() {
//TODO(rasekh): shut down browser.
// mBrowseMediaItemsAdapter.setRoot(null);
}
#Override
public void onConnectionFailed() {
showToastAndFinish("connection failed .. shit!");
}
}, null);
mBrowser.connect();
} else if (mMediaAppDetails.sessionToken != null) {
setupMediaController();
}
token = mBrowser.getSessionToken();
Toast.makeText(this.reactContext, "no token can't open controller", Toast.LENGTH_SHORT).show();
// toast
}
// Toast.makeText(this.reactContext, "found token", Toast.LENGTH_SHORT).show();
if(mBrowser == null )mBrowser = new MediaBrowserCompat(this.reactContext, new ComponentName(packageName, "MainActivity"), null, null);
MediaControllerCompat.TransportControls transportControls;
try{
mController = new MediaControllerCompat(this.reactContext, token);
if(mController!= null) {
transportControls = mController.getTransportControls();
transportControls.play();
}
}catch(Exception E){
Log.w("Error",E);
Log.w("Error","couldn't create mediaControllerCompat");
// System.out.println(E);
// System.out.println("couldn't create mediaControllerCompat");
}
}

Oreo JobScheduler not working when new picture is taken by the camera

In android Oreo Broadcast Receiver is not working for "android.hardware.action.NEW_PICTURE" so i have to replace it with JobScheduler.
Now the problem is PhotoContentsJob is getting called and shows a toast of new Images taken when I restart the app But It doesn't work in the background as soon as new Photo is taken.Please help me how to achieve it.
Code attached for reference.
In MainActivity onCreate Method
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
scheduleCameraJob();
}
#RequiresApi(api = Build.VERSION_CODES.O)
private void scheduleCameraJob() {
final Uri MEDIA_URI = Uri.parse("content://" + MediaStore.AUTHORITY + "/");
JobInfo.Builder builder = new JobInfo.Builder(11,
new ComponentName(this, PhotosContentJob.class.getName()));
// Look for specific changes to images in the provider.
builder.addTriggerContentUri(new JobInfo.TriggerContentUri(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
JobInfo.TriggerContentUri.FLAG_NOTIFY_FOR_DESCENDANTS));
// Also look for general reports of changes in the overall provider.
builder.addTriggerContentUri(new JobInfo.TriggerContentUri(MEDIA_URI, 0));
builder.setTriggerContentUpdateDelay(1);
builder.setTriggerContentMaxDelay(100);
JobInfo myCameraJob = builder.build();
JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
jobScheduler.schedule(myCameraJob);
}
PhotosContentJob Service --Working Code
#RequiresApi(api = Build.VERSION_CODES.O)
public class PhotosContentJob extends JobService {
SpreadsheetImage spreadsheetImage;
DatabaseHandler databaseHandler;
// Path segments for image-specific URIs in the provider.
static final List<String> EXTERNAL_PATH_SEGMENTS
= MediaStore.Images.Media.EXTERNAL_CONTENT_URI.getPathSegments();
// The columns we want to retrieve about a particular image.
static final String[] PROJECTION = new String[] {
MediaStore.Images.ImageColumns._ID, MediaStore.Images.ImageColumns.DATA
};
static final int PROJECTION_ID = 0;
static final int PROJECTION_DATA = 1;
// This is the external storage directory where cameras place pictures.
static final String DCIM_DIR = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM).getPath();
JobParameters mRunningParams;
// Check whether this job is currently scheduled.
public static boolean isScheduled(Context context) {
JobScheduler js = context.getSystemService(JobScheduler.class);
List<JobInfo> jobs = js.getAllPendingJobs();
if (jobs == null) {
return false;
}
for (int i=0; i<jobs.size(); i++) {
if (jobs.get(i).getId() == 11) {
return true;
}
}
return false;
}
// Cancel this job, if currently scheduled.
public static void cancelJob(Context context) {
JobScheduler js = context.getSystemService(JobScheduler.class);
js.cancel(11);
}
#Override
public boolean onStartJob(JobParameters params) {
Log.e("PhotosContentJob", "JOB STARTED!");
mRunningParams = params;
// Instead of real work, we are going to build a string to show to the user.
Date addedDate=new Date();
databaseHandler=new DatabaseHandler(getApplicationContext());
spreadsheetImage=new SpreadsheetImage();
StringBuilder sb = new StringBuilder();
// Did we trigger due to a content change?
if (params.getTriggeredContentAuthorities() != null) {
boolean rescanNeeded = false;
if (params.getTriggeredContentUris() != null) {
// If we have details about which URIs changed, then iterate through them
// and collect either the ids that were impacted or note that a generic
// change has happened.
ArrayList<String> ids = new ArrayList<>();
for (Uri uri : params.getTriggeredContentUris()) {
List<String> path = uri.getPathSegments();
if (path != null && path.size() == EXTERNAL_PATH_SEGMENTS.size()+1) {
// This is a specific file.
ids.add(path.get(path.size()-1));
} else {
// Oops, there is some general change!
rescanNeeded = true;
}
}
if (ids.size() > 0) {
// If we found some ids that changed, we want to determine what they are.
// First, we do a query with content provider to ask about all of them.
StringBuilder selection = new StringBuilder();
for (int i=0; i<ids.size(); i++) {
if (selection.length() > 0) {
selection.append(" OR ");
}
selection.append(MediaStore.Images.ImageColumns._ID);
selection.append("='");
selection.append(ids.get(i));
selection.append("'");
}
// Now we iterate through the query, looking at the filenames of
// the items to determine if they are ones we are interested in.
Cursor cursor = null;
boolean haveFiles = false;
try {
cursor = getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
PROJECTION, selection.toString(), null, null);
while (cursor.moveToNext()) {
// We only care about files in the DCIM directory.
String dir = cursor.getString(PROJECTION_DATA);
if (dir.startsWith(DCIM_DIR)) {
if (!haveFiles) {
haveFiles = true;
sb.append("New photos:\n");
}
sb.append(cursor.getInt(PROJECTION_ID));
sb.append(": ");
sb.append(dir);
sb.append("\n");
spreadsheetImage.ImagePath=dir;
spreadsheetImage.AddedOn=addedDate;
databaseHandler.AddSpreadSheetImage(spreadsheetImage);
}
}
} catch (SecurityException e) {
sb.append("Error: no access to media!");
} finally {
if (cursor != null) {
cursor.close();
}
}
}
} else {
// We don't have any details about URIs (because too many changed at once),
// so just note that we need to do a full rescan.
rescanNeeded = true;
}
if (rescanNeeded) {
sb.append("Photos rescan needed!");
}
} else {
sb.append("(No photos content)");
}
Toast.makeText(this, sb.toString(), Toast.LENGTH_LONG).show();
jobFinished(params, /*reschedule*/false);
scheduleCameraJob( /*immediate*/false);
return true;
}
#Override
public boolean onStopJob(JobParameters params) {
return false;
}
#RequiresApi(api = Build.VERSION_CODES.O)
private void scheduleCameraJob(Boolean Immediate) {
final Uri MEDIA_URI = Uri.parse("content://" + MediaStore.AUTHORITY + "/");
JobInfo.Builder builder = new JobInfo.Builder(11,
new ComponentName(this, PhotosContentJob.class.getName()));
// Look for specific changes to images in the provider.
builder.addTriggerContentUri(new JobInfo.TriggerContentUri(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
JobInfo.TriggerContentUri.FLAG_NOTIFY_FOR_DESCENDANTS));
// Also look for general reports of changes in the overall provider.
builder.addTriggerContentUri(new JobInfo.TriggerContentUri(MEDIA_URI, 0));
if (Immediate) {
// Get all media changes within a tenth of a second.
builder.setTriggerContentUpdateDelay(1);
builder.setTriggerContentMaxDelay(100);
} else {
builder.setTriggerContentUpdateDelay(1);
builder.setTriggerContentMaxDelay(100);
}
JobInfo myCameraJob = builder.build();
JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
int result =jobScheduler.schedule(myCameraJob);
if (result == JobScheduler.RESULT_SUCCESS) {
Log.e("JobScheduler"," JobScheduler OK");
} else {
Log.e("JobScheduler"," JobScheduler fails");
}
}
}
Scheduling a JobScheduler based on content observer URI is one time task only. When you receive the changes to your PhotosContentJob you need to reschedule the job again at end of onStartJob(JobParameters params) to continue receiving the updates.
Based on the documentation:
Note: TriggerContentUri() cannot be used in combination with
setPeriodic() or setPersisted(). To continually monitor for content
changes, schedule a new JobInfo before the app’s JobService finishes
handling the most recent callback.
Note:
Remember to reschedule job on Device reboot too. Since the scheduled Job will not persist across reboot.
This works (takes any single picture from the camera) for me:
public class PhotoJobService extends JobService {
private static final String TAG = PhotoJobService.class.getSimpleName();
{
Log.d(TAG, "This class object instance: " + this.toString() + ", " + jobinfoinststr());
}
private static String jobinfoinststr() {
return (
(JOB_INFO == null) ?
"null" : (
JOB_INFO.getClass().getSimpleName()
+ "#"
+ Integer.toHexString(java.lang.System.identityHashCode(JOB_INFO))
)
);
}
//static final Uri MEDIA_URI = Uri.parse("content://" + MediaStore.AUTHORITY + "/");
public static final int JOBSERVICE_JOB_ID = 499; // any number but avoid conflicts
private static JobInfo JOB_INFO;
private static boolean isRegistered(Context context) {
Log.d(TAG, "isRegistered() ?");
JobScheduler js = context.getSystemService(JobScheduler.class);
List<JobInfo> jobs = js.getAllPendingJobs();
if (jobs == null) {
Log.d(TAG, "JobService not registered ");
return false;
}
for (int i = 0; i < jobs.size(); i++) {
if (jobs.get(i).getId() == JOBSERVICE_JOB_ID) {
Log.d(TAG, "JobService is registered: " + jobinfoinststr());
return true;
}
}
Log.d(TAG, "JobService is not registered");
return false;
}
public static void startJobService(Context context) {
Log.d(TAG, "registerJob(): JobService init");
if (!isRegistered(context)) {
Log.d(TAG, "JobBuilder executes");
JobInfo.Builder builder = new JobInfo.Builder(JOBSERVICE_JOB_ID,
new ComponentName(context, PhotoJobService.class.getName()));
// Look for specific changes to images in the provider.
builder.addTriggerContentUri(
new JobInfo.TriggerContentUri(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
JobInfo.TriggerContentUri.FLAG_NOTIFY_FOR_DESCENDANTS));
// Also look for general reports of changes in the overall provider.
//builder.addTriggerContentUri(new JobInfo.TriggerContentUri(MEDIA_URI, 0));
// Get all media changes within a tenth of a second.
builder.setTriggerContentUpdateDelay(1);
builder.setTriggerContentMaxDelay(100);
JOB_INFO = builder.build();
Log.d(TAG, "JOB_INFO created " + jobinfoinststr());
JobScheduler scheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
int result = scheduler.schedule(JOB_INFO);
if (result == JobScheduler.RESULT_SUCCESS) {
Log.d(TAG, "JobScheduler OK");
} else {
Log.d(TAG, " JobScheduler fails " + result);
}
}
}
public static void stopJobService(Context context) {
Log.d(TAG, "cancelJob() " + jobinfoinststr());
JobScheduler js =
(JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
js.cancel(JOBSERVICE_JOB_ID);
isRegistered(context);
}
#Override
public boolean onStartJob(JobParameters params) {
Log.d(TAG, "onStartJob() " + this.toString() + ", "
+ ((JOB_INFO == null) ? "null" : JOB_INFO.getClass().getSimpleName() + "#" + Integer.toHexString(java.lang.System.identityHashCode(JOB_INFO))));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
if (params.getJobId() == JOBSERVICE_JOB_ID) {
if (params.getTriggeredContentAuthorities() != null) {
for (Uri uri : params.getTriggeredContentUris()) {
Log.d(TAG, "onStartJob() JobService Uri=" + uri.toString());
}
}
}
}
this.jobFinished(params, false); // false = do not reschedule
// manual reschedule
((JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE)).cancel(JOBSERVICE_JOB_ID);
startJobService(getApplicationContext());
return true; // false = no threads inside
}
//This method is called if the system has determined that you must stop execution of your job
//even before you've had a chance to call {#link #jobFinished(JobParameters, boolean)}.
#Override
public boolean onStopJob(JobParameters params) {
Log.d(TAG, "onStopJob() " + this.toString() + ", " + jobinfoinststr());
return false; // no restart from here
}
}

Android mark message as read not working properly

I am building small android application in which I am reading incoming message and I want to mark it as read message. For that I have added required permissions and also added receive for listening incoming messages.Everything is working fine except mark it as read process. I tried it in following ways:
private void markMessageRead(Context context, String number, String body) {
Uri uri = Uri.parse("content://sms/inbox");
Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
try{
while (cursor.moveToNext()) {
Debug.print("inside mark read before if ------ ");
Debug.print(cursor.getString(cursor.getColumnIndex("address"))+" "+number);
Debug.print(cursor.getInt(cursor.getColumnIndex("read"))+" ");
Debug.print(cursor.getString(cursor.getColumnIndex("body"))+" "+body);
if ((cursor.getString(cursor.getColumnIndex("address")).equals(number)) && (cursor.getInt(cursor.getColumnIndex("read")) == 0)) {
if (cursor.getString(cursor.getColumnIndex("body")).startsWith(body)) {
Debug.print("inside read message inside if ... ");
String SmsMessageId = cursor.getString(cursor.getColumnIndex("_id"));
ContentValues values = new ContentValues();
values.put("read", true);
context.getContentResolver().update(Uri.parse("content://sms/inbox"), values, "_id=" + SmsMessageId, null);
return;
}
}
}
}catch(Exception e)
{
}
}
//inside receiver side ...
#Override
public void onReceive(Context context, Intent intent) {
mContext = context;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
markMessageRead(mContext, message.getOriginatingAddress(), message.getMessageBody());
}
}, 2000);
}
Everything is working fine without any error. Only thing it is not marking my message as read message. Am I doing anything wrong. Need some help. Thank you.

How to receive status of download manager intent until download success or failed

Here's my problem.
I'm trying to download file from my server using download manager intent via Asynctask.
in my doInBackground of asynctask class, i was call download manager intent, and doinBackground will return boolean value when download finish (Success or Failed).
Here's my code
protected Boolean doInBackground(String... f_url) {
boolean flag = true;
boolean downloading =true;
try{
DownloadManager mManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
Request mRqRequest = new Request(
Uri.parse("http://"+model.getDownloadURL()));
long idDownLoad=mManager.enqueue(mRqRequest);
DownloadManager.Query query = null;
query = new DownloadManager.Query();
Cursor c = null;
if(query!=null) {
query.setFilterByStatus(DownloadManager.STATUS_FAILED|DownloadManager.STATUS_PAUSED|DownloadManager.STATUS_SUCCESSFUL|
DownloadManager.STATUS_RUNNING|DownloadManager.STATUS_PENDING);
} else {
return flag;
}
c = mManager.query(query);
if(c.moveToFirst()) {
int status =c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
while (downloading)
{ Log.i ("FLAG","Downloading");
if (status==DownloadManager.STATUS_SUCCESSFUL)
{ Log.i ("FLAG","done");
downloading = false;
flag=true;
break;
}
if (status==DownloadManager.STATUS_FAILED)
{Log.i ("FLAG","Fail");
downloading = false;
flag=false;
break;
}
c.moveToFirst();
}
}
return flag;
}
catch (Exception e)
{
flag = false;
return flag;
}
}
But DownloadManager status never jump on DownloadManager.STATUS_SUCCESSFUL or DownloadManager.STATUS_FAILED.
There's no need for the AsyncTask or the synchronous query. DownloadManager is already asynchronous. You should register a BroadcastReceiver for ACTION_DOWNLOAD_COMPLETE so that you get notified when the download completes (or fails).
There's a very good example at http://blog.vogella.com/2011/06/14/android-downloadmanager-example
You have to requery the download manager. The cursor stays the same even if the data changes. Try like this:
protected Boolean doInBackground(String... f_url) {
boolean flag = true;
boolean downloading =true;
try{
DownloadManager mManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
Request mRqRequest = new Request(
Uri.parse("http://"+model.getDownloadURL()));
long idDownLoad=mManager.enqueue(mRqRequest);
DownloadManager.Query query = null;
query = new DownloadManager.Query();
Cursor c = null;
if(query!=null) {
query.setFilterByStatus(DownloadManager.STATUS_FAILED|DownloadManager.STATUS_PAUSED|DownloadManager.STATUS_SUCCESSFUL|DownloadManager.STATUS_RUNNING|DownloadManager.STATUS_PENDING);
} else {
return flag;
}
while (downloading) {
c = mManager.query(query);
if(c.moveToFirst()) {
Log.i ("FLAG","Downloading");
int status =c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
if (status==DownloadManager.STATUS_SUCCESSFUL) {
Log.i ("FLAG","done");
downloading = false;
flag=true;
break;
}
if (status==DownloadManager.STATUS_FAILED) {
Log.i ("FLAG","Fail");
downloading = false;
flag=false;
break;
}
}
}
return flag;
}catch (Exception e) {
flag = false;
return flag;
}
}
Download Manager download files in asynchronous manner. So no need to put download manager inside an Asyntask.
You can use Receiver for get the status of download manager if download complete.
public class CheckDownloadComplete extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
if (action.equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE))
{
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0));
DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
Cursor cursor = manager.query(query);
if (cursor.moveToFirst()) {
if (cursor.getCount() > 0) {
int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
Long download_id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID,0);
// status contain Download Status
// download_id contain current download reference id
if (status == DownloadManager.STATUS_SUCCESSFUL)
{
String file = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
//file contains downloaded file name
// do your stuff here on download success
}
}
}
cursor.close();
}
}
}
Dont forget to add your receiver in Manifest
<receiver
android:name=".CheckDownloadComplete"
android:enabled="true"
android:exported="true" >
<intent-filter>
<action android:name="android.intent.action.DOWNLOAD_COMPLETE" />
</intent-filter>
</receiver>

Downloading images with webview

I m displaying a gallery from a mobile website in webview . How can i download those images from webview ? Are there any extra settings for webview ?
This solved my problem
` `#Override
public boolean shouldOverrideUrlLoading (WebView view, String url) {
boolean shouldOverride = false;
// We only want to handle requests for image files, everything else the webview
// can handle normally
if (url.endsWith(".jpg")) {
shouldOverride = true;
Uri source = Uri.parse(url);
// Make a new request pointing to the mp3 url
DownloadManager.Request request = new DownloadManager.Request(source);
// Use the same file name for the destination
File destinationFile = new File (destinationDir, source.getLastPathSegment());
request.setDestinationUri(Uri.fromFile(destinationFile));
// Add it to the manager
manager.enqueue(request);
}
return shouldOverride;
}``
make sure to add permissions for download manager, SD read, SD write!
I think the best way to do it is to parse the html code of the page and get the images url.
Just load the URL of the image with the webview.
webview.setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(url.contains("http://m.dudamobile.com/?source=DM_DIRECT") ){
DownloadManager dm = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
Request request = new Request(
Uri.parse(url));
enqueue = dm.enqueue(request);
return true;
}
else
{
view.loadUrl(url);
return true;
}
}}
//register your broadcast reciever of Download manager in the activity
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);
try{
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));
mNotificationManager.notify(1, notification);
// view.setImageURI(Uri.parse(url1));
/* Intent i = new Intent();
i.setAction(DownloadManager.ACTION_VIEW_DOWNLOADS);
startActivity(i);*/
}
}
}catch(NullPointerException e)
{
Toast.makeText(getApplicationContext(),"Item not downloadable :( ", Toast.LENGTH_LONG).show();
}
}
}
};
registerReceiver(receiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
`

Categories

Resources