Android Expansion file won't trigger onDownloadStateChanged? - android

I'm trying to make my app download an expansion file. Here's my code so far.
public class main extends Activity implements IDownloaderClient {
TextView tv1;
Button mcButt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//////////
tv1 = (TextView)findViewById(R.id.textView1);
// Check whether the file have been downloaded.
String mainFileName = Helpers.getExpansionAPKFileName(this, true, 1);
boolean fileExists = Helpers.doesFileExist(this, mainFileName, 32921796L, false);
if (!fileExists) {
Intent launcher = getIntent();
Intent fromNotification = new Intent(this, getClass());
fromNotification.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
fromNotification.setAction(launcher.getAction());
if (launcher.getCategories() != null) {
for (String cat : launcher.getCategories())
{ fromNotification.addCategory(cat); }
}
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, fromNotification, PendingIntent.FLAG_UPDATE_CURRENT);
try {
int result = DownloaderClientMarshaller.startDownloadServiceIfRequired( this, pendingIntent, ExpansionFileDownloaderService.class);
if (DownloaderClientMarshaller.NO_DOWNLOAD_REQUIRED != result) {
// implement Downloading UI.
tv1.setText("Need to download.");
return;
}
} catch (Exception e) {
Log.e("apk-expansion-files", "NameNotFoundException occurred. " + e.getMessage(), e);
}
}
tv1.setText("Downloaded!");
}
///////////////////////////////////////////////////
#Override
public void onServiceConnected(Messenger m) {
tv1.setText("onServiceConnected: " + m.toString() );
}
///////////
#Override
public void onDownloadStateChanged(int newState) {
tv1.setText("onDownloadStateChanged: " + String.valueOf(newState) );
}
////////////
#Override
public void onDownloadProgress(DownloadProgressInfo progress) {
ProgressBar mPB = (ProgressBar)findViewById(R.id.progressBar1);
progress.mOverallTotal = progress.mOverallTotal;
mPB.setMax((int) (progress.mOverallTotal >> 8));
mPB.setProgress((int) (progress.mOverallProgress >> 8));
tv1.setText(Long.toString(progress.mOverallProgress * 100 / progress.mOverallTotal) + "%");
tv1.setText(Helpers.getDownloadProgressString(progress.mOverallProgress,progress.mOverallTotal));
}
}
The file does download fine, but it does not trigger onDownloadProgress or onDownloadStateChanged during or after download.
What comes to mind, is that DownloaderClientMarshaller need to be somehow connected with IDownloaderClient which is implemented into the activity...
Any ideas? Thanks!

You should create and stub and connect it to the context. Then, the events will be sent to your IDownloaderClient.
if (DownloaderClientMarshaller.NO_DOWNLOAD_REQUIRED != result) {
downloaderClientStub = DownloaderClientMarshaller.CreateStub(this,
YourDownloaderServiceClass.class);
downloaderClientStub.connect(this);
}

Related

NFC tag(for NfcA) scan works only from the second time

