Recently, I am studying a code about printer Bluetooth connection.
The program try implement runnable in the MainActivity.
Here I would like to ask 2 question.
1.How can I execute the activity as a thread when there is no other program calling run() of this activity?
2.Is there any special meaning for implementing runnable in MainActivity? Are ther any difference between implementing runnable in a class other than MainActivity?
I am not too certain what you are asking in the first question because code inside Activity will always run on the main (UI) thread by default.
To answer your second question, the MainActivity is probably implementing the Runnable interface only to define some code that can be executed on a Thread later.
For example, you can call runOnUiThread (Runnable action) from the Activity, passing MainActivity.this as the runnable parameter to execute code on the main thread.
You can also spawn a new thread with the runnable to have it run in the background or post it to a handler.
There is a sequence of callback methods that start up an activity and a sequence of callback methods that tear down an activity.
1)Created 2)Started 3)Resumed 4) Paused 5) Stopped 6)Destroyed
However, only three of these states can be static :-3)Resumed 4) Paused 5) Stopped,,,,
Resumed State(Running state):- In this state, the activity is in the foreground and the user can interact with it.
(Also sometimes referred to as the "running" state.)
here are simply two rules to Android's single thread model:
1) Do not block the UI thread
2)Do not access the Android UI toolkit from outside the UI thread
Related
As I understand - both Runnable and Service are intended to run piece of code in background. My code structure is this:
BaseManager.class which is implemented as Singleton and using BaseManager.getInstance() will return single instance in application. Also, when first initialized it automatically creates SmallerAndCompletelyDifferentManager.class - has a dependency.
SmallerAndCompletelyDifferentManager.class - creates a Runnable that runs every 2 seconds.
Now, I've two scenerios:
SCENERIO A: I create initialize BaseManager.class in Activity first and use it wherever I need. The Runnable that is inside SmallerAndCompletelyDifferentManager.class runs okay, but as I understand is attached to Activity - if Activity dies, so will the Runnable which I can not afford.
SCENERIO B: I create a foreground service and initialize BaseManager.class. Does this mean that now the Runnable will work as intended - even if application is in background and Activity has been destroyed?
Am I getting this right or no? The overall plan is to make sure that Runnable survives in background at all costs.
As I understand - both Runnable and Service are intended to run piece
of code in background
This is not correct.
Service is an application component that can be perform long-running operations in the background. Here background means you do something behind the scene (or background) when users interact with the app, or when users switch to another apps.
Runnable is a block of code that can be run, that why it has the name "Runnable", it means something can be run/execute. The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread.
In Android there a two types of thread, the first one is main/UI thread and another one is background thread. Here background means when you do something in a thread rather than main/UI thread.
Back to your case
In scenario 1: The Activity creates Runnable and keep a reference to it. When you destroy the activity (by press Back button or call finish() method), the activity will be destroyed, and the runnable will be released.
In scenario 2: The foreground service creates Runnable and keep a reference to it. When you destroy activity or switch to another apps, the service is still alive (and runnable as well) until you kill service by calling (stopSelft() or stopService() method). Because when using a foreground service, it will tell the system that the app is doing something important and it shouldn’t be killed.
As I understand - both Runnable and Service are intended to run piece
of code in background.
To be more specific, Service runs on a main thread. It is your responsibility to put the work on a separate thread if you are planning to make a CPU-intensive work inside the service. You can do so by putting it inside a Runnable or a Thread.
Am I getting this right or no? The overall plan is to make sure that
Runnable survives in background at all costs.
Scenario B could work but my suggestion is to modify your BaseManager into a service class.
I have the following Kotlin code, executed from the UI thread of Android:
Runnable {
doSomeSuff() // Which thread will it run?
}.run()
On which thread will it run? The UI thread?
Your Runnable will be executed on the Thread it was created. In your case - UI thread. The question is - what do you want to achieve? There are bunch of built-in capabilities to perform background related work. I'll provide wider answer - if you explain your requirements.
From Android Documentation:
The Runnable interface should be implemented by any class whose
instances are intended to be executed by a thread. The class must
define a method of no arguments called run.
This interface is designed to provide a common protocol for objects
that wish to execute code while they are active. For example, Runnable
is implemented by class Thread. Being active simply means that a
thread has been started and has not yet been stopped.
Why it is different from Thread:
When an object implementing interface Runnable is used to create a
thread, starting the thread causes the object's run method to be
called in that separately executing thread.
I have a activity with a Listview and a adapter attached to it. I have a class which syncs data and hold it. (I think we should not care about from where data is coming) and it runs on a different thread. Now I want to know the clean way to update adapter but We should not call any function of activity from that class as it runs on different thread.
One way I know is to create handler in activity and pass it to other class and use it from there. But I want to know if activity is in background then activity's function can be called by UI thread or only when activity come in foreground.
I do not want to miss any update and want to update activity when it is in foreground.
If you want to update your listView from another class you can have a few ways to do that.
Send broadcastIntent from your worker class and add BroadcastReceiver to your activity and when you receive the right message, update your listview.
Second way is to create private or public class in your Activity which extends AsyncTask and in your doInBackground() do your work and in onPostExecute(result) update your listview.
Third way which I can imagine, but I don't think it's the best way create a static method is your activity which you can use from any other class for updatiogn your UI.
The best thing which you can use here at least in my opinion is AsyncTask.
this code will do what you want:
runOnUiThread(new Runnable() {
#Override
public void run() {
//your actions
}
});
We should not call any function of activity from that class as it runs on different thread.
That's wrong. (in java an object is not running in a thread. What you can say is that a method is running in the thread from which the method was called)
In Androïd (and in most UI frameworks) the rule is this:
You can only call a method updating UI from the UI thread.
If you have some code running on a thread (not the ui thread) and if that code need to update the UI : you can use the Handler of the UI-thread to post UI update code to the UI-thread. If the activity is not in the foreground when you post something to update it's UI : nevermind! the code you just post will be executed at some point in the future.
You should use AsyncTask, take a look at http://developer.android.com/reference/android/os/AsyncTask.html
In Android, I have a thread that initializes a global variable. The thread starts when the activity starts. If the activity finishes before the thread initialized the global variable will the thread still run in the background to complete its job or it will be killed as the activity finishes?
The Activity finishing is part of the main execution/UI thread in android. When you spawn a new thread, and perform operations on that thread, it works as a separate entity from the main UI thread.
Hence, to answer your question - The thread will still run in the background to complete its job.
However, a word of caution. If within the run() method, you are using some objects that are part of the activity class that just got terminated, you can run into null pointer exceptions.
I tried to look clear answer for it but wasn't able to find it anywhere. I am running background thread in main activity that checks for certain variable and if it is true it should show alert dialog. I also want this dialog to show up on any focused activity of the application. I tried it by adding Looper.prepare() and Looper.loop() to the thread but it does not work properly and it affects while() loop that I use to check variable in that thread. Can anyone please help me in finding out what is the best way to implement this?
Thanks.
If you construct the background thread using the main/ui thread, you can create a Handler in the constructor. When you want to run some code on the main/ui thread, you simply Handler.post(Runnable r) with a runnable to the ui thread.
If your background thread is not being constructed on the ui/main thread, you can use a BroadcastIntent to and a BroadcastReceiver pattern to send messages between your background thread and your foreground activities. This is especially useful if you are switching foreground activities during the useful life of your background thread.
You may want to try creating an implementation of Runnable and passing that to a View's post() method.
final Runnable r = new Runnable() {
public void run() {
//code to display dialog
}
}
final View view = findViewById(R.id.XYZ);
view.post(r);
This will run the Runnable on the UI thread.
Ok, i can see two approaches. The first one is a dirty but quick:
You can extend TimerTask and Handler classes. YourTimerTask will check variable and send a Message to YourHandler. YourHandler should override handleMessage and show a dialog.
The second one might be an overkill, but still. Android is event-based. It means that system gives you an opportunity to create your own events and handle it. So, you can start a Service, which will check your variable and send a Broadcast (can be local). In your activity you have to create your own BroadcastReceiver and register it. This receiver will handle a message.