Not able to stop service using Handler in android - android

I just start background service in Handler.now I want to stop Service but service not stopped from Handler and any other class.
below is My Code:-
below is handler where i try to Start And Stop Service.
mHandler = new Handler();
mRunnable = new Runnable() {
#Override
public void run() {
Log.e("mTrackStatus",String.valueOf(mTrackStatus));
if (mTrackStatus == 1) {
Log.e("BACKGROUND=", "background Service Start");
//handler will call after every 10 seconds
context.startService(new Intent(context, BackgroundService.class));
mHandler.postDelayed(mRunnable, 10000);
} else if (mTrackStatus == 2) {
Log.d("StopTracking", "StopTracking");
context.stopService(new Intent(context, BackgroundService.class));
mHandler.removeCallbacks(mRunnable);
}
}
};
// mHandler.postDelayed(mRunnable, 10000);
mRunnable.run();
I have tried Lot's Of method like
1. context.stopService(new Intent(context,BackgroundService.class)); and stopSelf(); but it will not work for me

I have Spent 2 days on this problem. Finally i Solve the Issue.Actually My BackgrounService is Stop by using :-
context.stopService(new Intent(context, BackgroundService.class));
I use onLocationChanged() method in My services class and when i Try to Stop Service, Service is Stopped but onLocationChanged() method is Continue sly running in Background. By using Stop Service Service is stop but onLocationChanged() is not Stopped because it Android Default method which we can not able stop that.

Related

How can we call an api in every 2 minutes in android N or higher versions even when the app is closed or killed

I want a best consistent solution to call an api to update current location in every 2 minutes on Nougat and higher version. The process should not be terminated even when the app is killed or closed.
Thanks in advance
Create a services:
public class MyServices extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
startService(new Intent(this,MyServices.class));
Timer t = new Timer();
final Handler handler = new Handler();
// Timer task makes your service will repeat after every 20 Sec.
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
//Do network call here
}
});
}
};
//Starts after 20 sec and will repeat on every 20 sec of time interval.
t.schedule(doAsynchronousTask, 3000,3000); // 20 sec timer
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
}
Register the service in menifest
<service android:name=".MyServices" />
Start the service in your activity
Intent intent = new Intent(this, MyServices.class);
startService(intent);
if version > N use this
startForegroundService(intent);
Create a service and update from there.
Service will not stop after closing the application but it will get stopped if the application is force stopped.
And also if your app goes to doze mode your app cannot use Internet or GPS service from the background.
You should check out WorkManager to schedule any kind of work you want your app to do.

Can't kill service from BroadcastReceiver

I start service from activity which are sending data throught socket to server. When service is started in it's onCreate() method I also set alarm with setExact() method. My problem is that when onReceive() in BroadcastReceiver is called I want to stop service, which is working corectly but it is also immedeately started again. Service is stopped with next code:
Intent i = new Intent(context, SocketService.class);
context.stopService(i);
which work correctly if it is called from Activity. When BroadcastReceiver is executed, no activity is binded to that service so it should stop without immedeately recreating.
Your service.
private Intent myservice;
Start your service on method onCreate()
myservice = new Intent(this, myservice.class);
startService(myservice);
also you can start your service with handler.
And for stop use handler.
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
stopService(myservice);
break;
default:
Log.d("STOP", msg.what + " ? ");
break;
}
}
};
for use handler on BroadcastReceiver make this
handler.sendEmptyMessage(1);

Android start a service every 5 seconds

I want to make a finite State Machine first calling my StartEstablishService() method every 5 seconds so that the app will try to reconnect to the service once the service fails. When the service fails it will destroy the service and the only thing I need to do the to call the StartEstablishService() method again and this is the output after connection failed :Destroying service...Service destroyed
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "Destroying service...");
t.interrupt();
Log.d(TAG, "Service destroyed.");
}
How do I call the StartEstablishService() every 5 seconds? I tried to call the following method after the service is destroyed
public void startExploring() {
Log.e(TAG,"Start Exploring Every 8 Seconds...");
final int FIVE_SECONDS = 5000;
final MainActivity activity = (MainActivity) getActivity();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
activity.startData();
handler.postDelayed(this,
FIVE_SECONDS);
}
}, 5000);
but it the activity is always null??
You can use an alarm manager for starting service every 5 minutes.
For finding why activity is null,you have to post more code including filename,structure you used etc

Start Android Service after every 5 minutes

