running a method continously using the thread - android

I have a method which contains volley network library which will send some data to php server and fetch based on the value sent. I want to run this method continuously. I have created a Thread in the Oncreate method like below.
new Thread(){
#Override
public void run(){
second.this.runOnUiThread(new Runnable(){
#Override
public void run(){
try {
getNumber(second.this.getContentResolver());
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}.start();
But i am not sure whether it is working. how can i check it is working or any mistake is there on implementation?

Related

how to start first thread complete to after second thread start

Am using some method i need to some method complete to start to another method so that am using thread function, How to start one thread follow by to second thread start?
Thread thread1 = new Thread(new Runnable() {
#Override
public void run() {
try {
loadIrrigationSourceMaster();
loadIrrigationMaster();
loadSeasonMaster();
loadFactoryMaseter();
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread1.start();
Thread thread2 = new Thread(new Runnable() {
#Override
public void run() {
try {
loadTransport();
plantTypeMaster();
plotOwnerTypeMaster();
ExitRatoonMaster();
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread2.start();
(new Thread(new Runnable() {
#Override
public void run() {
//TODO: fist thread code here
Log.w("tag","1");
(new Thread(new Runnable() {
#Override
public void run() {
//TODO: second thread code here
Log.w("tag","2");
}
})).start();
}
})).start();
out put of above:
tag:1
tag:2
but i dont think it's a good idea . just put rest of your job in first Thread
To wait for a thread to complete its execution before moving on, you can use the join() method: docs
Specifically for your problem, you can put thread1.join(), right after the thread1.start() call. The join call will block the calling thread until thread1 is finished with its execution, so that thread2 will be initialized and executed after thread1 is finished.
Alternatively, you can also call thread1.join() in the beginning of the run() method of thread2, so that the main thread won't need to be blocked by the join() call.

how to force the AsyncTask to wait

i want the AsyncTask to wait till it finishes. so i wrote the below code and i used .get() method as follows and as shown below in the code
mATDisableBT = new ATDisableBT();
but at run time the .get() doesnt force ATDisableBT to wait, becuase in the logcat i receive mixed order of messages issued from ATDisableBT and ATEnableBT
which means .get() on ATDisableBT did not force it to wait
how to force the AsyncTask to wait
code:
//preparatory step 1
if (this.mBTAdapter.isEnabled()) {
mATDisableBT = new ATDisableBT();
try {
mATDisableBT.execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
//enable BT.
this.mATEnableBT = new ATEnableBT();
this.mATEnableBT.execute();
You can do this way:
doInBackground of AsyncTask
#Override
protected Void doInBackground(String... params) {
Log.i("doInBackground", "1");
synchronized (this) {
try {
mAsyncTask.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Log.i("doInBackground", "2");
return null;
}
Outside this function from where you have to nstrong textotify AsyncTask to release from wait state:
new CountDownTimer(2000, 2000) {
#Override
public void onTick(long l) {
}
#Override
public void onFinish() {
synchronized (mAsyncTask) {
mAsyncTask.notify();
}
}
}.start();
Here I have notified AsyncTask by CountDownTimer after 2 seconds.
Hope this will help you.
You should execute AsyncTask on UI thread, so using get() - which will block it makes no sense - it might get you ANR error.
If you are on HONEYCOMB and up, then AsyncTasks are executed on single executor thread, serially - so your mATEnableBT should get executed after mATDisableBT. For more see here:
http://developer.android.com/reference/android/os/AsyncTask.html#execute(Params...)
You might also switch from AsyncTask to Executors. AsyncTask is implemented using executors. By creating single threaded executor you make sure tasks will get executed serially:
ExecutorService executor = Executors.newSingleThreadExecutor();
//...
executor.submit(new Runnable() {
#Override
public void run() {
// your mATDisableBT code
}
});
executor.submit(new Runnable() {
#Override
public void run() {
// your mATEnableBT code
}
});

Send a toast from a thread within a service

I'm trying to send a toast notification of an error in a thread. The thread is started in a service that is called from the main thread. I've tried several things with View.post and some weird handler stuff, but nothing seems to work. An excerpt of the thread is as follows:
public int onStartCommand(Intent intent, int flags, int startId)
{
new Thread(new Runnable(){
public void run() {
boolean bol = true;
while (bol)
{
try
{
//Some socket code...
}
catch (Exception e)
{
//Where I want the toast code.
}
}
}
}).start();
return START_STICKY;
}
Try following inside the thread in the service:
Handler h = new Handler(context.getMainLooper());
// Although you need to pass an appropriate context
h.post(new Runnable() {
#Override
public void run() {
Toast.makeText(context,message,Toast.LENGTH_LONG).show();
}
});
Taken from answer given by #Alex Gitelman here on Android: How can i show a toast from a thread running in a remote service? . This might help somebody as it helped me.
Toast can be shown only from UI Thread (Main Thread). To show Toast from some other threads you have to use Handler.
Threads, Handlers and AsyncTask
Yes you should use a Handler, and bind you Activity to your Service
Once the Handler is set, here is what you should do,
Message msg = Message.obtain(null, MyActivity.TOAST);
Bundle bundle = new Bundle();
bundle.putString(MyActivity.TOAST_MSG, "Toast message");
msg.setData(bundle);
try {
myActivityMessenger.send(msg);
} catch (RemoteException e) {
if (D) Log.w(TAG, "Unable to send() the toast message back to the UI.");
e.printStackTrace();
}
myActivityMessenger is set with the Handler of your MyActivity and sent to the Service when you bind MyActivity to it.
However displaying a Toast with a Service as context should work (but it's not the best way), so maybe it's because you try to make it from a new Thread. What is your code for making the Toast ?
new Thread(){
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
_dialog.dismiss();
Toast.makeText(LatestNewsActivity.this, "NO Internet Connection Available", Toast.LENGTH_LONG).show();
}
});
}
}.start();

While Loop inside Thread not working?

I have a very simple UI and i need to constantly run a check process, so I am trying to use a Thread with a while loop.
When I run the loop with nothing but a Thread.sleep(1000) command, it works fine, but as soon as I put in a display.setText(), the program runs for a second on the emulator then quits. I cannot even see the error message since it exits so fast.
I then took the display.setText() command outside the thread and just put it directly inside onCreate, and it works fine (so there is no problem with the actual command).
here is my code, and help will be greatly appreciated.
Thank you!
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
on=(Button) findViewById(R.id.bon);
off=(Button) findViewById(R.id.boff);
display=(TextView) findViewById(R.id.tvdisplay);
display2=(TextView) findViewById(R.id.tvdisplay2);
display3=(TextView) findViewById(R.id.tvdisplay3);
stopper=(Button) findViewById(R.id.stops);
stopper.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(boo=true)
{
boo=false;
display3.setText("System Off");
}
else{
boo=true;
}
}
});
Thread x = new Thread() {
public void run() {
while (boo) {
display3.setText("System On");
try {
// do something here
//display3.setText("System On");
Log.d(TAG, "local Thread sleeping");
Thread.sleep(1000);
} catch (InterruptedException e) {
Log.e(TAG, "local Thread error", e);
}
}
}
};
display3.setText("System On");
display3.setText("System On");
x.start();
}
You can't update the UI from a non-UI thread. Use a Handler. Something like this could work:
// inside onCreate:
final Handler handler = new Handler();
final Runnable updater = new Runnable() {
public void run() {
display3.setText("System On");
}
};
Thread x = new Thread() {
public void run() {
while (boo) {
handler.invokeLater(updater);
try {
// do something here
//display3.setText("System On");
Log.d(TAG, "local Thread sleeping");
Thread.sleep(1000);
} catch (InterruptedException e) {
Log.e(TAG, "local Thread error", e);
}
}
}
};
You could also avoid a Handler for this simple case and just use
while (boo) {
runOnUiThread(updater);
// ...
Alternatively, you could use an AsyncTask instead of your own Thread class and override the onProgressUpdate method.
Not 100% certain, but I think it is a case of not being able to modify UI controls from a thread that did not create them?
When you are not in your UI thread, instead of display3.setText("test") use:
display3.post(new Runnable() {
public void run() {
display3.setText("test");
{
});
You should encapsulate this code in an AsyncTask instead. Like so:
private class MyTask extends AsyncTask<Void, Void, Void> {
private Activity activity;
MyTask(Activity activity){
this.activity = activity;
}
protected Long doInBackground() {
while (true){
activity.runOnUiThread(new Runnable(){
public void run(){
display3.setText("System On");
}
});
try{
Thread.sleep(1000);
}catch (InterruptedException e) {
Log.e(TAG, "local Thread error", e);
}
}
}
Then just launch the task from your onCreate method.
In non-UI thread,you can't update UI.In new Thread,you can use some methods to notice to update UI.
use Handler
use AsyncTask
use LocalBroadcast
if the process is the observer pattern,can use RxJava

how to stop infinite loop threads from android service?

i am working with threads in sample application.In my application i have used 3 threads are running in infinite loop.These 3 threads are used in android service class.when i am starting these threads then the threads are running and UI is not allowing until completion of infinite loop.but how can i stop the threads and how can i handle UI?
i have written a service class as follows:
ServiceApp.java
public class ServiceApp extends Service
{
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
while(true)
{
Thread child1=new Thread(new Runnable() {
#Override
public void run() {
try {
function1();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
child1.start();
Thread child2=new Thread(new Runnable() {
#Override
public void run() {
try {
function2();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
});
child2.start();
Thread child3=new Thread(new Runnable() {
#Override
public void run() {
try {
function3();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
child3.start();
Toast.makeText(ServiceApp.this, "All threads started", Toast.LENGTH_SHORT).show();
}
}
public void function1() throws InterruptedException
{
Generic generic=new Generic(); //this for connect to web services
String add=generic.getAdd(10,20);
Log.v("function1", "addition from service"+add);
Thread.sleep(1000);
}
public void function2() throws InterruptedException
{
Generic generic=new Generic(); //this for connect to web services
String sub=generic.getSub(34,20);
Log.v("function2", "subtraction from service"+sub);
Thread.sleep(1000);
}
public void function3() throws InterruptedException
{
Generic generic=new Generic(); //this for connect to web services
String mul=generic.getMul(4, 6);
Log.v("function3", "multipicationn from service"+mul);
Thread.sleep(1000);
}
}
how can i stop child1,child2,child3 threads from activity class?
please any body help me?
Service.onCreate() is executed inside the UI thread. You have an infinite loop there, that continuously creates more and more threads, so UI doesn't get a chance to respond to user's actions. If you actually intend to have so many threads, you need to create another thread that would start the original three.
Activity can communicate with the service either via Binder (you'll need to return an actual implementation instead of null there) or by sending intents, which you can capture and process in Service.onStart()

Categories

Resources