Continue uploading in background - android

When closing an application with back or homescreen button, app showing a webview closes.
On returning back to the app, it load the page all over again.
More specifically, the page this app loads contains an upload button. File upload takes some time depending on the internet speed. If the used starts uploading and goes to other app, the upload progress will be lost and on revisiting the app, the page will load all over again.
What to do to make upload in VebView work in background. Giving a notification of "upload in progress..." in notification area will be an added benefit. Suggest what to do and how?

You should do the upload in a Service, instead of in a Activity. (Lookup IntentService for example, which will shut itself down after upload)

here is sample code of service just edit is as per your need:
i have create one service and call it from my activity using:
startService(new Intent(MainActivity.this, TempServices.class));
here is my service class
package com.example.uploadfile;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.Builder;
import android.util.Log;
public class TempServices extends Service {
protected static final int ID = 100;
private NotificationManager mNotifyManager;
private Builder mBuilder;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
mNotifyManager = (NotificationManager) getApplicationContext()
.getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(this);
mBuilder.setContentTitle("Picture Download")
.setContentText("Download in progress")
.setSmallIcon(R.drawable.ic_launcher);
// Start a lengthy operation in a background thread
new Thread(new Runnable() {
#Override
public void run() {
int incr;
// Do the "lengthy" operation 20 times
for (incr = 0; incr <= 100; incr += 5) {
// Sets the progress indicator to a max value, the
// current completion percentage, and "determinate"
// state
mBuilder.setProgress(100, incr, false);
// Displays the progress bar for the first time.
mNotifyManager.notify(0, mBuilder.build());
// Sleeps the thread, simulating an operation
// that takes time
try {
// Sleep for 5 seconds
Thread.sleep(5 * 1000);
} catch (InterruptedException e) {
Log.e("error-->", "sleep failure");
}
}
// When the loop is finished, updates the notification
mBuilder.setContentText("Download complete")
// Removes the progress bar
.setProgress(0, 0, false);
mNotifyManager.notify(ID, mBuilder.build());
}
}
// Starts the thread by calling the run() method in its Runnable
).start();
return super.onStartCommand(intent, flags, startId);
}
}
for counting progress check this link
do not forgate to add this service in android manifes:
<service android:name="TempServices" >

Related

i want show notification on stock value change in android

I developed stock market app.now I want to develop app that have features like notification when stock value has been change to 1 % of current ...help me ...thanks in advance..i want show notification on stock value change in android
Try the following it may helps you
1) First take one service in your application
2) In the service check the stock market updates frequently
EDIT
public class StockService extends Service{
Thread t=new Thread(){
public void run(){
while(true){
checkStockUpdates();
Thread.sleep(give how much time you want);
}
}
};
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
t.start();
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public void checkStockUpdates(){
//write code here for checking stock market updates
//if any updates found send notification here itself
}
}
3) If you observe any change then you can send notification to user
Following is the code for send notification
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
/* Invoking the default notification service */
mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.icon)
.setContentTitle("My notification")
.setContentText("Hello World!");
manager.notify(1234, mBuilder.build());
Note : Thread is lightweight so if you write while loop also it doesn't effect on Application performance.
hope it will helps you.

Getting data to a service without restarting it

I have a service that sends a notification at a random time, telling me to press a button. This button needs to be pressed quickly because after 2 minutes it will disappear again. But after those 2 minutes I don't know how I can see if the button has or hasn't been pressed.
Somehow I need to get something like a boolean from my MainActivity to my service, but I don't believe I can do that with an intent because then I would restart my service.
I have looked for an answer but wasn't able to find a solution, any help will be much appreciated!
My service:
`package com.example.pressme_alpha;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
public class ButtonAlarmService extends IntentService{
private static final String INTENT_NAME = "notification";
private NotificationManager nm;
private Notification notification;
public ButtonAlarmService() {
super("Imma button!");
}
#SuppressWarnings("static-access")
#Override
protected void onHandleIntent(Intent intent) {
nm = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
Intent newIntent = new Intent(this.getApplicationContext(), MainActivity.class);
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
newIntent.putExtra(INTENT_NAME, true);
PendingIntent pendingIntent = PendingIntent.getActivity(this.getApplicationContext(), 0, newIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(this);
notification = notifBuilder.setContentIntent(pendingIntent).setSmallIcon(R.drawable.ic_launcher).setContentTitle("Press me - alpha").setContentText("You need to press the button!").build();
notifBuilder.setAutoCancel(true);
nm.notify(0, notification);
startActivity(newIntent);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//Check if the button is pressed here
ButtonAlarmReceiver.completeWakefulIntent(intent);
}
}
`
Extending Service (not IntentService) is what you want to do as it will keep runing untill you explicitly tell it to stop via stopService(Intent) method or if the service calls stopSelf() on its self.
You can send signals to the service via startService(Intent) method. This will start the service the first time its called (when the service is not running) and just send data to it if called subsequent times.
Make sure to spawn a new thread if you are doing heavy proccessing in the service as this will run on the Main thread (or UI thread depending on what you want to call it). You do not want to block the main thread.