I was searching over the internet for last 2 days but I couldn't find any tutorial helpful. I have created a service and I am sending a notification in status bar when the service starts. I want that service to stop after showing the notification and start it again after 5 minutes. Please let me know if it is possible and provide me some helpful tutorials if you have any. I heard of TimerTask and AlarmManager and I tried to use them as well but I wasn't able to get the desired result.
EDIT: I need the service to be started every 5 minutes even if my application is not running.
You do not want to use a TimerTask since this depends on your application running continuously. An AlarmManager implementation makes it safe for your application to be killed between executions.
Stating that you tried to use AlarmManager but did not get the desired result is not a helpful statement, in that it tells no one how to help you to get it right. It would be much more useful to express what happened.
http://web.archive.org/web/20170713001201/http://code4reference.com/2012/07/tutorial-on-android-alarmmanager/ contains what appears to be a useful tutorial on AlarmManager. Here are the salient points:
1) Your alarm will cause an Intent to fire when it expires. It's up to you to decide what kind of Intent and how it should be implemented. The link I provided has a complete example based on a BroadcastReceiver.
2) You can install your alarm with an example such as:
public void setOnetimeTimer(Context context) {
AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
intent.putExtra(ONE_TIME, Boolean.TRUE);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (1000 * 60 * 5), pi);
}
Below I have provided three files, MainActivity.java for start service, Second file MyService.java providing service for 5 Minute and Third is manifest file.
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, MyService.class)); //start service which is MyService.java
}
}
MyService.java
public class MyService extends Service {
public static final int notify = 300000; //interval between two services(Here Service run every 5 Minute)
private Handler mHandler = new Handler(); //run on another Thread to avoid crash
private Timer mTimer = null; //timer handling
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
if (mTimer != null) // Cancel if already existed
mTimer.cancel();
else
mTimer = new Timer(); //recreate new
mTimer.scheduleAtFixedRate(new TimeDisplay(), 0, notify); //Schedule task
}
#Override
public void onDestroy() {
super.onDestroy();
mTimer.cancel(); //For Cancel Timer
Toast.makeText(this, "Service is Destroyed", Toast.LENGTH_SHORT).show();
}
//class TimeDisplay for handling task
class TimeDisplay extends TimerTask {
#Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
#Override
public void run() {
// display toast
Toast.makeText(MyService.this, "Service is running", Toast.LENGTH_SHORT).show();
}
});
}
}
}
AndroidManifest.xml
<service android:name=".MyService" android:enabled="true" android:exported="true"></service>
Create a Timer object and give it a TimerTask that performs the code you'd like to perform.
Timer timer = new Timer ();
TimerTask hourlyTask = new TimerTask () {
#Override
public void run () {
// your code here...
}
};
// schedule the task to run starting now and then every hour...
timer.schedule (hourlyTask, 0l, 1000*60*60); // 1000*10*60 every 10 minut
The advantage of using a Timer object is that it can handle multiple TimerTask objects, each with their own timing, delay, etc. You can also start and stop the timers as long as you hold on to the Timer object by declaring it as a class variable or something.

how to stop Intent services in android

i have created one intent service. Now I want to stop that service from activity how to stop that service? My code is:
MyActivity.java
#Override
public void onCreate(Bundle savedInstanceState) {
Intent intent = new Intent(this, myService.class);
intent.putExtra("myHand", new Messenger(this.myHand));
startService(intent);
}
myService.java
public class myService extends IntentService {
#Override
protected void onHandleIntent(Intent intent) {
String signal = intent.getAction();
if (signal != null && signal.equals("stop")) {
stopSelf();
} else {
t.schedule(new TimerTask() {System.out.println("print")}, 0, 10000);
}
}
}
to stop service on click of button
Intent in = new Intent(this, myService.class);
in.setAction("stop");
stopService(in);
can anybody help me to stop service?
From the docs for IntentService
IntentService is a base class for 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.
In other words, you don't have to stop an IntentService - it will terminate itself when it has no more work to do.
EDIT:
Looking back at your code, it seems you don't wan't to stop the IntentService you want to stop the TimerTask???
t.schedule(new TimerTask() {System.out.println("print")}, 0, 10000);
I don't know what t is but I'm guessing it's a Timer. If that's the case it will be running with its own Thread and attempting to terminate the IntentService is pointless - kill the Timer instead.
Also, why are you using an IntentService to create any type of object which maintains its own thread of execution?
Now I want to stop that service from activity how to stop that
service?
IntentService stops itself, you shouldn't, you can't call stopSelf().
When all requests have been handled, the IntentService stops itself.
From what I know, IntentHandler creates a separate new thread, does its work, and kills itself.
So I don't think you need to explicitly stop it from an activity.

Categories

Resources