Regaining revoked access to YouTube account - java

I created an application to upload certain custom thumbnails to YouTube videos and it works fine but, I revoked access to my application from my YouTube account to test some things and my application no longer asks for access. Now whenever I attempt to use my application it only responds with:
IOException: 400 Bad Request
{
"error" : "invalid_grant",
"error_description" : "Token has been expired or revoked."
}
com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request
{
"error" : "invalid_grant",
"error_description" : "Token has been expired or revoked."
}
I used the thumbnails set example from the YouTube page : https://developers.google.com/youtube/v3/docs/thumbnails/set
I was wondering what I could change in my following code to get the login page to show up again so I can give access to my application again, my code is here:
private void uploadThumbnail(String videoId, BufferedImage thumbnail){
YouTube youtube;
String IMAGE_FILE_FORMAT = "image/png";
// This OAuth 2.0 access scope allows for full read/write access to the
// authenticated user's account.
ArrayList<String> scopes = new ArrayList<>();
scopes.add("https://www.googleapis.com/auth/youtube");
try {
// Authorize the request.
Credential credential = Auth.authorize(scopes, "uploadthumbnail");
// This object is used to make YouTube Data API requests.
youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential).setApplicationName(
"youtube-cmdline-uploadthumbnail-sample").build();
get.saveImg(thumbnail,"./Screens/screenshot0t.png");
File imageFile = new File("./Screens/screenshot0t.png");
// Create an object that contains the thumbnail image file's
// contents.
InputStreamContent mediaContent = new InputStreamContent(
IMAGE_FILE_FORMAT, new BufferedInputStream(new FileInputStream(imageFile)));
mediaContent.setLength(imageFile.length());
// Create an API request that specifies that the mediaContent
// object is the thumbnail of the specified video.
Set thumbnailSet = youtube.thumbnails().set(videoId, mediaContent);
// Set the upload type and add an event listener.
MediaHttpUploader uploader = thumbnailSet.getMediaHttpUploader();
// Indicate whether direct media upload is enabled. A value of
// "True" indicates that direct media upload is enabled and that
// the entire media content will be uploaded in a single request.
// A value of "False," which is the default, indicates that the
// request will use the resumable media upload protocol, which
// supports the ability to resume an upload operation after a
// network interruption or other transmission failure, saving
// time and bandwidth in the event of network failures.
uploader.setDirectUploadEnabled(false);
// Set the upload state for the thumbnail image.
MediaHttpUploaderProgressListener progressListener = new MediaHttpUploaderProgressListener() {
#Override
public void progressChanged(MediaHttpUploader uploader) throws IOException {
switch (uploader.getUploadState()) {
// This value is set before the initiation request is
// sent.
case INITIATION_STARTED:
System.out.println("Initiation Started");
break;
// This value is set after the initiation request
// completes.
case INITIATION_COMPLETE:
System.out.println("Initiation Completed");
break;
// This value is set after a media file chunk is
// uploaded.
case MEDIA_IN_PROGRESS:
System.out.println("Upload in progress");
System.out.println("Upload percentage: " + uploader.getProgress());
break;
// This value is set after the entire media file has
// been successfully uploaded.
case MEDIA_COMPLETE:
System.out.println("Upload Completed!");
break;
// This value indicates that the upload process has
// not started yet.
case NOT_STARTED:
System.out.println("Upload Not Started!");
break;
}
}
};
uploader.setProgressListener(progressListener);
// Upload the image and set it as the specified video's thumbnail.
ThumbnailSetResponse setResponse = thumbnailSet.execute();
// Print the URL for the updated video's thumbnail image.
System.out.println("\n================== Uploaded Thumbnail ==================\n");
System.out.println(" - Url: " + setResponse.getItems().get(0).getDefault().getUrl());
get.deleteFile(imageFile.getPath());
} catch (GoogleJsonResponseException e) {
System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : "
+ e.getDetails().getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
e.printStackTrace();
}
}

I had the exact same issue with Gmail API, everything went back to normal after removing the stored credentials.
e.g. rm ~/.credentials/gmail-java-quickstart/StoredCredential

Related

How to send MMS with video/audio attachment programmatically on Android 12 using klinker package