on button click notification

I am making an application in android using eclipse IDE and i want to implement a notification in my android i want to make the notification on button click example i want to notify saved data..i found this tutorial here i copied the code and paste it in my setOnClickListener code..but im getting error..i dont know how to start doing this because in the tutorial they just give you the code snippet..this is my code
UPDATE QUESTION
what is the difference between notification and push notification and which is better to use..
submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mNotifyManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(this);
mBuilder.setContentTitle("Picture Download")
.setContentText("Download in progress")
.setSmallIcon(R.drawable.ic_notification);
// Start a lengthy operation in a background thread
new Thread(
new Runnable() {
#Override
public void run() {
int incr;
// Do the "lengthy" operation 20 times
for (incr = 0; incr <= 100; incr+=5) {
// Sets the progress indicator to a max value, the
// current completion percentage, and "determinate"
// state
mBuilder.setProgress(100, incr, false);
// Displays the progress bar for the first time.
mNotifyManager.notify(0, mBuilder.build());
// Sleeps the thread, simulating an operation
// that takes time
try {
// Sleep for 5 seconds
Thread.sleep(5*1000);
} catch (InterruptedException e) {
Log.d(TAG, "sleep failure");
}
}
// When the loop is finished, updates the notification
mBuilder.setContentText("Download complete")
// Removes the progress bar
.setProgress(0,0,false);
mNotifyManager.notify(ID, mBuilder.build());
}
}
// Starts the thread by calling the run() method in its Runnable
).start();
}
});
You should change this
mBuilder = new NotificationCompat.Builder(this);
to
mBuilder = new NotificationCompat.Builder(youractivity.this);
You need to pass current Context for creating mBuilder object.

How to update my notification to show my time counter changing?

I am almost finished with this toy app game I am making.
Problem:
My notification is always showing my counter to be 30000. Why isn't it timing down?
What I have done:
I have implemented a simple Service class and a custom timer to tick down. Eventually once I am sure the timer is working I will exit the entire game.
Here is my code:
package com.example.redshirtmarblez;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.widget.Toast;
public class TimingService extends Service{
public long counter = 30000;
private Context ctx;
private Activity localActivity;
private NotificationManager nm;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate()
{
super.onCreate();
nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
declareNotification();
timer.start();
//Toast.makeText(this, "Timer is :" + counter, Toast.LENGTH_LONG).show();
//showNotification();
}
public void getActivity(Activity activity)
{
localActivity = activity;
}
//count to end the game
public CountDownTimer timer = new CountDownTimer(30000, 1000){
public void onTick(long millisUntilFinished){
counter = millisUntilFinished / 1000;
}
public void onFinish(){
counter = 0;
//Kill the game
int i = android.os.Process.myPid();
android.os.Process.killProcess(i);
}
};
/*
* Show a notification while this service is running
*/
public void declareNotification()
{
//Declare a new notification
Notification notification = new Notification(R.drawable.ic_launcher, "A New Notification", System.currentTimeMillis());
notification.flags |= Notification.FLAG_ONGOING_EVENT;
notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
Intent intent = new Intent(this, TimingService.class);
PendingIntent activity = PendingIntent.getActivity(this, 0, intent, 0);
notification.setLatestEventInfo(this, "herp", "counter: " + counter, activity);
//This is clearly not 1337, but a good joke
startForeground(1337, notification);
}
}
All this does when it runs is shows "A New Notification", and then changes to "herp counter: 30000". However, this notification never changes. It just stays 30000. Why? I thought I fixed this with making the flag ongoing?
https://developer.android.com/reference/android/app/Notification.Builder.html#setUsesChronometer(boolean)
Show the when field as a stopwatch. Instead of presenting when as a
timestamp, the notification will show an automatically updating
display of the minutes and seconds since when. Useful when showing an
elapsed time (like an ongoing phone call). The counter can also be set
to count down to when when using setChronometerCountDown(boolean).
No updating required, works off the setWhen() value
NotificationCompat.Builder notification = new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_default_notification)
.setTicker("Ticker Text")
.setWhen(when) // the time stamp, you will probably use System.currentTimeMillis() for most scenarios
.setUsesChronometer(true)
.setContentTitle("Title Text")
.setContentText("Content Text");
counter is not a reference; the notification will not update with its new value until you explicitly tell it to.
Have a look at the documentation on updating an existing notification. Your ID is 1337 here, so you can use that to update it.
In fact, you may just be able to call declareNotification() again from your onTick() method... If this doesn't work, however, I would suggest keeping a reference to the Notification object (as a member variable), then updating it, and use nm.notify(1337, /* your notification object */);.
I don't know why you want to use a notification. But you need to keep updating your notification. For a simple fix add
declareNotification();
underneath this line:
counter = millisUntilFinished / 1000;
Note that this isn't a great way to code it. Really you should pass a method only updating the notification rather than "creating" a new one. However as long as they have the same ID, one will replace the other.
Also just to use a more up to date way of managing notifications, use
NotificationCompat.builder b = new NotificationCompat.Builder(context);