I wrote a custom plugin to read blocks of data from an NfcA(i.e.non-ndef) tag. It seems to work fine , but only after the second scan. I am using Activity intent to derive the "NfcAdapter.EXTRA_TAG" to later use it for reading the values. I am also updating the Intents in onNewIntent(). OnNewIntent gets called after the second scan and after that I get result all the time.But in the first scan onNewIntent does not gets called, hence I end up using the Activity tag that does not have "NfcAdapter.EXTRA_TAG", hence I get null. Please see the my code below.
SE_NfcA.java(my native code for plugin)
#Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
String Result = "";
String TypeOfTalking = "";
if (action.contains("TalkToNFC"))
{
JSONObject arg_object = args.getJSONObject(0);
TypeOfTalking = arg_object.getString("type");
if(TypeOfTalking != "")
{
if (TypeOfTalking.contains("readBlock"))
{
if(TypeOfTalking.contains("#"))
{
try
{
String[] parts = TypeOfTalking.split("#");
int index = Integer.parseInt(parts[1]);
Result = Readblock(cordova.getActivity().getIntent(),(byte)index);
callbackContext.success(Result);
}
catch(Exception e)
{
callbackContext.error("Exception Reading "+ TypeOfTalking + "due to "+ e.toString());
return false;
}
}
}
else
{
return false;
}
}
else
{
return false;
}
}
else
{
return false;
}
return true;
}
#Override
public void onNewIntent(Intent intent) {
ShowAlert("onNewIntent called");
Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
super.onNewIntent(intent);
getActivity().setIntent(intent);
savedTag = tagFromIntent;
savedIntent = intent;
}
#Override
public void onPause(boolean multitasking) {
Log.d(TAG, "onPause " + getActivity().getIntent());
super.onPause(multitasking);
if (multitasking) {
// nfc can't run in background
stopNfc();
}
}
#Override
public void onResume(boolean multitasking) {
Log.d(TAG, "onResume " + getActivity().getIntent());
super.onResume(multitasking);
startNfc();
}
public String Readblock(Intent Intent,byte block) throws IOException{
byte[] response = new byte[]{};
if(Intent != null)
{
Tag myTag = Intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
if(savedTag != null)
myTag = savedTag;
if(myTag != null)
{
try{
Reader nTagReader = new Reader(myTag);
nTagReader.close();
nTagReader.connect();
nTagReader.SectorSelect(Sector.Sector0);
response = nTagReader.fast_read(block, block);
nTagReader.close();
return ConvertH(response);
}catch(Exception e){
ShowAlert(e.toString());
}
}
else
ShowAlert("myTag is null.");
}
return null;
}
private void createPendingIntent() {
if (pendingIntent == null) {
Activity activity = getActivity();
Intent intent = new Intent(activity, activity.getClass());
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);
pendingIntent = PendingIntent.getActivity(activity, 0, intent, 0);
}
}
private void startNfc() {
createPendingIntent(); // onResume can call startNfc before execute
getActivity().runOnUiThread(new Runnable() {
public void run() {
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity());
if (nfcAdapter != null && !getActivity().isFinishing()) {
try {
nfcAdapter.enableForegroundDispatch(getActivity(), getPendingIntent(), getIntentFilters(), getTechLists());
if (p2pMessage != null) {
nfcAdapter.setNdefPushMessage(p2pMessage, getActivity());
}
} catch (IllegalStateException e) {
// issue 110 - user exits app with home button while nfc is initializing
Log.w(TAG, "Illegal State Exception starting NFC. Assuming application is terminating.");
}
}
}
});
}
private void stopNfc() {
Log.d(TAG, "stopNfc");
getActivity().runOnUiThread(new Runnable() {
public void run() {
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity());
if (nfcAdapter != null) {
try {
nfcAdapter.disableForegroundDispatch(getActivity());
} catch (IllegalStateException e) {
// issue 125 - user exits app with back button while nfc
Log.w(TAG, "Illegal State Exception stopping NFC. Assuming application is terminating.");
}
}
}
});
}
private Activity getActivity() {
return this.cordova.getActivity();
}
private PendingIntent getPendingIntent() {
return pendingIntent;
}
private IntentFilter[] getIntentFilters() {
return intentFilters.toArray(new IntentFilter[intentFilters.size()]);
}
private String[][] getTechLists() {
//noinspection ToArrayCallWithZeroLengthArrayArgument
return techLists.toArray(new String[0][0]);
}
}
My index.js file
nfc.addTagDiscoveredListener(
function(nfcEvent){
console.log(nfcEvent.tag.id);
alert(nfcEvent.tag.id);
window.echo("readBlock#88");//call to plugin
},
function() {
alert("Listening for NFC tags.");
},
function() {
alert("NFC activation failed.");
}
);
SE_NfcA.js(plugin interface for interaction b/w index.js and SE_NfcA.java)
window.echo = function(natureOfTalk)
{
alert("Inside JS Interface, arg =" + natureOfTalk);
cordova.exec(function(result){alert("Result is : "+result);},
function(error){alert("Some Error happened : "+ error);},
"SE_NfcA","TalkToNFC",[{"type": natureOfTalk}]);
};
I guess I have messed up with the Intents/Activity Life-Cycle, please help. TIA!
I found a tweak/hack and made it to work.
Before making any call to read or write, I made one dummy Initialize call.
window.echo("Initialize");
window.echo("readBlock#88");//call to plugin to read.
And in the native code of the plugin, on receiving the "Initialize" token I made a startNFC() call.
else if(TypeOfTalking.equalsIgnoreCase("Initialize"))
{
startNfc();
}

How to Record Android Screen Video programmatically in KitKat 4.4