I had this code working on Android 10 but something in Android 12 is breaking the logic. I am trying to send MMS with an attached video using the klinker package on my Android app on Android 12 phones. I can send pictures just fine but attaching audio and video do not work. The code used to be message.setVideo but that got deprecated. Now it is message.addVideo. But it is not working. It sets the bytes to the message but no MMS is sent. Does anyone know a fix for the klinker route or point me to a different direction to send audio and video MMS programmatically on Android 12?
Current code:
public void mmsSend() {
runOnUiThread(new Runnable() {
//#Override
public void run() {
try {
com.klinker.android.send_message.Settings sendSettings = new com.klinker.android.send_message.Settings();
sendSettings.setUseSystemSending(true);
Transaction transaction = new Transaction(mContext, sendSettings);
Message message = new Message(msgBodyMMS, PhoneNumberMMS);
byte[] mediaBytes = null;
//Convert media file to byte array
if (mAttachType != -1)
switch (mAttachType) {
case ProtocolConstants.MSG_NUM_MESSAGE_ATTACH_PICTURE:
File imgFile = new File(mAttachLocation);
if (imgFile.exists()) {
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
message.setImage(myBitmap);
}
break;
case ProtocolConstants.MSG_NUM_MESSAGE_ATTACH_AUDIO:
mediaBytes = convertMediaToBytes(mAttachLocation);
message.addAudio(mediaBytes);
break;
case ProtocolConstants.MSG_NUM_MESSAGE_ATTACH_VIDEO:
mediaBytes = convertMediaToBytes(mAttachLocation);
message.addVideo(mediaBytes);
break;
}
else if (mediaBytes == null) {
message.setImage(BitmapFactory.decodeResource(mContext.getResources(), R.drawable.android));
}
message.setFromAddress(Utils.getMyPhoneNumber(mContext));
message.setSave(false);
message.setSubject(msgBodyMMS);
Uri uri = Uri.parse("content://mms-sms/conversations/");
message.setMessageUri(uri);
transaction.sendNewMessage(message, Transaction.NO_THREAD_ID);
Log.d(TAG, "mmsSend() : MMS Sent Successfully");
lastMMSMessageSent = ClientProtocol.Mms_Send_Ok();
appClass.BluetoothWrite(lastMMSMessageSent);
Toast.makeText(mContext.getApplicationContext(),"MMS Sent Successfully",Toast.LENGTH_LONG ).show();
} catch (Exception e) {
Log.d(TAG, "mmsSend() : MMS send failed " + e.toString());
Toast.makeText(mContext.getApplicationContext(),
"MMS failed, please try again later ! ",
Toast.LENGTH_LONG).show();
}
}
});
}

How to generate access token in Java for Google AutoML Vision API without gcloud?

