A simple question, how to make a Service repeat at log cat console msg "hello", as long as the Service is living/is active? I've tried:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.v("LocalService", "Received start id " + startId + ": " + intent);
Mano lopas = new Mano(this);
lopas.Lopas();
while(true) {
Log.v("HAHA", "hello");
}
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
But it never returns START_STICKY, actually it doesnt even build the project. I think im missing something about services? I start my service, in MainActivity in my application, like:
startService(new Intent(getApplicationContext(),Myclass.class));
And it runs only once without my while loop in my service. It says me something in Logcat and this is it. Morever, my service starts so many times as many times I re-open my application. How to make service start run once and "forever", I mean untill it gets killed by the system or user kills it.
Services don't have their own thread, they run on the UI thread. If you want it to run in parallel, you need to create a Thread. So here you should create a Thread in your onStartCommand, and that thread should do whatever it is you want.
Same way you'd log something at intervals in your activity: use a Handler. Post a task that logs a message and re-posts itself to the same Handler using postDelayed(...). Cancel any pending execution in your activity's onPause() or your service's onDestroy().
Note that there is almost never a good reason to explicitly create a Thread or use J2SE constructs like TimerTask in Android. For heavyweight tasks, use AsyncTask. For lightweight tasks, use Handlers. In your case, creating a new Thread would be a ridiculously heavyweight solution for what you want to do.
First of all, do not forget to register the Service in your Manifest.
This can be done by using
<service android:enabled="true" android:name=".services.Paycan" />
Next is, that your Service (if its not an intentservice) run in the MainUI. If you create an endless loop make sure it's in a background thread, otherwise it will freeze the app.
You can do it using an Asynctask, a Thread which get created with onStartCommand and stopped in onDestroy or use an IntentService instead of a Service.
example:
public class yourTestClass extends Service {
Thread testThread;
boolean threadRunning = false;
#Override
public void onCreate() {
super.onCreate();
testThread = new Thread() {
#Override
public void run() {
try {
while(threadRunning) {
Thread.sleep(1000);
Log.i("test", "....");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
threadRunning = true;
testThread.start();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
threadRunning = false;
}
Related
I want to close a background thread in my service in the onDestroy method, because if I stop my service the background thread is still running. Because thread.stop() is deprecated, I don't really know how to do it.
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
runAsForeground();
Runnable service = new Runnable() {
#Override
public void run() {
connect(client,options);
}
};
backgroundThread = new Thread(service);
backgroundThread.start();
Log.i(TAG, "onStartCommand methode called");
return Service.START_NOT_STICKY;
}
Thread life cycle is not the same as Android Context Component life cycle. Stopping the service is not enough to stop the thread which service created. Thread.interrupt() is a option. - You should catch InterruptedException though. If it is not enough, you can check if service is not stopped inside your connect() method.
I suppose you're using a Service. Then you can Context.stopService(intent) just the same way you Context.startService(intent).
You can use
stopService(new Intent(this, YourService.class));
It will stop this service and all its Threads.
I have a Service and AsyncTask running at the same time, Inside the service, storing the data in the server takes place, In AsyncTask, getting data from a different source and updating UI takes place.
UI doesn't get updated until the the task inside the Service gets completed, after that UI gets displayed
protected List<AppItem> doInBackground(MyTaskParams... integers) {
android.os.Process.setThreadPriority(THREAD_PRIORITY_BACKGROUND + THREAD_PRIORITY_MORE_FAVORABLE);
I used the above code for asynctask , but its not working, how can I give more preference to AsyncTask than Service
use this piece of code instead
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
By default, Service runs on the Main thread.
Remember that if you do use a service, it still runs in your
application's main thread by default, so you should still create a new
thread within the service if it performs intensive or blocking
operations.
https://developer.android.com/guide/components/services?hl=en#should-you-use-a-service-or-a-thread
It looks like you start your Service first, then you run your AsyncTask. Because the service runs in the Main thread, your AsyncTask is not started until it finishes.
Update
There are many solutions and the choice depends on requirements. It looks like in your case the simplest way to achieve concurrency is to use the IntentService. So, you can start both the IntentService and AsyncTask from your Activity.
public class MyIntentService extends IntentService
{
private static final String TAG = this.getClass().getSimpleName();
public MyIntentService() {
super("MyIntentService");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
super.onStartCommand(intent, flags, startId);
Log.d(TAG, "MyIntentService Started");
// This thing still happens on ui thread
return START_NOT_STICKY;
}
#Override
protected void onHandleIntent(Intent intent)
{
Log.d(TAG, "MyIntentService Handling Intent");
// Your work should be here, it happens on non-ui thread
}
}
https://developer.android.com/reference/android/app/IntentService
I tried to use the following code trigger toast as background service but it gets executed for 20 times, it was not working till 100. With thread it is not working gives error.
Felt service get destroyed.
How to trigger notification with 30 minutes difference as a background service, though app is closed,
I need to display Good morning, Good Afternoon, Good Evening and Good night as a Notification.
without any internet support.
Is following procedure not ok? I think so. How to do this?
import android.app.Service;
public class HelloService extends Service {
private static final String TAG = "HelloService";
int i=0;
private boolean isRunning = false;
#Override
public void onCreate() {
Log.i(TAG, "Service onCreate");
Toast.makeText(this, " On create Hello Service Started", Toast.LENGTH_LONG).show();
isRunning = true;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "Service onStartCommand");
for (;i<100; i++) {
try {
// Thread.sleep(1000);
Toast.makeText(getApplicationContext(), "Hello Service On Loop"+i , Toast.LENGTH_LONG).show();
//
} catch (Exception e) {
}
}
//Stop service once it finishes its task
// i++;
stopSelf();
return Service.START_STICKY;
}
#Override
public IBinder onBind(Intent arg0) {
Log.i(TAG, "Service onBind");
return null;
}
#Override
public void onDestroy() {
isRunning = false;
Log.i(TAG, "Service onDestroy");
}
}
onStartCommand() is called on the main (UI) thread. If you execute a loop inside onStartCommand(), Android will kill the process after about 30 seconds with an ANR (Application Not Responding) because you cannot block the main (UI) thread.
You can do what you want either using AlarmManager to set a timer that will start your Service or trigger a BroadcastReceiver at certain times, or you can post a Runnable to a Handler in onStartCommand() with a certain delay and do whatever you want in the Runnable, or you can start a background thread in onStartCommand() and the background thread can loop and sleep or whatever and then do what you want.
In any case, you cannot show a Toast every second. This will flood the UI with toasts and either Android will dump most of them (ignore them) or the UI will be so busy showing them that Android will kill your app due to ANR or the user will just uninstall your app!
I have a service that have an variable life time. It may execute from 5 minutes to 2 hours (for example). So I'm looking for the best approach to do that, and my service must achieve the following features:
Send (to my server) lat-long every 5 seconds and some extra information (string's, boolean's and int's)
I have tried a "normal" service and tried to do something like this to achieve this:
public class MyFiveSecondsService extends Service {
private Handler handler;
Runnable r = new Runnable() {
#Override
public void run() {
//here send my new data
}
};
public void onCreate(){
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(handler == null){
handler = new Handler();
}
handler.post(r);
return super.onStartCommand(intent, flags, startId);
}
}
Actually that code works, but I got some performance problems with that approach, so I tried to do something like this:
public class SendUniquePositionIntentService extends IntentService {
public SendUniquePositionIntentService() {
super("co.bomboapp.Service.IntentService.SendUniquePositionIntentService");
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
protected void onHandleIntent(Intent intent) {
//do the logic here
}
}
public class MyFiveSecondsService extends Service {
private Handler handler;
Runnable r = new Runnable() {
#Override
public void run() {
//call my SendUniquePositionIntentService here
}
};
public void onCreate(){
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(handler == null){
handler = new Handler();
}
handler.post(r);
return super.onStartCommand(intent, flags, startId);
}
}
And that approach haven't worked, when I had closed the app any service kept running. So before start any other attempt to achieve this, I want some direction, what's the best approach to do this "infinite loop service" and keep the performance?
I'm using Android 4.1 as min API, and targeting 5.0 API.
My test device is a Nexus 5 running Android 6.
Right now I'm using parse.com as database.
"I have tried a "normal" service...but I got some performance problems"
By default, a service runs on the application's main thread, so when you create a handler with
public int onStartCommand(Intent intent, int flags, int startId) {
if(handler == null){
handler = new Handler();
}
...
}
the handler is associated with the main thread's Looper and all messages and runnables are delivered and later executed on the thread. That's the reason of the "performance problems". From the documentation:
Remember that if you do use a service, it still runs in your application's main thread by default...
Regarding the second approach and the part
"...when I had closed the app any service kept running"
you haven't mentioned how exactly you "close" the app, but what I can see is
public int onStartCommand(Intent intent, int flags, int startId) {
...
return super.onStartCommand(intent, flags, startId);
}
which means that if the system kills the service it, by default, will be recreated. So if "closing" your app means killing it, the following chain of actions takes place:
The system recreates MyFiveSecondsService,
onStartCommand() is called and the handler posts the runnable
within the run() method SendUniquePositionIntentService is started
From the documentation of onStartCommand():
the default implementation calls onStart(Intent, int) and returns either START_STICKY or START_STICKY_COMPATIBILITY.
Note that starting a service from another one (like starting SendUniquePositionIntentService from MyFiveSecondsService in your case) is redundant unless you intended to.
The final part of your question is confusing to me. On one hand it doesn't work for you because "...any service kept running" but, on the other hand, you'd like "do this "infinite loop service""...?
If you only need to send such information as "strings, booleans and ints" to a server (without any feedback to the component that started the service), I suppose it's simply enough for you to use IntentService. This is a "out-of-box" framework that does its work on a background thread (letting you avoid freezing the main thread) and stops itself once it's done. As an example you can use the documentation on IntentService - it's well written.
Also note that the behaviour of a service after killing it by the system depends on the flag returned by onStartCommand(). E.g. use START_NOT_STICKY to not recreate the service after killing the app or START_REDELIVER_INTENT to recreate it with the last Intent redelivered.
I currently have a service that processes some stuff, and it is started with startService.
I was wondering, can I call `stopService immediately after I start the service and expect it to stop the service after the processing is done?
Or does Android kill the service when I call that command?
One hopes that "processes some stuff" is done in a background thread, assuming that it will take more than a couple of milliseconds.
Android is largely oblivious to such a background thread. stopService() will trigger onDestroy() of the service, and the service will go away. The thread, however, will continue to run, until it terminates on its own, or until the process is terminated.
can I call `stopService immediately after I start the service and expect it to stop the service after the processing is done?
Only if "the processing" is done on the main application thread (e.g., in the body of onStartCommand()), which, again, is not a good idea if such work will take more than a couple of milliseconds. And, if that indeed is the case, there's no good reason for having a service in the first place.
If you want to have a service that:
Has a background thread, and
Automatically shuts down when the work is complete (avoiding the need for stopService())
then use an IntentService.
Android can't kill just a single Service. All it can do is to kill the whole process and everything running within. Most apps will have just 1 process so this usually means Android kills everything or nothing. Most of the times nothing.
The lifecycle of a Service or Activity tells Android whether it may kill the process safely or not. The Processes and Threads describes the order in which processes are kill if there is demand for memory.
It is important to know that a Thread started from a Service / Activity it is not affected at all by onDestroy etc. It just keeps running. Android simply does not know about that thread and won't stop it for you.
That means if you want to do some background processing you have link the lifecycle of such threads to the lifecycle of your Activity / Service or Android may just kill the process and thus your thread.
Quick example of a Service that prints to logcat every second while running. Not based on IntentService since that's more or less intended for tasks with an end.
public class MyService extends Service {
public static void start(Context context) {
context.startService(new Intent(context, MyService.class));
}
public static void stop(Context context) {
context.stopService(new Intent(context, MyService.class));
}
private final ExecutorService mBackgroundThread = Executors.newSingleThreadExecutor();
private Future<?> mRunningTask;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// startService -> start thread.
if (mRunningTask == null) {
// prevents task from being submitted multiple times.
// actually not necessary when using a single thread executor.
mRunningTask = mBackgroundThread.submit(mRunnable);
}
return START_STICKY;
}
private Runnable mRunnable = new Runnable() {
#Override
public void run() {
while (!Thread.interrupted()) {
try {
// Do something
Log.d("Service", "I'm alive");
Thread.sleep(1000);
} catch (InterruptedException e) {
Log.d("Service", "Got interrupted", e);
Thread.currentThread().interrupt();
}
}
}
};
#Override
public void onDestroy() {
// stopService > kill thread.
mBackgroundThread.shutdownNow();
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
According to the documentation:
stopService(Intent service)
Request that a given application service be stopped. If the service is
not running, nothing happens. Otherwise it is stopped. Note that calls
to startService() are not counted -- this stops the service no matter
how many times it was started.
Note that if a stopped service still has ServiceConnection objects
bound to it with the BIND_AUTO_CREATE set, it will not be destroyed
until all of these bindings are removed. See the Service documentation
for more details on a service's lifecycle.