I know this question has been asked so many times and there are so many questions, answers and discussions available. But I don't know what to do and what not to do.
I already referred to the links below to get solution with no luck.
https://stackoverflow.com/questions/23438767/how-to-record-video-on-kitkat-4-4
https://stackoverflow.com/questions/23185125/i-cannot-screen-record-with-my-kitkat-4-4-moto-x
Android KitKat start screenrecord from App
screen recorder with kitkat
Screen Recording kitkat with button
With lots of search I didn't get any simple example to achieve this task. Since 2 days i am trying to achieve this but with no success.
So the simple question is whether it is possible to record video of our own screen in android. I just heard that it is possible from android 4.4 Kitkat and i also check some app from market.
I know to do this our device should be rooted and other things which required to do this.
But I am not getting how to develop this programmatically. If any one have any idea then please guide me how to do this. or any example or code will be great help.
I appreciate your any kind of help.
I try to develop with this simple piece of code but not getting anything
public void startRecording(View v) {
File recordfolder = Environment.getExternalStorageDirectory();
String record = "su — bit rate 8000000 --time-limit 30 "
+ recordfolder + "Record.mp4";
recordfolder.mkdir();
try {
Process screenrecording = Runtime.getRuntime().exec(record);
} catch (IOException e) {
e.printStackTrace();
}
}
so basically I don't know what i have to do with this Process screenrecording, I mean how can I start progress.
Good Question But the answer depends on what type of platform you want to use to record the screen in android.
Here are some tricks.....
1) Using this class you can record the screen fort that you required rooted device you can test this in genymotion 4.4 also.
public static class MainFragment extends Fragment {
private Context mContext;
private EditText mWidthEditText;
private EditText mHeightEditText;
private EditText mBitrateEditText;
private EditText mTimeEditText;
private Button mRecordButton;
public MainFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
mContext = getActivity();
mRecordButton = (Button) rootView.findViewById(R.id.btn_record);
mRecordButton.setOnClickListener(RecordOnClickListener);
mWidthEditText = (EditText) rootView.findViewById(R.id.et_width);
mHeightEditText = (EditText) rootView.findViewById(R.id.et_height);
mBitrateEditText = (EditText) rootView
.findViewById(R.id.et_bitrate);
mBitrateEditText.addTextChangedListener(BitrateTextWatcher);
mTimeEditText = (EditText) rootView.findViewById(R.id.et_time);
mTimeEditText.addTextChangedListener(TimeTextWatcher);
return rootView;
}
private TextWatcher BitrateTextWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i,
int i2, int i3) {
// Not used.
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i2,
int i3) {
if (TextUtils.isEmpty(charSequence)) {
return;
}
int value = Integer.valueOf(charSequence.toString());
if (value > 50 || value == 0) {
mBitrateEditText.setError(mContext
.getString(R.string.error_bitrate_edittext));
return;
}
mTimeEditText.setError(null);
}
#Override
public void afterTextChanged(Editable editable) {
// Not used.
}
};
private TextWatcher TimeTextWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i,
int i2, int i3) {
// Not used.
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i2,
int i3) {
if (TextUtils.isEmpty(charSequence)) {
return;
}
int value = Integer.valueOf(charSequence.toString());
if (value > 180 || value == 0) {
mTimeEditText.setError(mContext
.getString(R.string.error_time_editext));
return;
}
mTimeEditText.setError(null);
}
#Override
public void afterTextChanged(Editable editable) {
// Not used.
}
};
private View.OnClickListener RecordOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!TextUtils.isEmpty(mTimeEditText.getError())
|| !TextUtils.isEmpty(mBitrateEditText.getError())) {
Toast.makeText(mContext,
mContext.getString(R.string.toast_invalid_values),
Toast.LENGTH_LONG).show();
return;
}
boolean widthSet = !TextUtils.isEmpty(mWidthEditText.getText());
boolean heightSet = !TextUtils.isEmpty(mHeightEditText
.getText());
if ((!widthSet && heightSet) || (widthSet && !heightSet)) {
Toast.makeText(mContext,
mContext.getString(R.string.error_invalid_wxh),
Toast.LENGTH_LONG).show();
return;
}
boolean bitrateSet = !TextUtils.isEmpty(mBitrateEditText
.getText());
boolean timeSet = !TextUtils.isEmpty(mTimeEditText.getText());
StringBuilder stringBuilder = new StringBuilder(
"/system/bin/screenrecord");
if (widthSet) {
stringBuilder.append(" --size ")
.append(mWidthEditText.getText()).append("x")
.append(mHeightEditText.getText());
}
if (bitrateSet) {
stringBuilder.append(" --bit-rate ").append(
mBitrateEditText.getText());
}
if (timeSet) {
stringBuilder.append(" --time-limit ").append(
mTimeEditText.getText());
}
// TODO User definable location.
stringBuilder
.append(" ")
.append(Environment.getExternalStorageDirectory()
.toString()).append("/recording.mp4");
Log.d("TAG", "comamnd: " + stringBuilder.toString());
try {
new SuTask(stringBuilder.toString().getBytes("ASCII"))
.execute();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
};
private class SuTask extends AsyncTask<Boolean, Void, Boolean> {
private final byte[] mCommand;
public SuTask(byte[] command) {
super();
this.mCommand = command;
}
#Override
protected Boolean doInBackground(Boolean... booleans) {
try {
Process sh = Runtime.getRuntime().exec("su", null, null);
OutputStream outputStream = sh.getOutputStream();
outputStream.write(mCommand);
outputStream.flush();
outputStream.close();
final NotificationManager notificationManager = (NotificationManager) mContext
.getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(RUNNING_NOTIFICATION_ID,
createRunningNotification(mContext));
sh.waitFor();
return true;
} catch (InterruptedException e) {
e.printStackTrace();
Toast.makeText(mContext,
mContext.getString(R.string.error_start_recording),
Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(mContext,
mContext.getString(R.string.error_start_recording),
Toast.LENGTH_LONG).show();
}
return false;
}
#Override
protected void onPostExecute(Boolean bool) {
super.onPostExecute(bool);
if (bool) {
final NotificationManager notificationManager = (NotificationManager) mContext
.getSystemService(NOTIFICATION_SERVICE);
notificationManager.cancel(RUNNING_NOTIFICATION_ID);
File file = new File(Environment
.getExternalStorageDirectory().toString()
+ "/recording.mp4");
notificationManager.notify(FINISHED_NOTIFICATION_ID,
createFinishedNotification(mContext, file));
}
}
private Notification createRunningNotification(Context context) {
Notification.Builder mBuilder = new Notification.Builder(
context)
.setSmallIcon(android.R.drawable.stat_notify_sdcard)
.setContentTitle(
context.getResources().getString(
R.string.app_name))
.setContentText("Recording Running")
.setTicker("Recording Running")
.setPriority(Integer.MAX_VALUE).setOngoing(true);
return mBuilder.build();
}
private Notification createFinishedNotification(Context context,
File file) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "video/mp4");
PendingIntent pendingIntent = PendingIntent.getActivity(
context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder mBuilder = new Notification.Builder(
context)
.setSmallIcon(android.R.drawable.stat_notify_sdcard)
.setContentTitle(
context.getResources().getString(
R.string.app_name))
.setContentText("Recording Finished")
.setTicker("Recording Finished")
.setContentIntent(pendingIntent).setOngoing(false)
.setAutoCancel(true);
return mBuilder.build();
}
}
}
2) You can capture the screen shots and make the video from it and it will work for the 3.0+ devices And for converting the images to video you can use FFMPEG or JavaCV.
-For Rooted devices(in that you can capture the keyboard screen also)
if (Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState())) {
// we check if external storage is\ available, otherwise
// display an error message to the user using Toast Message
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File(sdCard.getAbsolutePath() + "/ScreenShots");
directory.mkdirs();
String filename = "screenshot_jpeg_" + i + ".png";
File yourFile = new File(directory, filename);
try {
Process sh = Runtime.getRuntime().exec("su", null, null);
OutputStream os = sh.getOutputStream();
os.write(("/system/bin/screencap -p " + "/sdcard/ScreenShots/" + filename).getBytes("ASCII"));
os.flush();
os.close();
sh.waitFor();
i++;
} catch (Exception e) {
e.printStackTrace();
}
}
-For without Rooted devices(in that you can not capture the keyboard screen)
if (Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState())) {
// we check if external storage is\ available, otherwise
// display an error message to the user using Toast Message
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File(sdCard.getAbsolutePath() + "/ScreenShots");
directory.mkdirs();
String filename = "screenshot_jpeg_" + i + ".png";
File yourFile = new File(directory, filename);
try {
Process sh = Runtime.getRuntime().exec("su", null, null);
OutputStream os = sh.getOutputStream();
os.write(("/system/bin/screencap -p " + "/sdcard/ScreenShots/" + filename).getBytes("ASCII"));
os.flush();
os.close();
sh.waitFor();
i++;
} catch (Exception e) {
e.printStackTrace();
}
}