I am making an Android App that will utilize the Google AutoML Vision API. I am looking for a way to get a permanent access token or generate them in code so that I do not need to use gcloud everytime I want to use my app. How would I go about doing this?
I have created the AutoML model, set up my service account, and coded my app in Android Studio so that it makes the request to the API using Volley. The problem is, they require you to generate and pass an access token using gcloud. I can generate the token and put it in my code but it only lasts for an hour and then it expires. The REST API requires the access token as shown below.
curl -X POST -H "Content-Type: application/json" \
-H "Authorization: Bearer $(gcloud auth application-default print-access-
token)"
I have looked into different ways around this problem. For example, there are some Google Client Libraries for Java and Google Cloud Applications that show how to add the service account credentials into the code. I am confused how I would add the Json key file into the code when running it from a phone. I have also read that Firebase could be used but I am unfamiliar about what the process for that would be.
Currently, I will open up gcloud on my computer, generate the access token, paste it into my code and run the app as follows with the header and this returns the desired results for up to an hour until the access code expires.
#Override
public Map<String, String> getHeaders() throws AuthFailureError{
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "Bearer " + accesstoken);
return headers;
}
I would like this to be a stand alone application that can run on an Android phone. What is the best way to go about doing this?
UPDATE:
I was able to add the file into Android Studio and then use some functions to get an access token and it appears to work in the Emulator. I am not sure how secure this method is though because the json file with the key needs to be kept private.
InputStream is = getAssets().open("app.json");
GoogleCredentials credentials =
GoogleCredentials.fromStream(i).createScoped(Lists.newArrayList(scope));
credentials.refreshIfExpired();
AccessToken accesstoken = credentials.getAccessToken();
Add firebase to you android project. https://firebase.google.com/docs/android/setup You will create a project in Firebase and download a json file for configuration and add it in app directory. Add also dependencies in gradle files.
On Firebase console go to ML Kit section and create a AUTML model with your photos.
Train the model
When the training is finished you can download your model and downloaded 3 files in your assets/model directory. And it is ready to use. By this way you will use Firebase AutoML SDK and you dont need to generate the token.
Use your model and do predictions from application.
Steps are :
Prepare image for prediction
Prepare the model
Get the image labeler
Process the image for classification
public void findLabelsWithAutoML() {
Bitmap bitmap = null;
File file = new File(currentPhotoPath);
System.out.println("file "+file);
try {
bitmap = MediaStore.Images.Media
.getBitmap(getContentResolver(), Uri.fromFile(file));
} catch (Exception e) {
e.printStackTrace();
}
FirebaseVisionImageMetadata metadata = new FirebaseVisionImageMetadata.Builder()
.setWidth(480) // 480x360 is typically sufficient for
.setHeight(360) // image recognition
.setFormat(FirebaseVisionImageMetadata.IMAGE_FORMAT_NV21)
.setRotation(FirebaseVisionImageMetadata.ROTATION_0)
.build();
FirebaseVisionImage firebaseVisionImage = FirebaseVisionImage.fromBitmap(bitmap);
System.out.println("firebaseVisionImage :"+firebaseVisionImage);
FirebaseAutoMLLocalModel localModel = new FirebaseAutoMLLocalModel.Builder()
.setAssetFilePath("model/manifest.json")
.build();
FirebaseVisionOnDeviceAutoMLImageLabelerOptions labelerOptions = new FirebaseVisionOnDeviceAutoMLImageLabelerOptions.Builder(localModel)
.setConfidenceThreshold(0.65F) // Evaluate your model in the Firebase console
// to determine an appropriate value.
.build();
FirebaseVisionImageLabeler firebaseVisionImageLabeler = null;
try {
firebaseVisionImageLabeler = FirebaseVision.getInstance().getOnDeviceAutoMLImageLabeler(labelerOptions);
} catch (Exception e) {
e.printStackTrace();
}
firebaseVisionImageLabeler.processImage(firebaseVisionImage)
.addOnSuccessListener(new OnSuccessListener<List<FirebaseVisionImageLabel>>() {
#Override
public void onSuccess(List<FirebaseVisionImageLabel> labels) {
for (FirebaseVisionImageLabel label : labels) {
System.out.println("label " + label.getText() + " score: " + (label.getConfidence() * 100));
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
//
}
});
}

Firestore timeout for android

I am currently building an app that saves the user's blog post in Firestore server. Everything is working fine, but I found out that the post was not uploaded under the unstable internet connection.
I tried to set a timeout to the Firestore instance, but it seems like there's no timeout option for Firestore library. The problem is, because there's no timeout setting, the app doesn't know when to dismiss the uploading screen (Spinner dialog).
I was thinking about creating a Handler or Observable or Thread and setting the timeout manually. After the specified timeout period, let the app dismiss the uploading screen. However, Firestore client will keep retrying the upload in the background even after the timeout. So this approach won't be suitable for this case...
Is there any solution for this? If I can set the timeout for the Firestore client itself, meaning letting the client to call onFailure() after the given timeout period, I can just save the post as draft in the local storage and try it again when the device is back to stable connection.
Firestore will immediately add the document to its local cache. It will then try to synchronize that document with the server. To detect whether it will be able to do so, have a look at Gastón's answer.
To detect when the document has been written to the server, use a SuccessListener. This example from the Firestore documentation on adding documents shows how:
// Add a new document with a generated id.
Map<String, Object> data = new HashMap<>();
data.put("name", "Tokyo");
data.put("country", "Japan");
db.collection("cities")
.add(data)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
Log.d(TAG, "DocumentSnapshot written with ID: " + documentReference.getId());
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error adding document", e);
}
});
The best way of doing this is attaching a boolean that will let you know if you have internet before doing something (this is just to dismiss your spinner, as firestore has offline features like realtime database)
public static boolean hasActiveInternetConnection(Context context) {
if (isNetworkAvailable(context)) {
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
return (urlc.getResponseCode() == 200);
} catch (IOException e) {
Log.e(LOG_TAG, "Error checking internet connection", e);
}
} else {
Log.d(LOG_TAG, "No network available!");
}
return false;
}
so you should check first if you have an active connection , this method will ping google.com and check for internet connection, if is not reachable after 1.5 seconds it will return false
so you should do something like this (pseudocode)
if(hasActiveInternetConnection)
doyourfirebaseuploadstuff
else
spinner.dismiss()
Toast(please check your internet connection and try again)
Remember to add your internet permissions in your manifest
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
EDIT:
Another cool method and maybe more readable for someones can be this one
public boolean isInternetWorking() {
boolean success = false;
try {
URL url = new URL("https://google.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(10000);
connection.connect();
success = connection.getResponseCode() == 200;
} catch (IOException e) {
e.printStackTrace();
}
return success;
}
it just works like the other one , instead that this will just wait for 10 seconds untill it returns the internet status

YouTube API 3 Upload Video - Access not configured - Android

I am working on an Android app that records video and allows the user to upload it directly to YouTube using the YouTube Data API v3.
I have set up my app in Google's API console. Under services, I have YouTube Data API v3 enabled. Under API access I have both a section "Client ID for installed applications" (including a Client ID and Client Secret) and a section "Simple API Access" -> "Key for Android apps (with certificates)" (which includes an API key and an "Android Apps" section, which is left blank for now, i.e. allow all Android apps, but I have tried it with setting my android key).
I have based my code from a number of places, primarily:
https://developers.google.com/youtube/v3/code_samples/java#upload_a_video
and
https://code.google.com/p/google-api-java-client/source/browse/tasks-android-sample/src/main/java/com/google/api/services/samples/tasks/android/TasksSample.java?repo=samples
The upload initialises OK, starts the AsyncTask, but then I get an IOException thrown saying:
{
"code": 403,
"errors": [
{
"domain": "usageLimits",
"message": "Access Not Configured",
"reason": "accessNotConfigured"
}
],
"message": "Access Not Configured"
}
Similar SO posts suggest it is to do with my Google API console settings, but I can't find anything wrong. Any suggestions? I wonder if it is because I am not providing my client ID or secret anywhere ...
Thanks.
My code runs from a fragment containing a list of videos. The relevant sections are:
-- Init
public class UploadFragment extends Fragment {
private static GoogleAccountCredential credential;
private static final HttpTransport transport = AndroidHttp.newCompatibleTransport();
private static final JsonFactory jsonFactory = new GsonFactory();
public YouTube youtube;
List<String> scopes = Lists.newArrayList(YouTubeScopes.YOUTUBE_UPLOAD);
private static String VIDEO_FILE_FORMAT = "video/*";
static final int REQUEST_GOOGLE_PLAY_SERVICES = 0;
static final int REQUEST_AUTHORIZATION = 1;
static final int REQUEST_ACCOUNT_PICKER = 2;
-- Setup credential and youtube
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
...
credential = googleAccountCredential(scopes);
youtube = new YouTube.Builder(transport, jsonFactory, credential)
.setApplicationName("MyAppName")
.build();
...
}
-- On button click, initiate upload
#Override void onClick(View v) {
...
if (hasGooglePlayServices()) {
uploadYouTubeVideos();
...
}
-- Build credential
/**
* Get the credential to authorize the installed application to access user's protected data.
*
* #param scopes list of scopes needed to run YouTube upload.
*/
private static GoogleAccountCredential googleAccountCredential(List<String> scopes) throws Exception {
credential = GoogleAccountCredential.usingOAuth2(context, scopes)
.setSelectedAccountName(PreferenceManager.getAccountName());
return credential;
}
-- Request an account from the user
/**
* Fire intent to get user to choose account
* Return to onActivityResult
*/
private void chooseAccount() {
startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
}
-- On return from the user choosing and account
-- / requesting authorization
/**
* Returns from chooseAccount and from request authorization
*/
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_AUTHORIZATION:
if (resultCode == Activity.RESULT_OK) {
uploadYouTubeVideos();
} else {
chooseAccount();
}
break;
case REQUEST_ACCOUNT_PICKER:
if (resultCode == Activity.RESULT_OK && data != null && data.getExtras() != null) {
String accountName = data.getExtras().getString(AccountManager.KEY_ACCOUNT_NAME);
if (accountName != null) {
credential.setSelectedAccountName(accountName);
PreferenceManager.setAccountName(accountName);
uploadYouTubeVideos();
}
}
break;
}
}
-- Called multiple times depending on what information we have
-- account, authorization, etc.
/**
* Uploads user selected video to the user's YouTube account using OAuth2
* for authentication.
*
* #param videoFile file to be uploaded
*/
public void uploadYouTubeVideos() {
if (credential.getSelectedAccountName() == null) {
chooseAccount();
} else {
File videoFile = getVideoFile();
Insert videoInsert = prepareUpload(videoFile);
new VideoUploadAsyncTask().execute(videoInsert);
}
}
-- Prepare the upload
-- Puts everything together
/**
* Prepare upload. Just leaves execute to be run in AsyncTask.
*
* #param videoFile file to be uploaded
* #return
*/
public Insert prepareUpload( File videoFile ) {
try {
// Add extra information to the video before uploading.
Video videoObjectDefiningMetadata = new Video();
// Set the video to public (default).
VideoStatus status = new VideoStatus();
status.setPrivacyStatus("public");
videoObjectDefiningMetadata.setStatus(status);
// We set a majority of the metadata with the VideoSnippet object.
VideoSnippet snippet = new VideoSnippet();
// Video file name.
snippet.setTitle(videoFile.getName());
snippet.setDescription("Test description");
// Set keywords.
List<String> tags = new ArrayList<String>();
tags.add("test");
snippet.setTags(tags);
// Set completed snippet to the video object.
videoObjectDefiningMetadata.setSnippet(snippet);
InputStreamContent mediaContent = new InputStreamContent(
VIDEO_FILE_FORMAT, new BufferedInputStream(new FileInputStream(videoFile)));
mediaContent.setLength(videoFile.length());
/*
* The upload command includes: 1. Information we want returned after file is successfully
* uploaded. 2. Metadata we want associated with the uploaded video. 3. Video file itself.
*/
YouTube.Videos.Insert videoInsert = youtube.videos()
.insert("snippet,statistics,status", videoObjectDefiningMetadata, mediaContent);
// Set the upload type and add event listener.
MediaHttpUploader uploader = videoInsert.getMediaHttpUploader();
/*
* Sets whether direct media upload is enabled or disabled. True = whole media content is
* uploaded in a single request. False (default) = resumable media upload protocol to upload
* in data chunks.
*/
uploader.setDirectUploadEnabled(false);
MediaHttpUploaderProgressListener progressListener = new MediaHttpUploaderProgressListener() {
public void progressChanged(MediaHttpUploader uploader) throws IOException {
switch (uploader.getUploadState()) {
case INITIATION_STARTED:
Log.d(TAG, "Upload file: Initiation Started");
break;
case INITIATION_COMPLETE:
Log.d(TAG, "Upload file: Initiation Completed");
break;
case MEDIA_IN_PROGRESS:
Log.d(TAG, "Upload file: Upload in progress");
Log.d(TAG, "Upload file: Upload percentage: " + uploader.getProgress());
break;
case MEDIA_COMPLETE:
Log.d(TAG, "Upload file: Upload Completed!");
break;
case NOT_STARTED:
Log.d(TAG, "Upload file: Upload Not Started!");
break;
}
}
};
uploader.setProgressListener(progressListener);
return videoInsert;
} catch (FileNotFoundException e) {
Log.e(TAG, "File not found: " + e.getMessage());
return null;
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
return null;
}
}
-- Require Google play services
/**
* Pop up dialog requesting user to download Google Play Services.
* Returns to onActivityResult
*/
void showGooglePlayServicesAvailabilityErrorDialog(final int connectionStatusCode) {
getActivity().runOnUiThread(new Runnable() {
public void run() {
Dialog dialog =
GooglePlayServicesUtil.getErrorDialog(connectionStatusCode, getActivity(),
REQUEST_GOOGLE_PLAY_SERVICES);
dialog.show();
}
});
}
-- AsyncTask that runs execute on the upload
public class VideoUploadAsyncTask extends AsyncTask<Insert, Void, Void> {
#Override
protected Void doInBackground( Insert... inserts ) {
Insert videoInsert = inserts[0];
try {
Video returnVideo = videoInsert.execute();
} catch (final GooglePlayServicesAvailabilityIOException availabilityException) {
showGooglePlayServicesAvailabilityErrorDialog(
availabilityException.getConnectionStatusCode());
} catch (UserRecoverableAuthIOException userRecoverableException) {
startActivityForResult(
userRecoverableException.getIntent(), UploadFragment.REQUEST_AUTHORIZATION);
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
}
return null;
}
}
}
The answer provided by #Ibrahim was almost correct for me. What I needed to do was edit my API configuration. However, it was not the "Simple API access" section I needed to edit, it was the settings after clicking the button "Create another client Id".
Then I could select "Installed application" -> "Android". After inputting my package name and SHA1, and waiting 15 minutes, my app worked as expect. I also have the "Simple API access" set up. I am not sure if you need both or not.
Yes, YouTube Direct Lite for Android is similar. You have to configure simple API access with your SHA1 key. Explains here.

