I have a background class named "TCP client" that sets a boolean to true whenever a state change is detected in hardware. And runOnUIThread in main activity detects this and updates UI which are switch buttons, in order not to trigger the OncheckedChangeListener I set the listener to null, change state, then set the listener to its original one. But during runtime OncheckedChangeListener is still triggering. I guess this is a synchronization problem.
mainActivity.java
public class MainActivity extends AppCompatActivity {
public SwitchButton.OnCheckedChangeListener switchListener;
public com.suke.widget.SwitchButton switch;
public static boolean switchflag=false;
int i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.activity_main);
switch = findViewById(R.id.lightSwitch);
runThread();
switchListener = new SwitchButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(SwitchButton view, boolean bChecked) {
if (bChecked) {
Log.d("button", "light is on");
connection.tcpClient.sendMessage("li1_1");
} else {
Log.d("Button", "light is off");
connection.tcpClient.sendMessage("li1_0");
}
}
};
switch.setOnCheckedChangeListener(switchListener);
}
private void runThread() {
i = 0;
new Thread() {
public void run() {
while (i++ < 1000) {
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
if(connection.tcpClient.getStatusFlag()) {
Log.d("main", "got Status");
updateUI();
connection.tcpClient.setStatusFlag(false);
}
}
});
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
public void updateUI() {
try {
switch.setOnCheckedChangeListener(null);
switch.setChecked(switchFlag);
switch.setOnCheckedChangeListener(switchListener);
}catch (NullPointerException e) {e.printStackTrace();}
}
I am not getting where to use the synchronized.
Put
runThread();
below
switch.setOnCheckedChangeListener(switchListener);
Also Replace
switch.setChecked(lightFlag);
With
switch.setChecked(switchFlag);
Related
I am working on a game project. I want to associate each view of my game to its respective thread and then update the view according to the logic running in that thread.
To simplify, I am posting a sample:
This is Main Activity class, which will implement the UI:
public class Main extends Activity{
private View root;
private boolean ready = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
}
private void init() {
setContentView(R.layout.s_main);
root = findViewById(R.id.root);
ViewTreeObserver vto = root.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
#Override
public boolean onPreDraw() {
root.getViewTreeObserver().removeOnPreDrawListener(this);
ready = true;
return true;
}
});
}
public void start(View view) {
try {
if (ready && !Threads.run) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
new AsyncTasks(this, R.id.txv1).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
new AsyncTasks(this, R.id.txv2).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
new AsyncTasks(this, R.id.txv1).execute();
new AsyncTasks(this, R.id.txv2).execute();
}
} else {
Threads.run = false;
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
This is AsyncTask extended class to update View:
public class AsyncTasks extends AsyncTask<Void, Void, String> {
private TextView view;
private boolean breakMove;
private String updateError;
public AsyncTasks(Activity activity, int viewId) {
breakMove = false;
updateError = null;
view = activity.findViewById(viewId);
}
#Override
protected String doInBackground(Void... voids) {
String message;
Threads.run = true;
try {
while (!breakMove) {
publishProgress();
Thread.sleep(100);
}
message = updateError != null ? updateError : "Thread Ends";
} catch (Exception ex) {
ex.printStackTrace();
message = ex.getMessage();
}
return message;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
try {
breakMove = !Threads.run;
if (view != null)
view.setText(String.valueOf(Math.random() * 100));
} catch (Exception ex) {
breakMove = true;
ex.printStackTrace();
updateError = ex.getMessage();
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Threads.run = false;
}
}
This works good. But there are limitations:
AsyncTask is recommended for short duration threads, not for Game or Long Running Thread projects.
In latest android frameworks, only 5 AsyncTask threads can run simultaneously and rest will be in waiting queue. So it will not work if my project requires more than 5 views to update simultaneously.
What I have tried:
Rest of other Thread implementations like Runnable, Handler, Service etc. don't allow to update views. Please keep in mind that my threads are coded in separate external files or classes.
runOnUiThread is not recommended since it runs on UI thread so it will make Main thread busy all time and also it's output is noticeable after the thread which called it, ends.
I am looking for a simple clean solution like I have coded above to implement Updation of Multiple Views through Multiple Threads.
Thanks in advance
I found a solution. Simple and clean:
public class Main extends Activity{
private View root;
private Runs runs;
private boolean ready = false;
private final Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
}
private void init() {
setContentView(R.layout.s_main);
runs = new Runs(this);
root = findViewById(R.id.root);
//
ViewTreeObserver vto = root.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
#Override
public boolean onPreDraw() {
root.getViewTreeObserver().removeOnPreDrawListener(this);
ready = true;
return true;
}
});
}
private void startRuns() {
try {
runs.run();
Threads.run = true;
} catch (Exception ex) {
Alerts.alert(context, ex.getMessage());
}
}
public void start(View view) {
try {
if (ready && !Threads.run) {
startRuns();
} else {
Threads.pause = !Threads.pause;
}
} catch (Exception ex) {
ex.printStackTrace();
Alerts.alert(context, ex.getMessage());
}
}
}
public class Runs implements Runnable {
private int count;
private Handler handler;
private TextView view1, view2;
public Runs(Activity activity) {
count = 0;
handler = new Handler();
view1 = activity.findViewById(R.id.txv1);
view2 = activity.findViewById(R.id.txv2);
}
#Override
public void run() {
if (!Threads.pause) {
update();
}
handler.postDelayed(this, Threads.sleep);
}
private void update() {
view1.setText(String.valueOf(count++));
view2.setText(String.valueOf(Math.random() * 100));
}
}
I have implemented one counter and onFinish() of first counter,I started second counter but the first counter not able to finish.Text "Bye Guyz" remain for some time so how to finish the text.
Please help me.
Thanks in advance.!!!
Code :-
counter= new CountDownTimer(10000, 1000) {
public void onTick(long millisUntilFinished) {
if (count == 0) {
tv.setText("First counter");
tv2.setVisibility(View.VISIBLE);
tv2.setText("Hello Guyz");
}
}
public void onFinish() {
if(!flag) {
tv2.setText("Bye Guyz");
count = 0;
try {
counter.cancel();
}catch (Exception e){}
}
else if(flag) {
counter1 = new CountDownTimer(9000, 1000) {
public void onTick(long millisUntilFinished) {
flag = false;
tv.setText("Second counter");
tv2.setVisibility(View.VISIBLE);
tv2.setText("Hello Girls");
count = 0;
}
public void onFinish() {
tv2.setVisibility(View.VISIBLE);
tv2.setText("Bye Girls");
count = 0;
}
}.start();
Did you "debug" the code to be sure the code is arriving to counter1 = new CountDownTimer(9000, 1000)?
Are you sure when the first counter arrives to onFinish() the flag variable is true?
Why do you call counter.cancel() in onFinish() when obviously the counter is already over?
public void onFinish() {
if(!flag) {
tv2.setText("Bye Guyz");
count = 0;
try {
counter.cancel();
}catch (Exception e){}
}
If you say your tv2 displays "Bye Guyz" it means that your flag is set to false, so the "else if" part is not being executed. onFinish() is only executed once, so you need to make sure the flag is set for true to start the second counter.
Also you shouldn't cancel your counter in onFinish() because it's already finished.
Here is my alternative is as follows
Create the custom Counterextending Thread
class Counter extends Thread {
private long timeOne, timeTwo;
private OnCounterFinishedListener mCounterFinishedListener;
private Thread t;
Activity activity = null;
Counter(Context context){
t = new Thread(this);
activity = (Activity)context;
}
#Override
public void run() {
try {
sleep(timeOne);
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
mCounterFinishedListener.firstCounterFinished();
}
});
sleep(timeTwo);
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
mCounterFinishedListener.secondCounterFinished();
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
void setTimes(long timeOne, long timeTwo){
this.timeOne = timeOne;
this.timeTwo = timeTwo;
}
public void start(OnCounterFinishedListener listener){
mCounterFinishedListener = listener;
t.start();
}
interface OnCounterFinishedListener{
void firstCounterFinished();
void secondCounterFinished();
}
}
Then inside your main thread you can start this counter as
final Counter counter = new Counter(this);
counter.setTimes(5000, 5000);
counter.start(new Counter.OnCounterFinishedListener() {
#Override
public void firstCounterFinished() {
// Update your first TextView
}
#Override
public void secondCounterFinished() {
// Update your second TextView
}
});
I'd appreciate your help in interrupting an Android/Java sleep. What I have in my layout is a button, which if clicked, calls the Skip method and starts a new activity. FYI The same activity would be called anyway when the Sleep method terminates.
Here's my failing code:
public class Splash extends Activity {
private Thread timer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
timer = new Thread() {
public void run() {
try {
sleep(5000);
} catch (Exception e) {
e.printStackTrace();
onPause();
return;
} finally {
onPause();
startActivity(new Intent("net.example.splashscreenexample.MainActivity"));
}
}
};
timer.start();
}
#Override
public void onPause() {
timer.interrupt();
super.onPause();
finish();
}
public void Skip() {
timer.interrupt();
startActivity(new Intent("net.example.splashscreenexample.MainActivity"));
}
Now Resolved!
I've now got it all working. In addition to #RocketSpock's suggestions there was also a stupid error in my code in that I'd failed to include the View view paramater into my Skip method call. So the fully working code now looks like this:
public class Splash extends Activity {
private Thread timer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
timer = new Thread() {
public void run() {
synchronized (this) {
try {
sleep(5000);
} catch (Exception e) {
e.printStackTrace();
onPause();
return;
} finally {
onPause();
startActivity(new Intent(
"net.rogw.splashscreenexample.MainActivity"));
}
}
}
};
timer.start();
}
#Override
public void onPause() {
timer.interrupt();
super.onPause();
finish();
}
public void Skip(View view) {
synchronized (this) {
this.notify();
}
startActivity(new Intent("net.rogw.splashscreenexample.MainActivity"));
}
}
If you want to be able to interrupt it you should be using a wait.
public class Splash extends Activity {
private Thread timer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
timer = new Thread() {
public void run() {
synchronized(this) {
try {
wait(5000);
} catch (Exception e) {
e.printStackTrace();
onPause();
return;
} finally {
onPause();
startActivity(new Intent("net.example.splashscreenexample.MainActivity"));
}
}
}
};
timer.start();
}
#Override
public void onPause() {
timer.interrupt();
super.onPause();
finish();
}
public void Skip() {
//You may need to replace this with the timer object
synchronized (this) {
//Informs the wait to interrupt.
this.notify();
}
startActivity(new Intent("net.example.splashscreenexample.MainActivity"));
}
I know there are already quite a number of discussions about this, but none of what I found could clear my confusion.
I'm using the Android SDK for the first time and my Java Skills are rather average.
I have the following Problem:
From my MainActivity - OnCreate() fct. I start a thread (Receiver), receiving data from a SocketStream. This thread shall refresh a TextView-Element on the GUI when new data was read from the stream.
What is a simple but proper way to do so? I read something about ASyncTask, but did not understand how to implement it.
public class MainActivity extends Activity
{
ExecutorService myExecutor;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
System.out.println("this is a test"); System.out.flush();
try
{
myExecutor = Executors.newCachedThreadPool();
myExecutor.execute(Receiver.getInstance());
}
catch (IOException e)
{
e.printStackTrace();
}
}
...
public class Receiver implements Runnable
{
[...]
public void run()
{
while (true)
{
//blocking system-io-call to read data from socket..
//extract information
// *** update textView *** ??
}
}
}
You can implement handler in GUI thread to change GUI (in MainActivity in your case):
public Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
//refresh textview
}
};
and than call it from another threads
activity.handler.sendEmptyMessage(what);
You can write your own constructor for Receiver:
public class Receiver implements Runnable
{
[...]
MainActivity activity;
public Receiver(MainActivity activity){
this.activity = activity;
}
public void run()
{
while (true)
{
//blocking system-io-call to read data from socket..
//extract information
// *** update textView *** ??
activity.handler.sendEmptyMessage(0);
}
}
}
You can use runOnUiThread
public class Receiver implements Runnable
{
[...]
public void run()
{
while (true)
{
//blocking system-io-call to read data from socket..
//extract information
runOnUiThread(new Runnable() {
public void run() {
// *** update textView *** ??
}
});
}
}
}
this is a example:
create Counter class :
public class Counter implements Runnable
{
private ICounterEvents listener;
public static Thread OBJ_THREAD = null;
public Counter()
{
OBJ_THREAD = new Thread(this);
}
public void setCountListener(ICounterEvents listener)
{
this.listener = listener;
}
public void start()
{
OBJ_THREAD.start();
}
#Override
public void run()
{
for(int i = 0; i < 100; i++)
{
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
Message msg = Message.obtain();
msg.obj = i;
this.handler.sendMessage(msg);
}
}
private Handler handler =
new Handler()
{
#Override
public void handleMessage(Message msg)
{
if(Counter.this.listener != null)
{
int value = (Integer)msg.obj;
Counter.this.listener.countChanged(value);
}
}
};
}
and create a interface class:
public interface ICounterEvents
{
public void countChanged(int value);
}
and than in your main layout create a textview and a button,
and use this code in onCreate method in MainActivity:
public class MainActivity extends Activity implements ICounterEvents, OnClickListener
{
private TextView txtCounter;
private Button btnStart;
private Counter counter;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.setupViews();
}
private void setupViews()
{
this.counter = new Counter();
this.counter.setCountListener(this);
this.txtCounter = (TextView)findViewById(R.id.txtCount);
this.btnStart = (Button)findViewById(R.id.btnStart);
this.btnStart.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
this.counter.start();
}
public void countChanged(int value)
{
try
{
this.txtCounter.setText(value + "");
}
catch (Exception e)
{
}
}
}
I write a Splash Screeen to run at the boot time of application
public class SplashScreen extends Activity {
ImageView imgView;
int[] imgID = new int[]{R.drawable.frame0, R.drawable.frame1, R.drawable.frame2, R.drawable.frame3,
R.drawable.frame4, R.drawable.frame5, R.drawable.frame6};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
imgView = (ImageView) findViewById(R.id.imgSplash);
new Thread(new WelcomeScreen()).start();
}
private class WelcomeScreen implements Runnable {
#Override
public void run() {
try {
for (int i = 0; i < imgID.length; i++)
{
imgView.setImageResource(imgID[i]);
sleep(500);
}
} catch (InterruptedException e) {
}finally {
Intent intent = new Intent(SplashScreen.this,LoginActivity.class);
startActivity(intent);
finish();
}
}
}
}
It getting error "Sorry the application has stopped unexpectedly" . I don't know why . Somebody can help me ????
you can not set the resource for yuor ImageView inside a thread different from the UI Thread.
you can use runOnUiThread. It takes as paramter a runnable, and post it in the UI Thread queue. There, the UI thead takes it and update your ImageView. All in all your runnable will become:
private class WelcomeScreen implements Runnable {
#Override
public void run() {
try {
for (int i = 0; i < imgID.length; i++)
{
final int resuorceId = imgID[i];
runOnUiThread(new Runnable() {
#Override
public void run() {
imgView.setImageResource(resuorceId);
}
});
sleep(500);
}
} catch (InterruptedException e) {
}finally {
Intent intent = new Intent(SplashScreen.this,LoginActivity.class);
startActivity(intent);
finish();
}
}
You can not access your views from Thread.
You will need to put your code imgView.setImageResource(imgID[i]); in runOnUiThread
use like:
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
imgView.setImageResource(imgID[i]);
}
});
Thanks
You can not change something in UI from non-UI thread so replace this you code:
imgView.setImageResource(imgID[i]);
to:
runOnUiThread(new Runnable() {
#Override
public void run() {
imgView.setImageResource(imgID[i]);
}
});
//try code this way...
public class SplashScreen extends Activity {
private Intent launchIntent;
private Thread splashThread; //used for perform splash screen operation
private int splashTime = 10000, sleepTime = 50; //used for threading operation
private boolean active = true; //used for touch event
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splashscreen); //Set splashscreen.xml here
try {
splashThread = new Thread() { // Creating Thread for splash the screen
#Override
public void run() { // run method implemented to perform threading operation
try {
int waitTime = 0; //counter for threading
do {
sleep(sleepTime); //delay for specific time
if (active)
waitTime += 100;
//write your image code here that display your no. of images
} while (active && (waitTime < splashTime)); //Check touch condition and counter
} catch (Exception e) {
// to handle runtime error of run method
Validation.displayToastMessage(SplashScreen.this, e.toString()); //Call static method of class ToastMessage
}
finish(); //finish current activity
startJustCoupleActivityScreen(); //Call below defined function
}
};
splashThread.start(); //start thread here
} catch (Exception e) {
message("SplashScreen : "+ e.toString()); //Call static method of class ToastMessage
}
}
public void startJustCoupleActivityScreen() {
launchIntent=new Intent(SplashScreen.this,JustCoupleActivity.class); //call Next Screen
startActivity(launchIntent); //start new activity
}
#Override
public boolean onTouchEvent(MotionEvent event) { //onTouch Event
//on touch it immediate skip splash screen
if(event.getAction()==MotionEvent.ACTION_DOWN) active=false; //Check Touch happened or not
return true;
}
public void message(String msg)
{
Validation.displayToastMessage(SplashScreen.this, msg); //display Error Message
}
}