How to dismiss progress dialog from service? - android

I have an activity and it shows progress dialog when the user starts download
And the download from ftp start in a service
I want to dismiss this progress dialog when the service finishes downloading file
How to dismiss it from service?

A better approach would be to use LocalBroadcastManager for notifying Activity from Service.
Step1: Send the local broadcast from your service
public class MyService extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// do your operation here(create worker thread for blocking operations)
sendLocalBroadCast() //call this method as soon as above operations completes
return Service.START_NOT_STICKY;
}
}
private void sendLocalBroadCast() {
Intent intent = new Intent("MY_SERVICE_NOTIFICATION");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
Note that the system calls onStartCommand(Intent intent, int flags, int startId) on your service's main thread. A
service's main thread is the same thread where UI operations take
place for Activities running in the same process. You should always
avoid stalling the main thread's event loop. When doing long-running
operations, network calls, or heavy disk I/O, you should kick off a
new thread, or use AsyncTask
Step2: Make your Activity listen to this broadcast
public class MyActivity extends Activity{
BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// you can dismiss your progress dialog here. This method will be called when we receive broadcast from service after the service operation is completed
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
//register for listening to "MY_SERVICE_NOTIFICATION" event
LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver,
new IntentFilter("MY_SERVICE_NOTIFICATION"));
}
#Override
protected void onDestroy() {
super.onDestroy();
// remove the receiver
LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
}
}

Create an interface finishListener which has listen method, implement it in the activity to do whatever you want and pass it to the service constructor from there call listen method

Its simple
alertdialog.dismiss();
just put that in the bottom of your install code

Related

Oreo Foregroundservice the right way

What is the right way to implement the foregroundservice notification. Call the notification before starting backgroundthread or calling it in the backgroundthread? Tried both ways and it worked the same but what is the right way?
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
//calling notification before backgroundthread
runAsForeground();
Runnable service = new Runnable() {
#Override
public void run() {
//calling notification in backgroundthread
runAsForeground();
connect(client,options);
}
};
Thread backgroundThread = new Thread(service);
backgroundThread.start();
Log.i(TAG, "onStartCommand methode called");
return Service.START_NOT_STICKY;
}
Call the notification before starting backgroundthread or calling it
in the backgroundthread?
As soon as possible, to be more precise, the app must call service's startForeground() method within five seconds after the service is created.
So, in your particular situation there's no real reason or benefit in delaying the call by starting it from the Runnable.

difference between Service and IntentService

To know the difference between IntentService and Service in Android, I created the below posted small test of an IntentService class. The IntentService class can be started using
startService(intent); which will result in a call to nStartCommand(Intent intent, int flags, int startId). Also to send values from the IntentService class to the MainActivity
for an example, we should send it via sendBroadcast(intent); and the MainActivity should register a broadcastReceiver for that action so it can receive the values sent via
sendBroadcast(intent);
so far I cant see any difference between Service and IntentService!! Since they are similar in the way of starting them and the way they broadcast data,can you please tell me in
which context they differ?
please tell me why i am receiving those errors and how to solve it
MainActivity
public class MainActivity extends AppCompatActivity {
private final String TAG = this.getClass().getSimpleName();
private Button mbtnSend = null;
private int i = 0;
private BroadcastReceiver mBCR_VALUE_SENT = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(MyIntentService.INTENT_ACTION)) {
int intnetValue = intent.getIntExtra(MyIntentService.INTENT_KEY, -1);
Log.i(TAG, SubTag.bullet("mBCR_VALUE_SENT", "intnetValue: " + intnetValue));
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerReceiver(this.mBCR_VALUE_SENT, new IntentFilter(MyIntentService.INTENT_ACTION));
this.mbtnSend = (Button) findViewById(R.id.btn_send);
this.mbtnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MyIntentService.class);
intent.putExtra("intent_key", ++i);
startService(intent);
}
});
}
}
MyIntentService:
public class MyIntentService extends IntentService {
private final String TAG = this.getClass().getSimpleName();
public final static String INTENT_ACTION = "ACTION_VALUE_SENT";
public final static String INTENT_KEY = "INTENT_KEY";
public MyIntentService() {
super(null);
}
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* #param name Used to name the worker thread, important only for debugging.
*/
public MyIntentService(String name) {
super(name);
setIntentRedelivery(true);
}
#Override
public void onCreate() {
super.onCreate();
Log.w(TAG, SubTag.msg("onCreate"));
}
#Override
protected void onHandleIntent(Intent intent) {
Log.w(TAG, SubTag.msg("onHandleIntent"));
int intent_value = intent.getIntExtra("intent_key", -1);
Log.i(TAG, SubTag.bullet("", "intent_value: " + intent_value));
Intent intent2 = new Intent();
intent2.setAction(MyIntentService.INTENT_ACTION);
intent2.putExtra(MyIntentService.INTENT_KEY, intent_value);
sendBroadcast(intent2);
SystemClock.sleep(3000);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.w(TAG, SubTag.msg("onStartCommand"));
return super.onStartCommand(intent, flags, startId);
}
In short, a Service is a broader implementation for the developer to set up background operations, while an IntentService is useful for "fire and forget" operations, taking care of background Thread creation and cleanup.
From the docs:
Service A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use.
IntentService Service is a base class for IntentService Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.
Refer this doc - http://developer.android.com/reference/android/app/IntentService.html
Service
This is the base class for all services. When you extend this class, it’s important that you create a new thread in which to do all the service’s work, because the service uses your application’s main thread, by default, which could slow the performance of any activity your application is running.
IntentService
This is a subclass of Service that uses a worker thread to handle all start requests, one at a time. This is the best option if you don’t require that your service handle multiple requests simultaneously. All you need to do is implement onHandleIntent(), which receives the intent for each start request so you can do the background work.
Below are some key differences between Service and IntentService in Android.
1) When to use?
The Service can be used in tasks with no UI, but shouldn’t be too long. If you need to perform long tasks, you must use threads within Service.
The IntentService can be used in long tasks usually with no communication to Main Thread. If communication is required, can use Main Thread handler or broadcast intents. Another case of use is when callbacks are needed (Intent triggered tasks).
2) How to trigger?
The Service is triggered calling to method onStartService().
The IntentService is triggered using an Intent, it spawns a new worker thread and the method onHandleIntent() is called on this thread.
for more clarity refer this
http://www.onsandroid.com/2011/12/difference-between-android.html

