how to Kill and Start Thread with two buttons - java

Start Button...
btn_start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
start_stop = true;
thread.start();
chronometer.setBase(SystemClock.elapsedRealtime() + timeWhenStopped);
chronometer.start();
}
});
Stop Button...
btn_stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chronometer.stop();
// 변수에 저장된 값 초기화!!
timeWhenStopped =0;
start_stop=false;
graph.removeAllSeries();
data = 0;
double[] resetted = new double[50];
saving = resetted;
if(thread !=null && thread.isAlive()) thread.interrupt();
i++;
}
});
And here is my thread in the same activity.
runnable = new Runnable() {
#Override
public void run() {
int j =i;
if(!thread.interrupted()){
for (int i = 0; i < 50; i++){
if(start_stop){
runOnUiThread(new Runnable() {
#Override
public void run() {
addEntry();
}
});
try {
Thread.sleep(600); //여기서 속도 제어할 수 있나봄!
} catch (InterruptedException e) {
// manage error ...
}
}
}
}
}
};
thread = new Thread(runnable);
So what I'm going to do is. I want to draw some line graph started with button Start, and then stop and clear with stop button.
and draw new graph again with start button.
But every time I tried re-start , application shut-down with error..
" Thread already started... "
So I think I need to kill or stop thread by clicking Stop button..
and I've tried several ways ... recommended... around here and I couldn't solve yet.
help me please..
(+ and I'm quite new here,,, and,,, my English isn't perfect.. also it's my first question.. sorry for any mistakes. thanks)

Related

Exit activity after killing all threads android

I am trying to play with progress bars. I have this (below) simple activity which runs a progress bar N times one after the other, when I call Progress(N). It is working great but the problem I am facing is, if I press back button. I get into the mainActivity but the progress bars (the threads) are still running in background one after the other. As soon as they finish N loops, the intent is called and whatever I would be doing would be interrupted by this LOOP_OVER activity.
I tried solving this by my own. I tried using variable of Thread class (before I was directly doing it). And tried to interrupt() it at onDestroy() or even just before the intent is called but its not helping. How should I go about it?
public class Loop extends Activity {
private ProgressBar progressBar;
private CircleProgress circleProgress;
private int progressStatus = 0;
private Handler handler = new Handler();
private TextView myView;
private int started = 0, doneLoop=0;
private Thread th;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loop);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
circleProgress = (CircleProgress) findViewById(R.id.circle_progress);
myView = (TextView) findViewById(R.id.instruction);
progressBar.setScaleY(3f);
// Start long running operation in a background thread
Progress(3);
}
#Override
public void onDestroy() {
// Below, everything I am just
th.interrupt();
Loop.this.finish();
Thread.currentThread().interrupt();
super.onDestroy();
}
public void Progress(final int numberOfRuns){
// QueView.setText(Que);
if(numberOfRuns == 0){
th.interrupt();
Intent myIntent = new Intent(Loop.this, LOOP_OVER.class);
startActivity(myIntent);
super.onDestroy();
finish();
}
th = new Thread(new Runnable() {
public void run() {
genNextSet();
while (progressStatus < 100) {
progressStatus += 1;
// Update the progress bar and display the
//current value in the text view
handler.post(new Runnable() {
public void run() {
circleProgress.setProgress(progressStatus);
progressBar.setProgress(progressStatus);
textView.setText(progressStatus+"/"+progressBar.getMax());
}
});
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
myView.setText(Que);
}
});
// Sleep for 200 milliseconds.
//Just to display the progress slowly
Thread.sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
progressStatus = 0;
Progress(numberOfRuns - 1);
}
});
th.start();
}
private void genNextSet() {
// so some cool here!
}
}
You can think of a class variable that is shared among all threads.
Try to add something like this:
private Boolean LOOP = true;
then
while (progressStatus < 100 && LOOP) {
and
#Override
public void onBackPressed() {
LOOP = false
}
also
if(LOOP == true){
// call intent
}
finish();
Your activity does not get destroyed, if you press the "Back"-key, thus onDestroy() will not be called.I'd override onBackPressed(), if I where you.Alternatively, you could try to put it into the onPause()-method.
You haven't override the back button pressed..try this
#Override
public void onBackPressed() {
th.interrupt();
Loop.this.finish();
Thread.currentThread().interrupt();
super.onBackPressed();
// add finish() if you want to kill current activity
}

Starting a thread with a button

I'm programming a small android app in Java/eclipse.
In one part of my app i need a thread, as i build in the following way:
protected void onResume() {
super.onResume();
// we're going to simulate real time with thread that append data to the graph
new Thread(new Runnable() {
#Override
public void run() {
// we add 100 new entries
for (int i = 0; i < 100; i++) {
runOnUiThread(new Runnable() {
#Override
public void run() {
addEntry();
}
});
// sleep to slow down the add of entries
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// manage error ...
}
}
}
}).start();
}
Evertything works fine so far. But now i want to start that thread not automatically. I want to handle ".start()" with a button.
How can i realize it?
I'm very new to Java and Android.
Thanks in Advance!
You can use Handler with Runnable instead of your Thread idea, Check out the following code, it server your purpose,
private Handler broadcastHandler;
private Runnable broadcastRunnable;
protected void onResume() {
super.onResume();
broadcastRunnable = new Runnable() {
#Override
public void run() {
// Your UI related operations
runOnUiThread(new Runnable() {
#Override
public void run() {
addEntry();
}
});
// Add some delay
broadcastHandler.postDelayed(broadcastRunnable, 1000);
}
}
public void onButtonClick(View view) {
broadcastHandler.postDelayed(broadcastRunnable, 1000);
}

Android Process Function Not Working On Background

As you can see in the pictures, toast line is working properly but process function not working another activity.
This code line does not workking on background, only work on Activity.
Process p = Runtime.getRuntime().exec("input touchscreen tap 500 500");
My purpose is touch the different screen, EX:WhatsApp or any app.
btndene.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Thread(new Runnable() {
#Override
public void run() {
Intent launchIntent = getPackageManager().getLaunchIntentForPackage("com.teamviewer.quicksupport.market");
startActivity(launchIntent);
for(int i = 0; i<10; i++) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
update(i);
}
}
private void update(final int i) {
runOnUiThread(new Runnable() {
#Override
public void run() {
//txt.setText("Hello"+i);
// komut = "input keyevent 30";
//calistir(komut);
Toast.makeText(MainActivity.this,"Bastin",Toast.LENGTH_SHORT).show();
try {
p = Runtime.getRuntime().exec("input touchscreen tap 500 500");
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}).start();
Due to security reasons it wont work on other apps...You can use any UI automation frameworks like Robotium,Expresso to do this..
Try using monkeyrunner instead. It works with any app.

Using Sleep(int ms) in onClick(View arg0)

I am working on this android application:
A Button and a textField, the button click change the text of the textField.
So i want to add some animation to the button click by changing the text character by character and wait 100 millisecondes before adding each character.
But when I run the application and press the button, all the text appear after the sleep time without any animation :p
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
for(int i=0 ; i<str.length() ; i++)
{
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
txt.append(String.valueOf(str.charAt(i)));
}
}
});
you do not want to sleep on the main-thread. Better use postDelayed
you block ui thread now and you only see the result of onClick. you should not call sleep in ui thread. this is not best, but it should work
#Override
public void onClick(View arg0) {
final Handler handler = new Handler();
new Thread() {
public void run() {
for (int i = 0; i < str.length(); i++) {
final int _i = i;
try {
Thread.sleep(100);
} catch (Exception e) {
}
handler.post(new Runnable() {
public void run() {
txt.append(String.valueOf(str.charAt(_i)));
}
});
}
}
}.start();
}

Start infinite loop thread when button is pressed, stop when it is pressed again

I am simulating a camera feed and have a button that goes through an infinite loop of images.
It starts when the button is clicked, when the button is clicked it is supposed to stop the thread until the button is clicked again.
Right now it starts and loops fine, but when I click it again It crashes
on click
public void onClick(View v) {
switch(v.getId()){
case R.id.cam1btn:{
if(thread1 == null){
thread1 = new Thread(){
public void run(){
Cam1();
}
};
thread1.start();
}
else
{
thread1.stop();
thread1=(null);
}
}
break;
Cam1 function
protected void Cam1() {
int i=0;
do{
System.out.println("got into loop");
for(int x=0;x<4;x++){
//imgFeed1.setImageAlpha(camFeed1[x]);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
final int temp = x;
mCam1Handler.post(new Runnable(){
public void run(){
imgFeed1.setImageResource(camFeed1[temp]);
}
});
}
}while(i == 0);
}
logcat
You should not forcibly stop the thread in general. Thread has to stop by completing its task.
In your case, you need to define i = 0 in a instance scope and set that to some value when user clicks stop button, with that your while loop ends and the thread completes its task.
I would rather suggest you to maintain a boolean flag instead of an int.
UPDATE
Okay, then your you should have a flag and toggle that ex: toRun = false for the first time, when the user clicks the button you do toRun = !toRun;. In your run method there should be a while(toRun) {
//repeat your task
}
just to help you understand Rp- answer:
first declare boolean toRun outside your thread because it is a variable that is accessed by two threads(UI and your created) you must use 'synchornize` block to access it and read and write it.
boolean toRun = false;
public void onClick(View v) {
switch(v.getId()){
case R.id.cam1btn:{
boolean isThreadRunning;
synchronize(toRun){
isThreadRunning = toRun;
}
if(!isThreadRunning){
toRun =true; // here you do not need synchronize block because the thread has not been created.
thread1 = new Thread(){
public void run(){
Cam1();
}
};
thread1.start();
}
else
{
synchornize(toRun){
toRun = false;
}
}
}
break;
and in your cam1:
protected void Cam1() {
boolean myRun;
do{
System.out.println("got into loop");
for(int x=0;x<4;x++){
//imgFeed1.setImageAlpha(camFeed1[x]);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
final int temp = x;
mCam1Handler.post(new Runnable(){
public void run(){
imgFeed1.setImageResource(camFeed1[temp]);
}
});
}
synchronize(toRun){
myRun = toRun;
}
}while(myRun);
}

Categories

Resources