How do I implement multi thread on an Android Activity? - android

I've created a nested class within my Activity
public class MissionsActivity extends Activity {
class UpdateMissions implements Runnable {
#Override
public void run() {
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
[...]
}
[...]
}
In the thread I have to read a file and update some TextFields in the layout. I've tried implementing the run() method with a while(true) that reads and updates the fields, but the app just crashes when I start that Activity.
UPDATE: I've called the execute() method inside the onCreate() method of the UI Activity. The Task is only working the first time I enter the Activity, if i change and go back it won't do anything.

Hey a solution could be trying to use Java's Executor Framework. Put the following code in your Activity.
With executors, you can use a cachedThreadPool() singleThreadExecutor() fixedThreadPoolExecutor(int numOfThreads) etc.
Executors.newSingleThreadExecutor().submit(new Runnable() {
#Override
public void run() {
//Your task here.
}
});
Please note there are numerous Threading Models and techniques in Android, some Android Specific, some based in Android.
AsyncTask
HandlerThread

You can use an AsyncTask. It allows you to load the file and show the progress on ui thread until the load it's finished.
Here you have a good example Download a file with Android, and showing the progress in a ProgressDialog
I would recommend using RxJava or Live Data if you are more advance in developing but also the first solution is fine enough for beginning
https://developer.android.com/topic/libraries/architecture/livedata.html

Related

Using Async task for calling user defined method

I am developing an app where I am loading images from gallery. I saw my GUI freezing a little bit and a message saying "Skipped 53 frames. Your app might be doing huge work in its main thread" something like that. Upon a little bit of research I found that it is a common issue and can be resolved using Async task etc. I have defined a method in my main activity and I am calling that method at the very beginning of my activity, that method must be doing a lot of work. I want to call that method in an Async task or on a parallel thread which will run parallel to my main thread and until it is finished I want to display a message box with the text "processing...." on my GUI. How can I achieve this. I am not passing any arguments to the method in my method call nor I am returning anything from that method.
you could use RxJava if you are using Java and Coroutines if you are using Kotlin they are the most optimal solutions at present. But if you still want to use an Async task here is the way.
create an inner class like this,
private class AsyncTaskExample extends AsyncTask<null, null, null> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//show progress bar or any
thing you want to do before starting the process
}
#Override
protected void doInBackground() {
//your code that gets the images from gallery
}
#Override
protected void onPostExecute() {
super.onPostExecute();
// use this callback for if you want to stop showing the progress bar or anything that you want to do after the executing your code in Backgroud
}
}
}
then call this by doing this whenever you want to execute your code,
AsyncTaskExample asyncTask=new AsyncTaskExample();
asyncTask.execute();

anyway to quit smoothly looper.loop inside a run()?

I want to execute some code on like each 10 seconds (example only), and for this purpose I am using TimerTask.The problem is that within the run() method of TimerTask class, I am implementing looper.prepare and looper.loop , due to some handlers involved.The looper.loop seems to not return after first execution and therefore my TimerTask starts executes once and that is it. I tried using looper.quit(), but that didnt help either.Is there any nice way of making it work?
A small example :
public class Timez extends TimerTask {
public void run () {
Looper.prepare();
// some code here
Looper.loop();
}
}
Thanks in advance.

How can i create a Thread that running on background on Android

I have a Thread with open socket connection in a activity, I like to use the thread globaly so that I can get data from thread in other Activities. Somethink like running on the background...
Does anyone have a solution or examples for me?
Thank u.
You are looking for Service
or try this code
void runInBackground() {
new Thread(new Runnable() {
#Override
public void run() {
// DO your work here
// get the data
if (activity_is_not_in_background) {
runOnUiThread(new Runnable() {
#Override
public void run() {
//uddate UI
}
});
}
runInBackground();
}
});
}
And the third method using Async Task-- Understanding AsyncTask
If you want multiple activities to have access to this thread then I would combine Vaibs_cool's sample of running a thread (it's just a normal Thread, nothing Android specific about it) and then...
extend Application (make an entry for it in the Manifest) and put that Thread in there.
That way all your activities can talk to it.
You have two options:
Service
AsyncTask
If you want to open socket and make it opened even after Activity close use Service
On other hand if you want to open socket during Activity is running and close on Activity close then use AsyncTask
You can find example how to use AsyncTask here
From Docs:
Network operations can involve unpredictable delays. To prevent this from causing a poor user experience, always perform network operations on a separate thread from the UI. The AsyncTask class provides one of the simplest ways to fire off a new task from the UI thread.

Organising threads in Android