how to stop Handler working in android?

My APP has to start some time consuming job when receiving ACTION_SCREEN_OFF, and interrupt the job when receiving ACTION_SCREEN_ON if job is still going on.
public class TimeConsumingWorkIntentService extends IntentService {
#Override
protected void onHandleIntent(Intent intent) {
TimeConsumingWork();
}
}
public class ScreenStatusReceiver extends BroadcastReceiver {
Intent intent = new Intent(mContext, TimeConsumingWorkIntentService.class);
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
mContext.startService(intent );
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
mContext.stopService(intent );
}
}
}
By print log of time, I find time consuming work is still going on stop the TimeConsumingWorkIntentService (when receiving ACTION_SCREEN_ON).
why ?
Use
// Cancel the runnable
myHandler.removeCallbacks(yourRunnable);
Ok , then you can do something like this
Runnable r = new Runnable{
public void run(){
if(booleanCancelMember != false){
// within this you make the call to handler and work
// Since you block the call the handler wont get repeated
}
}
}
You can't do this like that. When you start your IntentService, it will call onHandleIntent() on a separate worker thread. That mehod then calls TimeConsumingWork(). Stopping the service will not interrupt the execution of the worker thread. It just tells the worker thread that when it has finished processing the current Intent, it should stop.
What you will need to do is to have your TimeConsumingWork() method periodically look to see if it should stop. You can do this by setting a static boolean variable and have TimeConsumingWork() periodically check this variable and quit if it is set.
You don't need to call stopService() on an IntentService as it will stop itself when it has nothing to do.

stop IntentService from Activity

I need help with this situation:
I have activity, what starts IntentService.
Service do some job in while cycle and sleep for some time.
Main cycle of service is endless, so I need to stop it from activity again.
I must be able to end activity, start it again and stop IntentService from new "instance" of activity.
public class MyService extends IntentService {
public MyService()
{
super("MyService");
}
public MyService(String name) {
super(name);
}
#Override
protected void onHandleIntent(Intent intent) {
Log.d("SERVICE", "start");
while(true)
{
SystemClock.sleep(1000);
Log.d("SERVICE", "tick");
}
}
#Override
public void onDestroy() {
Log.d("SERVICE", "end");
super.onDestroy();
}
...
Intent intent = new Intent(getApplicationContext(), MyService.class);
startService(intent);
I tried calling stopService(), but it's not working. Is there any solution how to do this?
Thanks in advance.
Service do some job in while cycle and sleep for some time.
IMHO, this is an inappropriate use of IntentService. Please create a regular Service, with your own background thread that you manage yourself.
Is there any solution how to do this?
Create a regular Service, with your own background thread that you manage yourself. For example, you could use a ScheduledExecutorService instead of your sleep() loop, using shutdown() or shutdownNow() in the service's onDestroy().

how can i stop my RECEIVE_BOOT_COMPLETED service

seeing many questions about this but im unable to fix this.
I have this code
public class myBroadcastReceiver extends BroadcastReceiver {
private final String TAG = "myBroadcastReceiver";
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(Consts.ANDROID_INTENT_ACTION_BOOT_COMPLEATE)){
Intent newinIntent = new Intent(context, ServiceBootCompleated.class);
context.startService(newinIntent);
}
}
}
It starts a Service and i can debug it using this line
android.os.Debug.waitForDebugger();
I see that return START_NOT_STICKY; is executed but still
the service is visible as a "running" service in the
Setttings>programs>Running Services
the onDestroy() is never called unless i stop it manually.
What do i have to do to stop it,
remove it from "Setttings>programs>Running Services " window?
Once you have completed the work you wanted to do in the background call stopSelf()
Be sure that any real work you do in the Service is done as a background thread and not in onCreate or onStartCommand.
See http://developer.android.com/reference/android/app/Service.html#ServiceLifecycle for more details on the Service Lifecycle.
Example:
public int onStartCommand(final Intent intent, final int flags, final int startId)
{
Thread thread = new Thread(new Runnable()
{
#Override
public void run()
{
//do work
stopSelf();
}
},"MyWorkerThread");
thread.start();
return Service.START_NOT_STICKY;
}
on completion of task, you have to do context.stopService() for stopping this type of unbound service.
Regards,
SSuman185

Categories

Resources