Weird behaviour of activity lifecycle - after onResume() also onPause() called ...why?

I have a Form with edittexts and a button to call the camera with an intent (return a bitmap that is put into the imageview)...From the portrait mode i enter all edittext filed and then click the camera button which forwards me to the camera - in the camera i take a picture after what I get returned to Activity 1 (staying in portrait orientation - and all editext fields are restore in onRestoreInstanceState()) - and the last callback method of Activity 1 is onResume() (what is ok) - But the problem comes when I make an orientation change from this portrait to landscape mode - the callback methods are following
So the last callback orientation change is onPause(). I do not understand why? The problem is that onSaveInstanceState is called prior of onPause - so when I turn back to portrait mode everything will be empty (editexts, imageview..) - this strange behavior continues on every orientation change (the onPause() is called last).
I am sure this problem has to do something with the taking an image (startInentforResult....) because everything (editext fields) works fine on orientation change prior to taking an image...sometimes I can also take an image and it works fine, but in most cases not...
So my question is what is it that "drives" my Activity up to the onPause() method instead up to the onResume()?
Thanks, I would really appreciate if somebody knows the solution because I am struggling with this already a few days and could not find the solution.
The project has many classes but this is the activity code (Important to note is that the problem arises only when I take an image from camera app, after that the activity lifecycle goes crazy - also this activity is called from the main activity with 'startIntentforResult()'. I do not use 'android:configChanges="orientation|keyboardHidden"' to stop the recreatioin ):
public class NewCounterActivity extends Activity {
Button btnCreate;
Button btnCancel;
Button btnTakeImg;
ImageView counterImgView;
CheckBox existsDamage;
EditText inputNameFirst;
EditText inputNameLast;
EditText inputAdresse;
EditText inputCounterID;
EditText inputCounterValue;
EditText inputDescription;
TextView registerErrorMsg;
DatabaseHandler db;
//Data to be submitted
String nameFirst;
String nameLast;
String adresse;
String counterID;
String counterValue;
String countDescript;
String existsDmg;
Bitmap counterBitmap;
Bitmap recievedBitmap;
String longitude;
String latitude;
LocationTracker gps;
// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
//The dimensions of the ImageView
int targetW;
int targetH;
// Some lifecycle callbacks so that the image can survive orientation change
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.e("onSaveInstanceState", "fadsfass");
outState.putParcelable("bitmap", counterBitmap);
outState.putString("fname", inputNameFirst.getText().toString());
outState.putString("lname", inputNameLast.getText().toString());
outState.putString("adrese", inputAdresse.getText().toString());
outState.putString("cID", inputCounterID.getText().toString());
outState.putString("cValue", inputCounterValue.getText().toString());
outState.putString("Descript", inputDescription.getText().toString());
outState.putString("ErrorMsg", registerErrorMsg.getText().toString());
outState.putBoolean("damageCheck", existsDamage.isChecked());
((MyApplicationClass) getApplication()).detach(this);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
Log.e("onRestoreInstanceState", "fadsfass");
counterBitmap = savedInstanceState.getParcelable("bitmap");
counterImgView.setImageBitmap(counterBitmap);
inputNameFirst.setText(savedInstanceState.getString("fname"));
inputNameLast.setText(savedInstanceState.getString("lname"));
inputAdresse.setText(savedInstanceState.getString("adrese"));
inputCounterID.setText(savedInstanceState.getString("cID"));
inputCounterValue.setText(savedInstanceState.getString("cValue"));
inputDescription.setText(savedInstanceState.getString("Descript"));
registerErrorMsg.setText(savedInstanceState.getString("ErrorMsg"));
existsDamage.setChecked(savedInstanceState.getBoolean("damageCheck"));
((MyApplicationClass) getApplication()).attach(this);
}
#Override
public void onContentChanged() {
// TODO Auto-generated method stub
super.onContentChanged();
Log.e("onContetnChanged", "fadsfass");
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.e("onDestroy", "fadsfass");
}
#Override
public void onDetachedFromWindow() {
// TODO Auto-generated method stub
super.onDetachedFromWindow();
Log.e("onDetachedFromWindow", "fadsfass");
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Log.e("onPause", "fadsfass");
}
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
Log.e("onRestart", "fadsfass");
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.e("onResume", "fadsfass");
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
Log.e("onStart", "fadsfass");
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
Log.e("onStop", "fadsfass");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newcounteractivity_layout);
Log.e("onCreate", "mActivity equals NULL");
inputNameFirst = (EditText) findViewById(R.id.createFirstName);
inputNameLast = (EditText) findViewById(R.id.createLastName);
inputAdresse = (EditText) findViewById(R.id.createAdresse);
inputCounterID = (EditText) findViewById(R.id.createCounterID);
inputCounterValue = (EditText) findViewById(R.id.createCounterValue);
inputDescription = (EditText) findViewById(R.id.createDescription);
registerErrorMsg = (TextView) findViewById(R.id.create_error);
btnCreate = (Button) findViewById(R.id.btnCreate);
btnCancel = (Button) findViewById(R.id.btnCancel);
btnTakeImg = (Button) findViewById(R.id.btnImage);
counterImgView = (ImageView) findViewById(R.id.counterImgView);
existsDamage = (CheckBox) findViewById(R.id.createDamageExists);
//REGISTER BUTTON CLICK EVENTS
btnCreate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//new DoBackgroundTask(NewCounterActivity.this).execute();
//CounterUser data to submit
nameFirst = inputNameFirst.getText().toString().trim();
nameLast = inputNameLast.getText().toString().trim();
adresse = inputAdresse.getText().toString().trim();
counterID = inputCounterID.getText().toString().trim();
counterValue = inputCounterValue.getText().toString().trim();
countDescript = inputDescription.getText().toString().trim();
existsDmg = Integer.toString((existsDamage.isChecked()) ? 1 : 0);
// create LocationTracker class object
gps = new LocationTracker(NewCounterActivity.this);
if(!gps.canGetLocation()){
gps.stopUsingGPS();
gps.showSettingsAlert();
//Ovo se mozda treba i izbaciti
gps.getLocation();
}
else{
processInput();
}
}
});
btnCancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent returnIntent = new Intent();
setResult(RESULT_CANCELED, returnIntent);
finish();
}
});
btnTakeImg.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(isIntentAvailable(NewCounterActivity.this, MediaStore.ACTION_IMAGE_CAPTURE)){
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePictureIntent,2);
}
else {
Toast.makeText(NewCounterActivity.this, "No Camera Available", Toast.LENGTH_SHORT).show();
}
}
});
}
/************************************************************************************************
* Methods used in this class
* */
public void processInput(){
//Get current Longitude and Latitude
longitude = Double.toString(gps.getLongitude());
latitude = Double.toString(gps.getLatitude());
//Na kraju iskljuci location updatese - ne moze na emulatru jer ja emit coordinate preko DDMS... a kad emit on mora biti ukljucen da bi primio
//gps.stopUsingGPS();
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + longitude + "\nLong: " + latitude, Toast.LENGTH_LONG).show();
if (!nameFirst.equals("") && !nameLast.equals("") && !adresse.equals("") && !counterID.equals("") && !counterValue.equals("")
&& counterBitmap != null ){
new DoBackgroundTask(NewCounterActivity.this).execute();
}
else{
// Not all fields are filled
registerErrorMsg.setText("Not all fields are filled");
}
}
//Method to check whether an app can handle your intent
public boolean isIntentAvailable(Context context, String action) {
final PackageManager packageManager = context.getPackageManager();
final Intent intent = new Intent(action);
List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
/**************************************************************************************************
*
* When the calling activity, Activity #1, resumes after having called another activity, Activity #2, using startActivityForResult,
* the method onActivityResult in Activity #1 is called BEFORE onResume.
* This is important to know if you are instantiating your SQLite Database objects from within onResume in Activity #1. If so, you will also need to instantiate the object from within onActivityResult,
* when returning from Activity #2.
*
* startActivityForResult() is asynchronous. It can feel synchronous to the user since the UI will change and your calling activity will be paused
* (your onPause() method will be called).
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
Log.e("onActivityResult", "fadsfass");
if (requestCode == 2) {
if(resultCode == RESULT_OK){
Bundle extras = data.getExtras();
recievedBitmap = (Bitmap) extras.get("data");
}
if (resultCode == RESULT_CANCELED) {
Toast.makeText(NewCounterActivity.this, "No Image Taken", Toast.LENGTH_SHORT).show();
}
}
}
/**
* Koristim onWindowFocusChanged jer kad se vratim na Activity 1 onda dodje do potpunog recreate Activitija i getWidth()/height() ne mogu dobiti
* ni u jednom od lifecicle methoda - naime ide start onCreate,...onActivityResult(), onResume() - u onactivityResult izvadim bitmap i pohranim ga u receivedBitmap
* te kad getWidth() postane dostupan system invoke ovu dole methodu. :D
*/
#Override
public void onWindowFocusChanged(boolean hasFocus){
if(recievedBitmap != null){
targetW=counterImgView.getWidth();
targetH=counterImgView.getHeight();
Log.e("onWindowFocusChanged", "fadsfass" + " " + targetW + " " + targetH);
// http://stackoverflow.com/questions/4837715/how-to-resize-a-bitmap-in-android
// http://sunil-android.blogspot.com/2013/03/resize-bitmap-bitmapcreatescaledbitmap.html
// Scale or resize Bitmap to ImageView dimensions
counterBitmap = Bitmap.createScaledBitmap(recievedBitmap, targetW, targetH, false);
/**
* Canvas: trying to use a recycled bitmap android.graphics - This exception occurs when you try to recycle a bitmap which is already recycled.
* http://androdevvision.blogspot.com/2011/10/solution-for-out-of-memory-error-and.html
*/
if(recievedBitmap != null && !recievedBitmap.isRecycled()){
recievedBitmap.recycle();
recievedBitmap = null;
}
counterImgView.setImageBitmap(counterBitmap);
}
}
/************************************************************************************************
* Background AsyncTask to create new counterUser - https://github.com/callorico/CustomAsyncTask - najbolje radi
* new DoBackgroundTask(NewCounterActivity.this).execute();
* */
private static class DoBackgroundTask extends CustomAsyncTask<Void, Integer, JSONObject> {
private static final String TAG = "DoBackgroundTask";
private ProgressDialog mProgress;
private int mCurrProgress;
private NewCounterActivity myActivity = null;
public DoBackgroundTask(NewCounterActivity activity) {
super(activity);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
showProgressDialog();
}
#Override
protected void onActivityDetached() {
if (mProgress != null) {
mProgress.dismiss();
mProgress = null;
}
}
#Override
protected void onActivityAttached() {
showProgressDialog();
}
private void showProgressDialog() {
mProgress = new ProgressDialog(mActivity);
mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgress.setIndeterminate(true);
mProgress.setMessage(" Saljem na server... ");
mProgress.setCancelable(true);
mProgress.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
cancel(true);
}
});
mProgress.show();
mProgress.setProgress(mCurrProgress);
}
#Override
protected JSONObject doInBackground(Void... params) {
//so you need to either pass an instance of the outer class to the inner class method (or its constructor) as a parameter,
//or create it inside the method.
JSONObject json = null;
if(mActivity != null){
myActivity = (NewCounterActivity) mActivity;
//Prepare counterBitmap as String
ByteArrayOutputStream stream = new ByteArrayOutputStream();
//Write a compressed version of the bitmap to the specified output stream.
myActivity.counterBitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream);
byte [] b_array = stream.toByteArray();
String bitmapString = Base64.encodeBytes(b_array);
//Get workerId from logged worker
Functions workerFunction = new Functions();
DatabaseHandler db = new DatabaseHandler(mActivity);
String workerID = db.retrieveWorker().get("workerId");
if(myActivity != null){
//Get JsonObject from Functions.java
json = workerFunction.newCounterUser(myActivity.counterID, myActivity.counterValue, myActivity.adresse, myActivity.nameFirst, myActivity.nameLast, bitmapString, myActivity.existsDmg, myActivity.countDescript, workerID, myActivity.longitude, myActivity.latitude);
}
}
return json;
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
if (mActivity != null) {
mProgress.dismiss();
try {
if (jsonObject.getString(KEY_SUCCESS) != null) {
myActivity.registerErrorMsg.setText("");
String res = jsonObject.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// counterUser successfully registered
Toast.makeText(mActivity, "New counterUser is created", Toast.LENGTH_LONG).show();
// Return back to MainActivity
Intent returnIntent = new Intent();
returnIntent.putExtra("result",jsonObject.toString());
mActivity.setResult(RESULT_OK,returnIntent);
// Close all views before launching MainActivity
returnIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
mActivity.finish();
}else{
// Error in registration
myActivity.registerErrorMsg.setText("Error occured in registration");
}
}
} catch (JSONException e) {
Log.e("Error","NO Json at all");
e.printStackTrace();
}
} else {
Log.d(TAG, "AsyncTask finished while no Activity was attached.");
}
}
}
Same issues on call to recreate(), when activity has been updated it get onPause after onResume. Tested on emulator, bug exists on Marshallow and below.
This is my fix
private static boolean isRecreate = false;
private void reCreateActivity() {
isRecreate = true;
recreate();
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if(isRecreate) {
isRecreate = false;
runOnUiThread(new Runnable() {
#Override
public void run() {
onResume();
}
});
}
}
I don't know if that's correct, but it works.
EDIT
Best solution to avoid this issues, call recreate in postDelayed with 0 delayMillis
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
recreate();
}
}, 0);
It is only normal, that strange code produces strange behavior ...
replace this line:
((MyApplicationClass) getApplication()).detach(this);
with this line:
super.onSaveInstanceState(outState);