My Android app needs to be constantly receiving via USB serial in the background of my app, while sending information via USB serial only happens on certain functions. When we send and receive I am always sending a packet of X bytes every time. I understand how Android USB API works, the thing that I am having trouble with is how would I organize this? Would I use a thread for receiving only and the rest as functions, or for the whole USB connection/sending and receiving all together is in a thread? The main activity is called "Homescreen.java" and here is how I have it organized so far.
public class HomeScreen extends Activity implements OnTouchListener, Runnable{
onCreate() { }
onResume() { }
onStart() { }
onDestroy() { }
run() { }
}
Note: The reason there is no onPause is because this app is a fullscreen widget and should never be closed.
Another question: If I was to make a thread would I have to make it extend from Homescreen.java? And what of Context? Can I just import it? (Not very keen on Context object)
this is more of design choice, for instance if you want one background thread to handle the data from USB
public class test extends Activity{
Thread t;
runT= true;
public void onCreate(Bundle b)
{
..........
..........
t = new Thread(new Runnable() {
#Override
public void run()
{
while(runT)
{
//call data read or send functions here you can add condtion to sleep the thread as well
}
}
});
t.start();
}
}
When you are ending the activity simply set runT to false, which will stop the thread.
You can also have a thread pool and use theads accordingly.
If this is not happening frequently you can start an Asynctask everytime you want to send data.
You can look at AsyncTask. It is a special thread implementation for Android that should keep things simpler. If you are not doing any threaded "heavy lifting" I would recommend going with AsyncTask. You simply write an inner class inside your HomeScreen class, write your logic and call it from your Activity (for example from within onCreate()).
You could try getBaseContext() from within the Activity - I guess this will get you the relevant Context.
Cheers

Android - Starting a thread crashes app

I've got a few activities. In the main activity I have a login screen, when the user presses the login button, a thread is started to show a progress dialog until the user has been authenticated. At this point i load the next activity which has several fields for the user to input data.
Here the user inputs some data and presses a button to process it. The data is passed to a new activity where the data is actually processed and displayed. This is where i create the new thread and where it's crashing when i call thread.start(); and I have no idea why this is happening.
Both activities are implementing Runnable.
I'm using the same code below to create and call thread.start() in the button press of the first activity and the onCreate method of the last one:
pd = ProgressDialog.show(search_results.this, "", "Searching...", true, false);
Thread thread = new Thread(this);
thread.start();
I'm using the same code below as well to handle the threads for both as well.
public void run() {
handler.sendEmptyMessage(0);
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
pd.dismiss();
}
};
Am I missing something? I don't really understand why it's crashing.
While I encourage people to use AsyncTask, it's not really needed, especially for simple things like progress/loading dialogs. That's not the problem here.
Your question and your code is confusing. I'm not sure which code goes where, on which activity, and I hope you're not leaving dialogs open between activities, trying to access them across them (it won't work, of course). Also, providing a Context to a Thread does not even compile (it's marked with errors at design time). To sum it all up, you didn't provide the Log entry. Sorry, I can't make sense of what you're doing or where the error is. We can only guess.
Below are one of the possible ways to do it with a Handler, a Runnable and a Thread. This was taken from the Developer Resource when I first learn how to use it:
1- You declare a Handler. Most people do this on the onCreate section to reuse it often:
Handler mHandler = new Handler();
2- When you need, you start a Thread:
new Thread() { public void run() {
mHandler.post(mLoadingData);
// ... do work
mHandler.post(mLoadingDataStop);
}}.start()
3- These are the Runnables that are posted to the Handler:
private final Runnable mLoadingData = new Runnable() {public void run() {
showDialog(LOADING_DIALOG); // In your case, show your custom dialog
}};
private final Runnable mLoadingDataStop = new Runnable() {public void run() {
dismissDialog(LOADING_DIALOG); // In your case, dismiss the dialog
}};
For a progress dialog, things need a bit more work (update the progress etc.), but for a loading dialog, you don't need to really mess with messages.
I had this same issue when developing for the tablet. After a certain API, I'm thinking 3.0 (sdk 11), Android enforces applications to run long running processes on a separate thread, otherwise it kills it. Logcat will confirm this.
I know you are using another thread, but that didn't work for me either. Try using AsyncTask. You can create a quick inner class that, in my opinion, is way easier than handling your own threads. AsyncTask has several functions that run on the UI thread and a couple that run on their own thread. This allows you to start a "Loading" user interface object on the user interface thread, process on the back end thread, and then when its done, it'll notify a user interface thread function.
You'll want to specifically look at override
onPreExecute()
doInBackground()
onPostExecute()

Categories

Resources