How to display current time every fixed time interval in the status bar?

I am having a hard time figuring out how to display the current time every fixed time interval in the status bar using service with its own thread. The following code allows me to display the current time when I click the start service button (there is also a stop service button) but it does not display the current time again. I suspect some sort of loop or timer is needed or perhaps my thread sleep mechanism is not correct. Please hint or suggest a solution. The run method is where help is needed (first). Thanks much in advance!
public class MyOwnService extends Service {
// Use a layout id for a unique identifier
private static int TIME_NOTIFICATIONS = R.layout.status_bar_notifications;
// variable which controls the notification thread
private ConditionVariable mCondition;
private NotificationManager mNM;
// Create Runnable object
private Runnable mTask = new Runnable() {
public void run() {
try{
SimpleDateFormat sdfDate = new SimpleDateFormat("hh:mm:ss");
Date now = new Date();
String strDate = sdfDate.format(now);
showNotification(R.drawable.icon, strDate);
Thread.sleep(30000);
} catch (Exception e) {
}
// Show happy face for 5 seconds
//showNotification(R.drawable.icon, strDate);
//mCondition.block(5 * 1000);
// Done with our work... stop the service!
//MyOwnService.this.stopSelf();
}
};
#Override
public void onCreate() {
mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
/// Start up the thread running the service. Note that we create a
/// separate thread because the service normally runs in the process's
/// main thread, which we don't want to block.
Thread notifyingThread = new Thread(
null, // Thread group
mTask, // Runnable object
"NotifyingService"); // Thread name
mCondition = new ConditionVariable(false);
notifyingThread.start();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
// Cancel the persistent notification.
mNM.cancel(MOOD_NOTIFICATIONS);
// Stop the thread from generating further notifications
mCondition.open();
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
private void showNotification(int timeId, String strTime) {
// In this sample, we'll use the same text for the ticker and the
// expanded notification
CharSequence text = strTime;
// Set the icon, scrolling text and time stamp.
// Note that in this example, we pass null for tickerText. We update the
// icon enough that
// it is distracting to show the ticker text every time it changes. We
// strongly suggest
// that you do this as well. (Think of of the "New hardware found" or
// "Network connection
// changed" messages that always pop up)
Notification notification = new Notification(timeId, text, System
.currentTimeMillis());
// The PendingIntent to launch our activity if the user selects this
// notification
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, ServiceLauncher.class), 0);
// Set the info for the views that show in the notification panel.
notification.setLatestEventInfo(this,
getText(R.string.status_bar_notification_title), text,
contentIntent);
// Send the notification.
// We use a layout id because it is a unique number. We use it later to
// cancel.
mNM.notify(TIME_NOTIFICATIONS, notification);
}
// This is the object that receives interactions from clients. See
// RemoteService for a more complete example.
private final IBinder mBinder = new Binder() {
#Override
protected boolean onTransact(int code, Parcel data, Parcel reply,
int flags) throws RemoteException {
return super.onTransact(code, data, reply, flags);
}
};
}
Run() is not a loop. You need to wrap your code in a while loop.
You also want to add a way to stop that thread gracefully so in your while loop you should check a variable that can be set from the main thread. ie
while(!stopped){ ... }
then add this to your onDestory()
mTask.stopped = true;

Categories

Resources