How to get the network uri of a file being downloaded from the Download Manager in Android

I am writing an application wherein I want to detect if a download has started and retrieve the URI of the file being downloaded and then cancel the download from the Download Manager. I am doing this so that I can send this URI somewhere else.
The trouble is that I can detect when a download begins by querying the Download Manager, but is there a method or a constant variable in Download Manager from which I can also get the URL of the file being downloaded
Ok its weird answering your own question, but I finally figured out how to do this. There is a DownloadManager class in android.app, which stores a list of all http downloads initiated and their statuses. These can be filtered out based on whether the download is 'RUNNING', 'PENDING', 'PAUSED' and so on.
This list can be read into a cursor and one of the columns of the result is 'COLUMN_URI', which is the url from where the file is being downloaded. A sample code where I have used it is as given below:
public void readDownloadManager() {
DownloadManager.Query query = null;
DownloadManager downloadManager = null;
Cursor c = null;
try {
query = new DownloadManager.Query();
downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
//Just for testing I initiated my own download from this url. When an http
// reuest for this url is made, since download is taking place, it gets saved in
// the download manager.
Request request = new Request(Uri.parse("http://ocw.mit.edu/courses" +
"/aeronautics-and-astronautics/16-100-aerodynamics-fall-2005" +
"/lecture-notes/16100lectre1_kvm.pdf"));
downloadManager.enqueue(request);
query.setFilterByStatus(DownloadManager.STATUS_PENDING);
c = downloadManager.query(query);
if(true){
int statusColumnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
int urlColumnIndex = c.getColumnIndex(DownloadManager.COLUMN_URI);
long downloadProcessIdColumnNo = c.getColumnIndex(DownloadManager.COLUMN_ID);
Log.d("Column Count", ((Integer)c.getCount()).toString());
if(c.getCount() > 0){
String url="";
c.moveToLast();
if(c.isLast()){
url = c.getString(urlColumnIndex);
downloadManager.remove(downloadProcessIdColumnNo);
Log.d("Count after remove", ((Integer)c.getCount()).toString());
}
Log.d("After", "Stopped Working");
//Here I am sending the url to another activity, where I can work with it.
Intent intent = new Intent(EasyUploadMainMenu.this, EasyUploadActivity.class);
Bundle b = new Bundle();
b.putString("url", url);
intent.putExtras(b);
startActivity(intent);
Log.d("url:", url);
}
}
} catch (NullPointerException ex) {
ex.printStackTrace();
}
}

Categories

Resources