Return to download activity from Notificationbar

I know many questions been asked on this topic but none could answer my specific question or maybe I failed to recognize the right reply anyway!!
Just like Android Market during the download of a file with progressbar in the activity and progressbar in the notification bar, clicking the notification progressbar return back to the original activity with the progressbar updated with the download progress.
I am using AsyncTask for the download and creating & updating the notification bar all works fine, but when I click the notification it return me to same activity but without any data or progressbar (blank activity) in other word it start new activity and loose the extras and all fields data including the activity progressbar status.
I tried playing with flags and intent but failed to get my original activity loaded when clicking the notification bar specially when going back to another activity and then going to home screen then press the notification bar.
I run the download by:
df = new AsyncDownloadTask();
df.execute(m_item.getiid(),m_item.getipackage());
and the snippet (I changed the notification bar just to display progress text):
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView (R.layout.activity_app_display);
//get extras
Bundle extras = getIntent().getExtras();
if (extras == null) {
return;
}
itemId = extras.getString("id");
itemStatus = extras.getString("IorU");
ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressbar);
progressBar.setVisibility(0);
showUI();
}
private void showUI() {
if(m_item != null) {
TextView actvTitle = (TextView) findViewById(R.id.title_text);
actvTitle.setText(m_item.geticategory());
appinstall = (Button) findViewById(R.id.app_install_btn);
appudinstall = (Button) findViewById(R.id.app_udinstall_btn);
permlist = (LinearLayout) findViewById(R.id.app_perm); //
info = (LinearLayout) findViewById(R.id.info);
mList = (HeightListView) findViewById(R.id.app_perm_list);
mList.setTextFilterEnabled(true);
instTxt = (TextView) findViewById(R.id.app_install);
TextView titleTxt = (TextView) findViewById(R.id.app_titlebig);
TextView companyTxt = (TextView) findViewById(R.id.app_descbig);
TextView descTxt = (TextView) findViewById(R.id.long_desc);
TextView verTxt = (TextView) findViewById(R.id.version);
//fill info
titleTxt.setText(m_item.getititle());
companyTxt.setText(m_item.geticompany());
descTxt.setText(m_item.getidescription());
verTxt.setText(" Version:" + m_item.getiversion());
}
}
#Override
protected void onResume(){
super.onResume();
}
#Override
public Object onRetainNonConfigurationInstance() {
Toast.makeText (getApplicationContext(), "onRetainNonConfigurationInstance", Toast.LENGTH_SHORT).show();
return null;
}
#Override
protected void onDestroy() {
super.onDestroy();
/*
if(df != null)
{
if(!df.isCancelled())
df.cancel(true);
}
CN=true;
*/
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onStart() {
super.onStart();
}
private class AsyncDownloadTask extends AsyncTask<String, Integer, Void>
{
private int successCount;
private int numTotalFiles;
private File outputFile;
private String pack;
private int downloadErr = 0;
#Override
protected void onPreExecute()
{
super.onPreExecute();
successCount = 0;
notificationManager = (NotificationManager) getApplicationContext().getSystemService(getApplicationContext().NOTIFICATION_SERVICE);
CN=false;
}
#Override
protected Void doInBackground(String... params)
{
String remoteFilepath;
String id = params[0];
pack = params[1];
remoteFilepath = "http://www.myserver/download/1.zip";
String PATH = Environment.getExternalStorageDirectory()+ "/download/";
File file = new File(PATH);
file.mkdirs();
try
{
if(isCancelled())
return null;
URL url = new URL(remoteFilepath);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setConnectTimeout(getConnectTimeout());
c.setReadTimeout(getReadTimeout());
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
int filesize = c.getContentLength();
if(filesize > 0)
{
outputFile = new File(file, "1.zip");
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
int bytesRead, totalBytesRead = 0;
byte[] bytes = new byte[BYTES_BUFFER_SIZE];
String progress, kbytes;
while(!isCancelled() && (bytesRead = is.read(bytes)) != -1)
{
totalBytesRead += bytesRead;
fos.write(bytes, 0, bytesRead);
if(!isCancelled() ) //&& loopCount++ % 20 == 0)
{
RemoteViews progressView = getProgressView(successCount + 1, numTotalFiles, totalBytesRead, filesize);
if(progressView == null)
{
progress = "Download "+pack;
kbytes = String.format("%s / %s", getStringByteSize(totalBytesRead), getStringByteSize(filesize));
if(!isCancelled() && !CN){
showNotification("Downloading File(s)", progress , kbytes);
publishProgress(totalBytesRead,filesize);
} else { return null; }
}
else
{
if(!isCancelled() && !CN){
showNotification(progressView, "Downloading File(s)");
} else { return null; }
}
}
}
fos.close();
is.close();
if(isCancelled())
return null;
successCount ++;
}
else
{
}
}
catch(Exception e)
{
e.printStackTrace();
showNotification("Download Failed", "Download Progress", "Failed: " + (new File(remoteFilepath)).getName());
//updateCancelInstall();
publishProgress(100,100);
notificationManager.cancel(42);
downloadErr = 1;
CN = true;
}
return null;
}
#Override
protected void onCancelled()
{
super.onCancelled();
showNotification("Download Cancelled", "Download Progress", "Cancelled");
CN = true;
publishProgress(100,100);
notificationManager.cancel(42);
}
protected void onProgressUpdate(Integer... prog) {
if(prog[0]<prog[1]){
updateProgress(prog[0],prog[1],false);
} else {
updateProgress(100,100,true);
notificationManager.cancel(42);
}
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
if(!CN){
if(downloadErr==0) {
showNotification("Installing", "Installing "+pack, "Completed");
updateDLcount udl = new updateDLcount();
udl.execute("hello");
//updateCancelInstall();
notificationManager.cancel(42);
} else {
showNotification("Download Error", "Failed to download "+pack, "Error");
//updateCancelInstall();
notificationManager.cancel(42);
}
}
}
}
protected RemoteViews getProgressView(int currentNumFile, int totalNumFiles, int currentReceivedBytes, int totalNumBytes)
{
return null;
}
protected Class<?> getIntentForLatestInfo()
{
return DisplayApp.class;
}
protected void showNotification(String ticker, String title, String content)
{
Notification notification = new Notification(R.drawable.download_icon, ticker, System.currentTimeMillis());
Intent i=new Intent(this, DisplayApp.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
i.putExtra("id", itemId);
i.putExtra("IorU", "itemStatus");
i.putExtra("progrss", content);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, i, 0);
notification.setLatestEventInfo(getApplicationContext(), title, content, contentIntent);
notification.flags = notification.flags | Notification.FLAG_ONGOING_EVENT;
notificationManager.notify(42, notification);
if(content.equalsIgnoreCase("Cancelled")||content.equalsIgnoreCase("Completed")||CN)notificationManager.cancel(42);
}
protected void updateProgress(int downsize, int totalsize, boolean cancel){
//Log.i("YYYY","cancel="+cancel);
if(!cancel || (downsize<totalsize)){
ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressbar);
TextView pb_t = (TextView) findViewById(R.id.progressbar_text);
progressBar.setVisibility(0);
pb_t.setVisibility(0);
progressBar.setProgress((int)downsize*100/totalsize);
pb_t.setText(String.format("%s / %s", getStringByteSize(downsize), getStringByteSize(totalsize)));
} else {
ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressbar);
TextView pb_t = (TextView) findViewById(R.id.progressbar_text);
progressBar.setProgress(100);
progressBar.setVisibility(4);
pb_t.setVisibility(4);
updateCancelInstall();
}
}
protected void showNotification(RemoteViews remoteView, String ticker)
{
Notification notification = new Notification(R.drawable.download_icon, ticker, System.currentTimeMillis());
notification.contentView = remoteView;
Intent i=new Intent(this, DisplayApp.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
notification.contentIntent = PendingIntent.getActivity(this, 0, i, 0);
//Log.d("YYYY","2:"+notification.contentIntent.toString());
notification.flags = notification.flags | Notification.FLAG_ONGOING_EVENT;
notificationManager.notify(42, notification);
}
Appreciate if you can help me by code, url or any documentations that mimics the market way of doing this.
Thanks
I have used singleInstance in the launchMode of my activity, the activity comes to front with the progress bar progressing along with the download.
I figured out that it get confused only if I moved back and then home then click notification bar, this obvious since clicking back will destroy my activity and I loose history so my work around was to disable the back key in my activity and let the application user navigate through my UI menu and button.
I know there should be away to store my activity instance and retrieve it later no matter what happened to the history/stack but so far the above is enough for me!!
Thanks,
In your AndroidManifest.xml file try adding under the activity you wish to return to the line android:launchMode="singleTop". For example:
<activity android:name=".MainLayout"
android:label="#string/app_name"
android:launchMode="singleTop">
This will prevent a new instance of your activity being created and will route the intent to any current instances of your activity. For more info see here.

IntentService runs through a list, which can be reordered concurrently via onHandleIntent

I am using IntentService to download 200 large JPGs from a list. While this is loading, the user can skip through the not-loaded JPGs and load JPG #156 for example, but after it is loaded, it should continue loading the rest. So it's like a Lazy Loader... but it continues when it's idle.
I previously used onHandleIntent and put a loop from #1 to #200... which obviously doesn't work when I try to send another IntentService call for JPG #156. So the call to #156 only happens after onHandleIntent is done with #200.
I then changed it so onHandleIntent reorders request #156 to be at the top of the list, then requests the top of the list (and downloads the JPG), then removes it from the list. It then calls the IntentService again, which sounds rather risky from a recursive/stack overflow kinda way. It works sometimes and I can see file #156 being put first... sometimes.
Is there a better way to do this? A way I could think of would be to run it all through a database.
EDIT: This is what I have come up with:
code
public class PBQDownloader extends IntentService {
int currentWeight = 0;
PriorityBlockingQueue<WeightedAsset> pbQueue = new PriorityBlockingQueue<WeightedAsset>(100, new CompareWeightedAsset());
public PBQDownloader() {
super("PBQDownloader");
}
public PBQDownloader(String name) {
super(name);
}
#Override
protected void onHandleIntent(Intent intent) {
String downloadUrl = "-NULL-";
Bundle extras = intent.getExtras();
if (extras!=null) {
downloadUrl = extras.getString("url");
Log.d("onHandleIntent 1.1", "asked to download: " + downloadUrl);
} else {
Log.d("onHandleIntent 1.2", "no URL sent so let's start queueing everything");
int MAX = 10;
for (int i = 1; i <= MAX; i++) {
// should read URLs from list
WeightedAsset waToAdd = new WeightedAsset("url: " + i, MAX - i);
if (pbQueue.contains(waToAdd)) {
Log.d("onStartCommand 1", downloadUrl + " already exists, so we are removing it and adding it back with a new priority");
pbQueue.remove(waToAdd);
}
pbQueue.put(waToAdd);
}
currentWeight = MAX + 1;
}
while (!pbQueue.isEmpty()) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
WeightedAsset waToProcess = pbQueue.poll();
Log.d("onHandleIntent 2 DOWNLOADED", waToProcess.url);
}
Log.d("onHandleIntent 99", "finished all IntentService calls");
}
#Override
public int onStartCommand(Intent intent, int a, int b) {
super.onStartCommand(intent, a, b);
currentWeight++;
String downloadUrl = "-NULL-";
Bundle extras = intent.getExtras();
if (extras!=null) downloadUrl = extras.getString("url");
Log.d("onStartCommand 0", "download: " + downloadUrl + " with current weight: " + currentWeight);
WeightedAsset waToAdd = new WeightedAsset(downloadUrl, currentWeight);
if (pbQueue.contains(waToAdd)) {
Log.d("onStartCommand 1", downloadUrl + " already exists, so we are removing it and adding it back with a new priority");
pbQueue.remove(waToAdd);
}
pbQueue.put(waToAdd);
return 0;
}
private class CompareWeightedAsset implements Comparator<WeightedAsset> {
#Override
public int compare(WeightedAsset a, WeightedAsset b) {
if (a.weight < b.weight) return 1;
if (a.weight > b.weight) return -1;
return 0;
}
}
private class WeightedAsset {
String url;
int weight;
public WeightedAsset(String u, int w) {
url = u;
weight = w;
}
}
}
code
Then I have this Activity:
code
public class HelloPBQ extends Activity {
int sCount = 10;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button tv01 = (Button) findViewById(R.id.tv01);
Button tv02 = (Button) findViewById(R.id.tv02);
Button tv03 = (Button) findViewById(R.id.tv03);
tv01.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
doPBQ();
}
});
tv02.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
doInitPBQ();
}
});
tv03.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
sCount = 0;
}
});
}
private void doInitPBQ() {
Intent intent = new Intent(getApplicationContext(), PBQDownloader.class);
//intent.putExtra("url", "url: " + sCount);
startService(intent);
}
private void doPBQ() {
sCount++;
Intent intent = new Intent(getApplicationContext(), PBQDownloader.class);
intent.putExtra("url", "url: " + sCount);
startService(intent);
}
}
code
Now the messy bit is that I have to keep an ever-increasing counter that runs the risk of going out of int bounds (WeightedAsset.weight) - is there a way to programmatically add to the queue and have it automatically be the head of the queue? I tried to replace WeightedAsset with a String, but it didn't poll() as I wanted, as a FIFO instead of a LIFO stack.
Here's how I'd try it first:
Step #1: Have the IntentService hold onto a PriorityBlockingQueue.
Step #2: Have onHandleIntent() iterate over the PriorityBlockingQueue, downloading each file in turn as it gets popped off the queue.
Step #3: Have onStartCommand() see if the command is the "kick off all downloads" command (in which case, chain to the superclass). If, instead, it's the "prioritize this download" command, re-prioritize that entry in the PriorityBlockingQueue, so it'll be picked up next by onHandleIntent() when the current download is finishing.

Categories

Resources