android progressbar in notification open activity when click - android

I just wonder that is it possible to make progressbar in notification and open an activity when click it.
Let's make a sample:
I have Activity A, B and C which C is file upload Activity with progressbar and notification.
So, when i click HOME button and then click notification icon i want to back to Activity C, Clicking back button go to Activity B and clicking again go to Activity A.
Here is my Fileupload and notification class
Activity C
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_c);
WindowManager.LayoutParams params = getWindow().getAttributes();
params.x = -20;
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
{
params.height = 750;
params.width = 550;
}
else
{
params.height = 550;
params.width = 750;
}
params.y = -10;
this.getWindow().setAttributes(params);
pg = (ProgressBar) findViewById(R.id.progressBar1);
pg.setProgress(0);
new RunProgress().execute();
}
public class RunProgress extends AsyncTask<String, String, String>
{
#Override
protected void onPreExecute()
{
if(extraFlag == 0)
{
// Call Notification method
// backup is executed
displayNotification();
}
super.onPreExecute();
}
#Override
protected String doInBackground(String... params)
{
for (int i = 0; i < fileName.size(); i++)
{
name = fileName.get(i);
WebDav writer = new WebDav(getApplicationContext(),
name);
try
{
x += percentage;
publishProgress("" + x);
writer.uploadFile(name);
if (isCancel)
break;
File file = new File(new FilePathClass().returnSimple()
+ name);
file.delete();
}
catch (Exception e)
{
system.out.println(e.toString());
}
}
return null;
}
#Override
protected void onProgressUpdate(String... progress)
{
pg.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String result)
{
// This makes Notification icon CLEAR
myNotificationManager.cancelAll();
}
}
and notification method
private void displayNotification()
{
n = new Notification.Builder(getApplicationContext());
n.setContentTitle(getResources().getString(R.string.msg_action_bar_title));
n.setTicker("Uploading...");
n.setContentText("Upload progress started");
n.setSmallIcon(R.drawable.ic_launcher);
// This makes return to Same Activity
// when clicking notification icon
Intent i = new Intent(getApplicationContext(), ActivityC.class);
// i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.putExtra("extraFlag", 1);
i.putStringArrayListExtra("fileName", fileName);
i.putExtra("numberOfContacts", fileName.size());
TaskStackBuilder stackBuilder = TaskStackBuilder.create(ActivityC.this);
stackBuilder.addParentStack(ActivityC.class);
stackBuilder.addNextIntent(i);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_ONE_SHOT);
n.setContentIntent(pendingIntent);
myNotificationManager = (NotificationManager) getSystemService(ActivityC.NOTIFICATION_SERVICE);
if (currentApiVersion < 16)
myNotificationManager.notify(0, n.getNotification());
else
myNotificationManager.notify(0, n.build());
}

Call setLatestEventInfo() on the Notification object, supplying a PendingIntent that will start your activity when they tap on your entry in the notification drawer.
Check out this sample.

Related

Android UI omits some updates

