I have a CountDownTimer in for loop, but it doesn't count. Why?
for (int i = 0; i < payloadList.size(); i++) {
sonpx.dtnsocialnetwork.Bundle bundle = new sonpx.dtnsocialnetwork.Bundle(
srcIMEI, desIMEI, fileName, i, totalFragment,
numOfSendingRest, payloadList.get(i));
byte[][] payload = new byte[1][];
try {
payload[0] = serialize(bundle);
} catch (IOException e) {
e.printStackTrace();
}
Log.i(TAG, "bundle payload size: "+payload[0].length);
mDefaultChannel.sendData(nodeName, DIRECT_BUNDLE, payload);
CountDownTimer countDownTimer = new CountDownTimer(5000, 100) {
#Override
public void onTick(long millisUntilFinished) {
if (bundleResultOk) {
cancel();
bundleResultOk = false;
}
Log.i(TAG, "bundle result: "+bundleResultOk);
}
#Override
public void onFinish() {
counterFinish = true;
Log.i(TAG, "Send Message time out");
}
};
countDownTimer.start();
}
It doesn't print Log.i(TAG, "bundle result: "+bundleResultOk);
maybe the code in not running in a HandlerThread
Use this custom CountdownTimer
Related
I'm work on crate server and android client
but thread doesn't interrupted by android client
My android Client has request for the RoomList from server
and Server receive, Client Accept
and fill in my ListView used the Adapter
here's problem if Click backButton,
than RoomListAcitivity was close and thread was stop
but thread dosen't stop just alive in my app
first Enter has work on sucessfully
but Press BackButton on and re-Enter this Activity
MyApp just White, No Action
how can i stop this thread?
(and sorry for my English skill...)
i tried .interrupt() method , and handler.removeMessages(0)
but failed thread keep alive
upload this full java code just in case...
ListView roomList;
RoomAdapter roomAdapter;
Socketservice ss;
String msg,rtitle;
String msgs[];
String list[];
Thread listthread,EnterRoomThread,removeV;
boolean staterun = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_room);
roomList = findViewById(R.id.roomList);
roomAdapter = new RoomAdapter();
listthread = new Thread() {
public void run(){
ss.out.println("163|");
ss.out.println("100|");
try {
while (staterun == true) {
msg = ss.in.readLine();
handler.post(new Runnable() {
public void run() {
msgs = msg.split("\\|");
String protocol = msgs[0];
switch (protocol) {
case "163":
list = msgs[1].split(",");
for (int i = 0; i < list.length; i++) {
String list1[] = list[i].split("-");
String listT = list1[0];
int listC = Integer.parseInt(list1[1]);
int listI = Integer.parseInt(list1[2]);
roomAdapter.CreateRoom(listI, listT, listC);
}
roomList.setAdapter(roomAdapter);
msg = "";
msgs = null;
break;
case "200":
Intent i = new Intent(getApplicationContext(), GameWaitingActivity.class);
i.putExtra("tname", rtitle);
staterun = !staterun;
Toast.makeText(getApplicationContext(),""+listthread.isAlive(),Toast.LENGTH_SHORT).show();
startActivity(i);
finish();
break;
case "201":
Toast.makeText(getApplicationContext(), "방이 꽉 찼습니다.", Toast.LENGTH_SHORT).show();
break;
}
}
});
}
} catch (IOException e) {
}
}
};
listthread.start();
roomList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Room item = (Room) roomList.getItemAtPosition(position);
rtitle=item.getTitle();
EnterRoomThread = new Thread() {
public void run() {
ss.out.println("200|" + rtitle);
EnterRoomThread.interrupt();
}
};
EnterRoomThread.start();
}
});
}
Handler handler = new Handler();
#Override
public void onBackPressed() {
removeV = new Thread() {
public void run(){
ss.out.println("101|");
removeV.interrupt();
}
};
removeV.start();
handler.removeMessages(0);
staterun = false;
listthread.interrupt();
Toast.makeText(getApplicationContext(),""+listthread.isAlive(),Toast.LENGTH_SHORT).show();
finish();
}
}
Go ahead with this, write this inside run() method
//use this boolean value to keep track.
boolean shouldRunFlag = true;
while (shouldRunFlag) {
try {
Thread.sleep(10);
//Do your work............
} catch (Exception e) {
e.printStackTrace();
Log.v(TAG, "Interrupted Exception caught");
// change the flag, so that while loop can be broken.
shouldRunFlag = false;
Log.v(TAG, "run: breaking the loop");
break;
}
}
and this is how you interrupt and clean the thread
private void interrupt(Thread currentThread) {
Log.i(TAG, "interrupt");
if (currentThread != null) {
Thread dummyThread = currentThread;
dummyThread.interrupt();
currentThread = null;
}
}
The thread in my application is giving a weird error on the myThread.start() function specifically the start is wrong the error is "Cannot resolve symbol start" . initially i thought it was a bracket issue but when i adjust them it ends up breaking the OnClicklistner. The thread is suppose just suppose to make the user wait before doing a set text and then the following button will take the user to a website. Can any one see my error?
package com.example.trap.york_hw6;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;
public class Main3Activity extends AppCompatActivity implements View.OnClickListener {
Button Cheat;
Button NextPage3;
WebView browser3;
#SuppressLint("HandlerLeak")
Handler handler = new Handler() {
public void handleMessage(Message msg) {
TextView statement = (TextView) findViewById(R.id.snitch);
statement.setText("Checking to see if your a cop");
}
;
};
#SuppressLint("HandlerLeak")
Handler handler2 = new Handler() {
public void handleMessage(Message msg) {
browser3.loadUrl("https://www.youtube.com");
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
browser3 = (WebView) findViewById(R.id.webkit3);
browser3.getSettings().setJavaScriptEnabled(true);
browser3.getSettings().setDomStorageEnabled(true);
Cheat = (Button) findViewById(R.id.CC);
NextPage3 = (Button) findViewById(R.id.Next3);
NextPage3.setOnClickListener(this);
Cheat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Runnable r = new Runnable() {
public void run() {
long futureTime = System.currentTimeMillis() + 5000;
while (System.currentTimeMillis() < futureTime) {
synchronized (this) {
try {
wait(futureTime - System.currentTimeMillis());
} catch (Exception e) {
}
}
}
handler.sendEmptyMessage(0);
}
;
Thread myThread = new Thread(r);
myThread.start();
};
}
});
final Runnable r2 = new Runnable() {
public void run() {
long futureTime = System.currentTimeMillis() + 7000;
while (System.currentTimeMillis() < futureTime) {
synchronized (this) {
try {
wait(futureTime - System.currentTimeMillis());
} catch (Exception e) {
}
}
}
handler.sendEmptyMessage(0);
}
;
Thread myThread2 = new Thread(r2);
myThread2.start();
};
}
public void onClick(View v) {
Intent i = new Intent(this, Main4Activity.class);
i.putExtra("value", "I got this from MainActivity2");
i.putExtra("value1", 5);
startActivityForResult(i, 3);
}
}
You are starting thread inside wrong block. Try the code below .
final Runnable r2 = new Runnable() {
public void run() {
long futureTime = System.currentTimeMillis() + 7000;
while (System.currentTimeMillis() < futureTime) {
synchronized (this) {
try {
wait(futureTime - System.currentTimeMillis());
} catch (Exception e) {
}
}
}
handler.sendEmptyMessage(0);
};
};
Thread myThread2 = new Thread(r2);
myThread2.start();
AND
Cheat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Runnable r = new Runnable() {
public void run() {
long futureTime = System.currentTimeMillis() + 5000;
while (System.currentTimeMillis() < futureTime) {
synchronized (this) {
try {
wait(futureTime - System.currentTimeMillis());
} catch (Exception e) {
}
}
}
handler.sendEmptyMessage(0);
};
};
Thread myThread = new Thread(r);
myThread.start();
}
});
You can not initialise and start Runnable inside its block.
You can write like this.
Cheat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Runnable r = new Runnable() {
public void run() {
long futureTime = System.currentTimeMillis() + 5000;
while (System.currentTimeMillis() < futureTime) {
synchronized (this) {
try {
wait(futureTime - System.currentTimeMillis());
} catch (Exception e) {
}
}
}
handler.sendEmptyMessage(0);
}
};
Thread myThread = new Thread(r);
myThread.start();
}
});
and second one
final Runnable r2 = new Runnable() {
public void run() {
long futureTime = System.currentTimeMillis() + 7000;
while (System.currentTimeMillis() < futureTime) {
synchronized (this) {
try {
wait(futureTime - System.currentTimeMillis());
} catch (Exception e) {
}
}
}
handler.sendEmptyMessage(0);
}
};
Thread myThread2 = new Thread(r2);
myThread2.start();
Suggestion : Also i seen your onClick method, i suggest you check clicked button's id before doing any action like. Because if you have multiple buttons having OnClickListener referring to current class, you will need to check.
public void onClick(View v) {
switch (v.getId()){
case R.id.Next3:
Intent i = new Intent(this, Main4Activity.class);
i.putExtra("value", "I got this from MainActivity2");
i.putExtra("value1", 5);
startActivityForResult(i, 3);
break;
}
}
I am implementing TTS (Text to Speech) support in my Android app. I am showing my code :
TextSpeech textSpeech = new TextSpeech();
textToSpeech = new TextToSpeech(this, textSpeech);
private class TextSpeech implements TextToSpeech.OnInitListener {
#Override
public void onInit(final int status) {
if (status != TextToSpeech.ERROR) {
if (TextToSpeech.LANG_AVAILABLE == textToSpeech.isLanguageAvailable(Locale.ENGLISH)) {
Thread thread = new Thread() {
#Override
public void run() {
super.run();
textToSpeech.setLanguage(Locale.ENGLISH);
try {
for (int i = 0; i < 10; i++) {
if (Util.isGreaterThanApi21()) {
textToSpeech.speak("" + i, TextToSpeech.QUEUE_FLUSH, null, null);
} else {
textToSpeech.speak("" + i, TextToSpeech.QUEUE_FLUSH, null);
}
Thread.sleep(1000);
}
} catch (Exception exception) {
}
}
};
thread.start();
} else {
Toast.makeText(ViewWorkplanActivity.this, "Language Not Supported", Toast.LENGTH_SHORT).show();
}
}
}
}
When I run this code, some devices missing 3-4 number or taking 3-4 seconds for initialization. Can any body tell me how can I remove this error?
I need count down timer that whenever I clicked or times up, send result and time score to another activity. So I used thread, but I don't know why in first time run activity it don't show time for some seconds in textview, one more strange thing is that when press back,then go to activity again it works fine.
count down code:
if (flagTime) {
flagTime = false;
new Thread(new Runnable() {
#Override
public void run() {
int counter = 60;
while (function.isActivityVisible() && counter > 0) {
counter--;
final int finalCounter = counter;
try {
Thread.sleep(1000);
G.HANDLER.post(new Runnable() {
#Override
public void run() {
if (function.isActivityVisible()) {
timeSc=finalCounter;
String preSec = "";
if (finalCounter < 10) {
preSec = "0";
}
if (function.isActivityVisible()
&& finalCounter <= 0) {
flagTime = false;
Intent intent = new Intent(
Memorize.this,
MemorizeResult.class);
intent.putExtra("TIME", 60);
intent.putExtra("ARRAY_RESULT",
array_choice);
startActivity(intent);
finish();
}
String score = "00:" + preSec
+ finalCounter;
txt[20].setText( " time ramaining " + score);
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
if (!function.isActivityVisible()) {
flagTime = false;
finish();
}
}
}).start();
}
I use many flag to handle it, but it seems don't work properly.
Try using a CountDownTimer
Something like:
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
I have two threads, two handlers. From thread i check a random number and send result to handle to update ui. But i am getting the error "only the original thread that created a view hierarchy can touch its views.". I searched some articles, they tell to use handler. I am doing that, yet can not avoid the errors.
After some checking, I found that it crashes when A sends the result. In case of B, it works
Also, can i use one handler for two thread?
public class MainActivity extends Activity implements View.OnClickListener{
Button start;
TextView status_B, status_A;
Boolean isRunning;
Thread Athread, Bthread;
int a, b;
Handler a_Handler, b_Handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initialize variables
start = (Button) findViewById(R.id.button);
start.setOnClickListener(this);
status_B = (TextView) findViewById(R.id.textView);
status_A = (TextView) findViewById(R.id.textView1);
a_Handler = new Handler() {
public void handleMessage(Message msg)
{
int number = msg.getData().getInt("number");
String winner = msg.getData().getString("winner");
start.setEnabled(true);
isRunning = false;
status_A.setText(winner + number);
}
};
b_Handler = new Handler() {
public void handleMessage(Message msg)
{
int number = msg.getData().getInt("number");
String winner = msg.getData().getString("winner");
start.setEnabled(true);
isRunning = false;
status_B.setText(winner + number);
}
};
}
#Override
protected void onStart() {
super.onStart();
isRunning = false;
}
#Override
public void onClick(View v) {
start.setEnabled(false);
status_B.setText("Guessing...");
if (!isRunning)
{
Athread = new Thread(new Runnable() {
#Override
public void run() {
while (isRunning)
{
try
{
Athread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
a = (int) (Math.random()*1000);
System.out.println("a "+ a);
if(a%7 == 0) {
isRunning = false;
Bundle bundle = new Bundle();
bundle.putString("winner", "A");
bundle.putInt("number", a);
Message msg = a_Handler.obtainMessage();
msg.setData(bundle);
a_Handler.handleMessage(msg);
}
}
}
});
Bthread = new Thread(new Runnable() {
#Override
public void run() {
while(isRunning)
{
try
{
Bthread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
b = (int) (Math.random()*1000);
System.out.println("b "+ b);
if(b%7 == 0) {
isRunning = false;
Bundle bundle = new Bundle();
bundle.putString("winner", "B");
bundle.putInt("number", b);
Message msg = b_Handler.obtainMessage();
msg.setData(bundle);
b_Handler.sendMessage(msg);
}
}
}
});
isRunning = true;
Athread.start();
Bthread.start();
}
}
}
You need put your code to modify views on UI thread:
a_Handler = new Handler() {
public void handleMessage(Message msg)
{
final int number = msg.getData().getInt("number");
final String winner = msg.getData().getString("winner");
runOnUiThread(new Runnable() {
#Override
public void run() {
start.setEnabled(true);
status_A.setText(winner + number);
}
});
isRunning = false;
}
};
b_Handler = new Handler() {
public void handleMessage(Message msg)
{
final int number = msg.getData().getInt("number");
final String winner = msg.getData().getString("winner");
runOnUiThread(new Runnable() {
#Override
public void run() {
start.setEnabled(true);
status_B.setText(winner + number);
}
});
isRunning = false;
}
};