I have Activity class, Controller class (normal java class use to control number of activity) and BusinessEngine class (normal java class use to process data).
When I need to do some calculation from activity, Activity will call Controller and Controller will call BusinessEngine to do the calculation. When BusinessEngine done with the calculation, it will pass the value back to Controller and finally let the activity know the calculation is complete.
The problem is how I callback Activity from Controller class? Or pass any data to Activity and notify it the data has been change?
Any "long" running tasks must be performed in a background thread. I'm not sure if your currently doing this for your task, so just in case your not, there are a couple of ways to do this. The first is to simply use a AsyncTask, the second is to create your own instance of AbstractExecutorService (AsyncTask uses ThreadPoolExecutor) and use that to post Runnable or Callables to. The later way may save you a lot of re factoring depending on your code base.
Assuming you're now running the task in a background thread, it's necessary to perform your UI updates on the UI thread. There are again a couple of ways to do this. One method is to post a runnable to the method Activity#runOnUiThread, the second is to use a Handler which has previously been created on the UI thread (which Activity#runOnUiThread does behind the scenes).
So, assume your Activity has a method #postResults(final Object o), and your controller has the method #doSomething(final Activity activity).
Your activity would look something like this.
public class MyActivity extends Activity {
Controller controller = ....
ExecutorService service = Executors.newFixedThreadPool(10);
private void startTask() {
Runnable r = new Runnable() {
public void run() {
c.doSomething(MyActivity.this);
}
}
service.submit(r);
}
public void postResults(final Object o) {
Runnable r = new Runnable() {
public void run() {
// Update your UI here
}
}
runOnUiThread(r)
}
}
and your controller
public class Controller {
public void doSomething(final Activity activity) {
// Perform some long running task here
activity.postResults(someObject);
}
}
Obviously this example could be tidied up (for example passing a interface to doSomething rather than the Activity), but hopefully it should be enough to understand what you need to do :)
Why are you looking for the controller to call you Activity? Normally, your Activity must call the controller via its methods and directly get results from them:
// Code in your Activity
result = controller.doSomething(args);
try using a android AsyncTask, if your method takes a long time to process. example
Add your classes to an Async task or if you're calling the classes and passing them from one class to the other.I would say to use static class. And provide some code so we can know how you are passing your data.
If not use general methods to call the superclass or the subclass.
My answer is a bit abstract as information is less.
Related
I have an activity which contains a ViewPager inside it.The ViewPager's Adapter is FragmentStatePagerAdapter. Each page is Fragment.The Fragment contains a number of Threads. My problem is, I have to stop all the threads inside the fragment when ViewPager's page is changed.How can I do this ?
you have asked about communication between activity and fragment that you achieve using interface:
Your Fragment:
public class YourFragment
extends Fragment{
private OnListener listener;
public interface OnListener
{
void onChange();
}
void initialize( OnListener listener)
{
this.listener = listener;
}
//onview pager change call your interface method that will go to the activity as it has the listener for interface.
listener.onChange();
}
Your Activity:
public class yourActivity
extends Activity
implements yourFragment.OnListener
{
// intialize the method of fragment to set listener for interface where you define fragment.
yourFragment.initialize( this );
// implement what you want to do in interface method.
#Override
public void onChange()
{
// implement what you want to do
}
}
hope it will help.
Android's philosophy with applications is to kill processes, so maybe following the same idea you could kill your Threads. Be aware though that this can lead to deadlocks if your Threads own locks, or monitors.
A more serious approach to me seems to use Thread.interrupt() from your Activity. Then your Threads in your Fragment have to check Thread.interrupted for interruption, and finish gracefully if they've been interrupted.
You can use Thread.join() if you want some synchronous behavior
In addition, you can wait for a certain amount of time for your Thread to finish gracefully using a Timer, then kill them on timeout.
Please have a look at java.lang.Thread
To let this be more easy to implement, you could use a ThreadPoolExecutor or some other helper of java.util.concurrent package.
I've seen a few questions on here asking similar questions, but I've not yet seen a suitable answer. Many people have asked how to update the UI from a thread, but they're almost always in the same class as the UI.
What I'm trying to do is update the UI from a thread which has been created in another class. I've seen all of the suggestions, such as async, handlers, runnable, etc... but I've having real trouble implementing them in separate classes.
I'm trying to keep my UI class minimal and only deal with interactions with the GUI, such as when a user presses a button. Now, I've created a new thread, in a new class, which connects to a Bluetooth device, but I then want to change a button in the UI thread from being a 'connect' button to a 'disconnect' button (i.e. change the button from creating the Bluetooth socket to closing it).
What is the general way to do this? Am I thinking of this all wrong and should have everything in one class? What is the correct way to interact between the 'main' UI class and other classes/threads?
Ideally I want to be able to do other UI interactions, so some solution which allows other UI changes outside of the UI class would be great!
What I'm trying to do is update the UI from a thread which has been
created in another class. I've seen all of the suggestions, such as
async, handlers, runnable, etc... but I've having real trouble
implementing them in separate classes.
Generally for your goal i recommend to you use:
AsyncTask
IntentService with ResultReceiver
I don't think that its too tricky. Absolutely not. If you have it as separated class(es) and not as inner class(es) in some Activity class so i recommend to use constructor where you will pass context, widgets, generally whatever you want and then in correct methods(which allows UI update) update your UI.
I'm doing it because i like when i have clean classes(so UI class have only UI implementations and logic is positioned separately).
Example:
public class TaskExample extends AsyncTask<Void, Integer, Void> {
private Context c;
private Button b;
public TaskExample(Context c, Button b) {
this.c = c;
this.b = b;
}
protected Void doInBackground(Void... params) {
// some work
if (isSomethingConnected) {
publishProgress(Constants.IS_CONNECTED);
}
return null;
}
public void onProgressUpdate(Integer... params) {
switch (params[0]) {
case Constants.IS_CONNECTED:
b.setText("Connected");
break;
case Constants.ANOTHER_CONSTANT:
// another work
break;
}
}
}
Usage:
public class Main extends Activity implements View.OnClickListener {
private Button b;
public void onCreate(Bundle b) {
super.onCreate(b);
// initialise widgets and set listeners to appropriate widgets
}
public void onClick(View v) {
switch(v.getId()) {
case R.id.connectBtn:
startWorker();
break;
}
}
private void startWorker() {
TaskExample te = new TaskExample(this, b);
te.execute();
}
}
There are a couple of options. If you have access to the View you are changing and simply need to force a refresh, you can use View.postInvalidate() from any thread. If you need more complex operations, such as changing the text of a button, you should use runOnUIThread, which requires access to the Activity context. This should be simple to get - just add it as a parameter for your custom Object's constructor. With this context, you can do something like this:
activityContext.runOnUiThread(new Runnable(){
#Override
public void run() {
myButton.setText("disconnect");
}
});
Use the runOnUiThread(Runnable) method to run something on the Main thread and call the ClassName.View.invalidate() method if it is a view or just make a public method in you're Target class which handles the refreshing of the UI.
Hello i am new to android and android thread so want to know that
How could we use more number of thread in order to perform every single task or method so that while user click on any UI component it does effect the performance ,having little knowledge of how the handler thread and asynctask work.But how can we run every method inside the asynctask so to do the operation and mean while user can do the other operation also.
In the application
i have voice recording from mic.
next showing progress bar.
next showing gallery with some image and with that setting effect to the picture.
The recommended way is to use AsyncTasks for long running tasks. So, not everything needs to be run with AsyncTasks, as you can get a performance hit due to the context switching.
As for how AsyncTasks work, read the documentation.
Use an AsyncTask and make sure to implement these as needed. You mention the idea of doing something in the background while a user is doing something so I'm guessing you'll want to alter the UI.
Take a look at these links for an more details from Android. They cover Runnable, AsyncTask and Handler
Overview of them all http://developer.android.com/guide/components/processes-and-threads.html
AsyncTask example http://developer.android.com/reference/android/os/AsyncTask.html
Old but relevant, Painless Threading http://android-developers.blogspot.com/2009/05/painless-threading.html
Another, more complex example http://developer.android.com/training/displaying-bitmaps/process-bitmap.html
I don't generally paste full examples in here but I had a lot of trouble finding an example I was happy with for a long time and to help you and others, here is my preferred method. I generally use an AsyncTask with a callback to the Activity that started the task.
In this example, I'm pretending that a user has triggered onClick(...) such as with a button, but could be anything that triggers a call into the Activity.
// Within your Activity, call a custom AsyncTask such as MyTask
public class MyActivity extends Activity implements View.OnClickListener, MyTask.OnTaskComplete {
//...
public void onClick(View v) {
// For example, thet user clicked a button
// get data via your task
// using `this` will tell the MyTask object to use this Activty
// for the listener
MyTask task = new MyTask(this);
task.execute(); // data returned in callback below
}
public void onTaskComplete(MyObject obj) {
// After the AsyncTask completes, it calls this callback.
// use your data here
mTextBox.setText(obj.getName);
}
}
Getting the data out of a task can be done many ways, but I prefer an interface such as OnTaskComplete that is implemented above and triggered below.
The main idea here is that I often want to keep away from inner classes as they become more complex. Mostly a personal preference, but it allows me to separate reusable tasks outside of one class.
public class MyTask extends AsyncTask<Void, Void, MyObject> {
public static interface OnTaskComplete {
public abstract void onTaskComplete(MyObject obj);
}
static final String TAG = "MyTask";
private OnTaskComplete mListener;
public MyTask(OnTaskComplete listener) {
Log.d(TAG, "new MyTask");
if (listener == null)
throw new NullPointerException("Listener may not be null");
this.mListener = listener;
}
#Override
protected MyObject doInBackground(Void... unused) {
Log.d(TAG, "doInBackground");
// do background tasks
MyObbject obj = new MyObject();
// Do long running tasks here to not block the UI
obj.populateData();
return
}
#Override
protected void onPostExecute(MyObject obj) {
Log.d(TAG, "onPostExecute");
this.mListener.onTaskComplete(obj);
}
}
I have a class in my Android app, called Main.java, to validate a user login (user name + password) against the data in my server. At first, I succeeded; I used an AsyncTask thread to do it plus a library which handles the Http connection, call HttpPostAux.java (in fact, I found the library's code here in this forum). In the onPostExecute method of AsyncTask, I was creating and starting a new activity instead of modifying the current one and it worked.
But now I want to do things different. I want to save the validated data (user name + password) into a SQLite table in the AsyncTask thread and then in the UI thread, recover that data and use it to open the mentioned activity. The insertion occurs but when I'm trying to access the database from UI thread: it says that the table is empty. So I looked in the logcat and I found that UI thread executes before AsyncTask thread.
So my question is how to insert data in the AsyncTask thread and then recover it inside UI thread? Can anybody help here? I'm kind of lost!
I will appreciate a code example! Thanks in advance!
Greetings from Venezuela!
UI thread is your applications main thread. When you create an AsyncTask, your long time-taking task will be executed(inside doInBackground function) on a separate thread. When doInBackground completes, onPostExecute() will be called from the UI thread. So you simply need to execute your UI thread task(="recover that data and use it to open the mentioned activity") from inside onPostExecute().
I think the way you did it before is correct. I would recommend to make a sort of SplashScreen activity which checks if the user has been logged in before, i.e. if there is a username/password in the database. If this is the case, use this data to login the user and then proceed to your main activity. If the user hasn't been logged in before, promp them with a login screen, store this data for future use and continue to your main activity.
You can implement a BroadcastReciever in your UIThread that listens to Intents sent from your AsyncTask when the insert to the database is done.
fire from AsyncTask:
Intent intent = new Intent("DATABASE_INSERTION_DONE");
context.sendBroadcast(intent );
register in UiThread:
IntentFilter intentFilter = new IntentFilter("DATABASE_INSERTION_DONE");
registerReceiver(myIntentsReceiver, intentFilter);
class:
class MyIntentReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if ("DATABASE_INSERTION_DONE".equals(intent.getAction())) {
//do something
}
}
}
You have to keep in mind that once you start an AsyncTask, it will run on another thread and your UI thread will keep moving forward. For example:
x="foo";
new SampleAsyncTask().execute();
txtView.setText(x);
Class SampleAsyncTask extends AsyncTask<...>{
.....
public Void doInBackground(...){
//LOTS OF CALCULATIONS
x="bar";
}
}
Your txtView will most definitely show "foo" rather than "bar". To make sure that your AsyncTask is finished there are lots of options. You can call a method to start the rest of your operations in PostExecute of your AsyncTask. You can also use intents and a broadcastreceiver like Jelgh said. But my favorite is using a simple callback:
public class LoginActivity extends Activity implement SampleAsyncTask.asyncCallback{
#Override
protected void onCreate(Bundle savedInstanceState){
x="foo";
new SampleAsyncTask().execute();
Class SampleAsyncTask extends AsyncTask<...>{
asyncCallback mCallback;
public SampleAsyncTask(Context c){
mCallback; = (asyncCallback) c
}
public interface asyncCallback{
void servedMyPurposeYouCanGoOn();
}
public Void doInBackground(...){
//LOTS OF CALCULATIONS
x="bar";
mCallback.servedMyPurposeYouCanGoOn;
//REST OF THE WORK
}
}
}
#Override
public void servedMyPurposeYouCanGoOn(){
runOnUIThread(
//rest of the work
)
}
}
I would like to achieve the following behaviour, but I'm not sure how:
User start an activity
Activity starts an AsyncTask
User performs some action that creates a new activity
The AsyncTask finishes and somehow returns the result to the new activity
Is there a way of achieving this behaviour?
Thank you
Create a Service that itself spawns its own thread and does your background processing. You can bind your activities to the service so you can call back into an activity when your processing is complete.
I've been using a variation of what was suggested by Chris:
Start by creating an IntentService, which is the easiest kind of Service to create. Then use SharedPreferences to indicate the state of your IntentService and share values between your Service and Activities. Your Activity can register itself as an OnSharedPreferenceChangeListener in order to know when your Service is done doing work and/or another SharedPreference it cares about has changed.
With IntentService, all you need to do is override the onHandleIntent method. Everything inside onHandleIntent will run on a background thread.
This is a way to do exactly what you want, assuming that the result is an int. You can extend this property, using a parcelable object. Probably, using a Service is still the best choice.
1) Create a class, called Result, that is a wrapper for your result. It must implement the Parcelable interface:
public class Result implements Parcelable {
private int result;
public Result(int i) {
super();
result = i;
}
public void setResult(int result) {
this.result = result;
}
public int getResult() {
return result;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(result);
}
public static final Parcelable.Creator<Result> CREATOR = new Parcelable.Creator<Result>() {
public Result createFromParcel(Parcel in) {
return new Result(in);
}
public Result[] newArray(int size) {
return new Result[size];
}
};
public Result(Parcel in) {
result = in.readInt();
}
}
2) Now, you can use a Result object as a private variable of the first activity:
public class FirstActivity extends Activity {
private Result result;
....
}
3) In your firstActivity, you can start an AsyncTask with a line like this:
new MyAsyncTask(result).execute();
4) Your AsyncTask can be made in this way:
class MyAsyncTask extends AsyncTask<Void, Void, Void> { // you can modify types as you want
Result result;
public MyAsyncTask(Result result) {
this.result = result;
}
....
public mySetResult() {
result.setResult(...); //set your value
}
....
}
5) When you start the second Activity, you can pass your result object to the second activity:
Intent i = new Intent(getApplicationContext(), SecondActivity.class);
i.putExtra("parc", result);
startActivity(i);
6) Finally, from the second activity, you can obtain the result using this code:
Result res = (Result) getIntent().getParcelableExtra("parc");
For more details about parcelable object, can see Android Developer
A Service is a component that allows some code to have a separate lifetime outside of activities without interacting with the user. As others have mentioned, that's certainly one option to consider. If you go with that, IntentService is the easiest way to make the work asynchronous.
However, you could continue to use AsyncTask and just add some code to signal that it's "complete". This is the case when the background work no longer matters if your application is killed, and you're OK with your app being killed before this work completes if the user leaves the application. Another way to see this is if the result of the AsyncTask only matters to either/both of these two activities and not outside. This is an important difference in requirements from needing a Service which again, provides a lifetime outside of activities.
To pass the data, take a look at this doc. There are a lot of ways you could tackle this, but for this kind of thing I prefer a pseudo-singleton approach. (I don't like to use SharedPreferences to pass data, because frankly I don't think that's what the class is for. I prefer this pseudo-singleton approach over a pure singleton because it's more testable. Android uses the singleton approach all over the place though.) I'd create a reference to some sort of AsyncTask registrar class in the Application object. As the Application object is accessible from both activities, the first one can register your AsyncTask with the registrar and the second one can get that AsyncTask and register to listen for completion if it hasn't already finished.