I am dealing with the android UI and I am facing what looks a very common problem here. By using an AsyncTask, I want to:
1- Show a ProgressDialog meanwhile some stuff gets ready
2- Show a countdown to let the user get ready for the real action
3- Play a sound afterwards the countdown to notify the sample will be taken
4- Show another ProgressDialog representing the 10s sample taking
5- Play a sound afterwards the sample is taken
Well, this is my outcome:
1- Works fine
2- MISSING, THE UI IS NOT UPDATED BUT THE BACKGROUND PROCESS IS RUNNING
3- Works fine
4- Works fine
5- Works fine
The funniest is, when I remove the code to handle the first part that handles the first progress dialog, the other parts are executed/displayed as expected. I understand there is something blocking the UI at some point but I am quite newbie with android to realize what's blocking it.
Thanks in advance for your help.
public class SnapshotActivity extends AppCompatActivity {
private int COUNTDOWN_TIME = 5;
private Button startStop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_snapshot);
startStop = (Button) findViewById(R.id.btnStartStop);
startStop.setText("START");
}
public void startSnapshot(View view) {
startStop.setClickable(false);
new Async(SnapshotActivity.this).execute();
}
class Async extends AsyncTask<Void, Void, Void>{
TextView tv = (TextView) findViewById(R.id.tvCountDown);
ProgressDialog progressDialog ;
ProgressDialog preparing;
Context context;
int flag = 0;
int counter = COUNTDOWN_TIME;
public Async(Context context) {
this.context = context;
progressDialog = new ProgressDialog(context);
preparing = new ProgressDialog(context);
}
#Override
protected void onPreExecute(){
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
//PROGRESS DIALOG
flag = 4;
publishProgress();
try {
//SIMULATE SOME WORKLOAD
Thread.sleep(2000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
flag = 5;
publishProgress();
//HANDLE THE COUNTDOWN
for(counter = COUNTDOWN_TIME; counter>=1; counter--){
publishProgress();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
//PLAY THE SOUND
new Thread(new Runnable() {
#Override
public void run() {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
}
}).start();
//PROGRESS DIALOG
flag = 1;
publishProgress();
//10s SAMPLE
flag = 2;
for(int j = 0; j <= 10; j++ ){
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
publishProgress();
}
//PLAY THE SOUND
new Thread(new Runnable() {
#Override
public void run() {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
}
}).start();
flag = 3;
publishProgress();
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
switch (flag) {
case 0:
tv.setText(String.valueOf(counter));
break;
case 1:
tv.setText("");
progressDialog.setTitle("TAIKING SAMPLE");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMax(10);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
break;
case 2:
progressDialog.incrementProgressBy(1);
break;
case 3:
progressDialog.dismiss();
break;
case 4:
preparing.setMessage("Starting the device...");
preparing.setCanceledOnTouchOutside(false);
preparing.show();
break;
case 5:
preparing.dismiss();
break;
default:
break;
}
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
startStop.setClickable(true);
}
}
}
There are two issues:
You are not informing onProgressUpdate() of the countdown value
There is a race condition
doInBackground() and onProgressUpdate() methods are executed in two different threads and both methods/threads are accessing the flag field in a unsafe way. Instead of setting a value in flag in doInBackground() to be read in onProgressUpdate(), you can inform this value directly in the publishProgress() call. So I advise you to do the following:
public class SnapshotActivity extends AppCompatActivity {
// ...
// Change the Progress generic type to Integer.
class Async extends AsyncTask<Void, Integer, Void> {
// Remove the flag field.
// int flag = 0;
#Override
protected Void doInBackground(Void... params) {
//PROGRESS DIALOG
// Pass the flag argument in publishProgress() instead.
// flag = 4;
publishProgress(4);
// ...
// flag = 5;
publishProgress(5);
//HANDLE THE COUNTDOWN
for (counter = COUNTDOWN_TIME; counter>=1; counter--){
// The countdown progress has two parameters:
// a flag indicating countdown and
// the countdown value.
publishProgress(6, counter);
// ...
}
//PLAY THE SOUND
// ...
//PROGRESS DIALOG
// flag = 1;
publishProgress(1);
//10s SAMPLE
// flag = 2;
for(int j = 0; j <= 10; j++ ){
// ...
publishProgress(2);
}
//PLAY THE SOUND
// ...
// flag = 3;
publishProgress(3);
return null;
}
// This signature changes.
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
// Redeclare flag here.
int flag = values[0];
switch (flag) {
// ...
case 6:
tv.setText(Integer.toString(values[1]));
break;
// ...
}
}
}
}

Android Expansion file won't trigger onDownloadStateChanged?

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

progress bar in Notification area is not closing and not starting the second progress bar

in my app i have 4 buttons and when the user clicks any of the button it starts downloading a file and the progress bar gets shown in the notification area. The downloading and progress bar is working fine, but i have the following two problems
When the download completes the progress bar is not getting closed, it remains in the notification area
As i said above i have 4 buttons and when the first button is clicked download gets started and when the other three buttons are clicked immediately download is not taking place. I thought it may start after first download completes. But nothing happens. How to show all the progress bar when all buttons clicked
Following is my code(here i have added only 2 buttons) pls help me
b1 = (Button)findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
i =1;
Intent intent = new Intent(NotificationProgressTestActivity.this, UploadService.class);
startService(intent);
}
});
b2 = (Button)findViewById(R.id.button2);
b2.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
i = 2;
Intent intent = new Intent(NotificationProgressTestActivity.this, UploadService.class);
startService(intent);
}
});
Next following is my Uplaod Service.class
public class UploadService extends IntentService
{
private NotificationManager notificationManager;
private Notification notification;
private int progress = 10;
private static String fileName = "folder/";
private static URL url;
public UploadService(String name)
{
super(name);
}
public UploadService()
{
super("UploadService");
}
#Override
protected void onHandleIntent(Intent intent)
{
notificationManager = (NotificationManager) getApplicationContext().getSystemService(getApplicationContext().NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
notification = new Notification(R.drawable.icon,"Uploading file", System.currentTimeMillis());
notification.flags = notification.flags | Notification.FLAG_ONGOING_EVENT;
notification.contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.upload_progress_bar);
notification.contentIntent = contentIntent;
notification.contentView.setProgressBar(R.id.progressBar1, 100, progress, false);
notificationManager.notify(42, notification);
notificationManager.notify(42, notification);
Thread download = new Thread()
{
#Override
public void run()
{
Log.e("download", "start");
try
{
for (int i = 1; i < 100; i++)
{
progress++;
notification.contentView.setProgressBar(R.id.progressBar1, 100, progress, false);
if(i==1)
{
if(NotificationProgressTestActivity.i ==1 )
{
url = new URL("http://xxxxxxxxxxxxxxxx.mp4");
}
else if(NotificationProgressTestActivity.i == 2)
{
url = new URL("http://xxxxxxxxxxxxxxxx.mp4");
}
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH = Environment.getExternalStorageDirectory()+ "/";
Log.e("PATH:", PATH);
File file = new File(PATH);
if (!file.exists())
{
file.mkdir();
Log.e("destination", "created");
}
else
{
Log.e("destination", "exist");
}
File outputFile = new File(file, fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[10171188];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1)
{
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
// -----------------------
if (!outputFile.exists())
{
Log.e(outputFile.toString(), "not created");
}
else
{
Log.e(outputFile.toString(), "created");
Log.e(outputFile.toString(), "" + outputFile.length());
}
Log.e("download", "end");
}
notificationManager.notify(42, notification);
try
{
Thread.sleep(1017);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
catch (IOException e)
{
Log.e("log_tag", "Error: " + e);
}
Log.e("log_tag", "Check: ");
// remove the notification (we're done)
notificationManager.cancel(42);
}
};
download.run();
}
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
1- in this above line, the 2nd parameter in getActivity() is requestCode, it should be a unique number for each button. currently it is 0 for both buttons.
notificationManager.notify(42, notification);
2- in the above line, the notification index you are passing as 42, it should be unique for both buttons. currently no matter how many buttons you create it will never show you a new notification because you are passing 42 for each. it will keep updating the current one.
also you might need to look again the code you are doing in onHandleIntent(). there are better ways to do this.
What you need is an AsyncTask and a ListView.
Your downloadmagic happens in AsyncTask.
Make for example an Array that indicates which download is running and the progress of each running download.
Now in your AsyncTask there is a publishProgress-Method which calls onProgressUpdate.
In onProgressUpdate you have to update the respective progress-variable and call notifyDataSetChanged on your ListView Adapter.
This will cause the ListView to reload all Data.
Finally in your ListView-Adapter you got a Method getView, where you have to create the View for each row of your ListView.
There you can decide to show the ProgressBar (download running) or not.
More Information about AsyncTask can be found here: http://labs.makemachine.net/2010/05/android-asynctask-example/
And more about the ListView here: Android : BaseAdapter how to?

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.

Using Android AsyncTask and Notification which freezes my System

I just wanted to learn how to do some Android App development, so I started with some simple demos and now doing something harder (I guess ;-)).
Using: Eclipse + min SDK 8 + Android 2.2. Debugging and testing on emulator and my SGS I9000:
I managed to use AsyncTask to send some Data (Picture which I get from Camera or over the Gallery) to a server which works great. So, now that things works great, I decided to add a Custom Notification to the Status bar with a progress bar and text. Well, that worked too, but then I noticed:
1) as soon ad I call the publishProgress() from doInBackground() which will call the onProgressUpdate() where I update my notification. I noticed by "opening" and "closing" the Notification bar during the update, that it is not smooth. It freezes or sometime you'll see that the notification bar is not responding anymore (If opened it won't close anymore or if it was closed and try to open it won't).
2) I also noticed when I start x Notifications, then my System crashes and it looks as my system did a new start which it didn't!
well, I thought I did everything as it stands in the documentations, but I am sure I did something wrong, cause I am sure it's possible what I am looking for since Facebook for Android does the same as I soon as I choose a picture to share.
I create the notification in my onPreExecute() call (so that means on the UI thread).
here my code if anybody can tell me where my problem is: (I hope that's Okay to post the code here)
NotificationHelper manges the Notification by generating and updating the progressbar/text
public class NotificationHelper {
private Context mContext;
private Notification mNotification;
private NotificationManager mNotificationManager;
private PendingIntent mContentIntent;
private RemoteViews contentView;
private static Random randomGenerator = new Random();
private int Id = -1;
public NotificationHelper(Context context)
{
mContext = context;
Id = randomGenerator.nextInt(1000);
}
public void CreateNotification(String text)
{
mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
mNotification = new Notification(R.drawable.icon, "MyTestApp", System.currentTimeMillis());
contentView = new RemoteViews(mContext.getPackageName(), R.layout.notification);
contentView.setProgressBar(R.id.progressBar, 100, 0, false);
contentView.setTextViewText(R.id.text, Html.fromHtml("<b>TEST </b>" + text));
contentView.setTextViewText(R.id.textStatus, String.format(mContext.getString(R.string.uploading), ""));
mNotification.contentView = contentView;
Intent notificationIntent = new Intent(mContext, main.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContentIntent = PendingIntent.getActivity(mContext, 0, notificationIntent, 0);
mNotification.contentIntent = mContentIntent;
mNotificationManager.notify(Id, mNotification);
}
public void UpdateProgress(int Percent)
{
if (mNotification == null) return;
mNotification.contentView.setProgressBar(R.id.progressBar, 100, Percent, false);
contentView.setTextViewText(R.id.textStatus, String.format(mContext.getString(R.string.uploading), Integer.toString(Percent) + "%"));
mNotificationManager.notify(Id, mNotification);
}
public void Completed(boolean Status)
{
if (contentView != null) {
//mNotificationManager.cancel(Id);
contentView.setViewVisibility(R.id.progressbarContainer, View.INVISIBLE);
if (Status)
{
contentView.setTextViewText(R.id.textStatus, mContext.getString(R.string.upload_done));
}else
{
contentView.setTextViewText(R.id.textStatus, mContext.getString(R.string.upload_failed));
}
mNotificationManager.notify(Id, mNotification);
}
}
}
here is my Task:
public class MyTask extends AsyncTask<Void, Integer, Integer> {
private Context context;
private NotificationHelper pbNotificationHelper;
public String TextToShow;
public MyTask(Context context, String text) {
this.context = context;
TextToShow = text;
}
#Override
protected Integer doInBackground(Void... params) {
int xfileSize = 1048576 * 4;
if (true){
int i = 0;
while (true)
{
if (i > xfileSize) break;
i += 32 * 1024;
publishProgress( (i * 100) / xfileSize);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return 0;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pbNotificationHelper = new NotificationHelper(context);
pbNotificationHelper.CreateNotification(TextToShow);
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
pbNotificationHelper.UpdateProgress(values[0]);
}
#Override
protected void onPostExecute(Integer result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pbNotificationHelper.Completed(true);
}
}
and here is my test activity:
public class main extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void Test1Click(View view) {
new MyTask(getApplicationContext(), "This is a test message").execute();
}
}
I am sorry if that is too much code, but I am really at end of my understandings!
Interesting is that, when I don't call the publishProgress() nothings freezes and looks everything smooth! Any help? any Idea what I do wrong?
Many thanks in advance,
Cheers Gohlool
I think where ever you calling your async task code it should be in separate thread.

Categories

Resources