How to use timer in Android - java

In my application i have timer for some works.
When my application running after some time my application freeze and not work any View !
In this timer every 500ms i emit socket.io
My Codes:
AsyncTask.execute(new Runnable() {
#Override
public void run() {
socketPingTimer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
if (isSendSocketPing) {
checkSocketPingTimer += startSocketPingTimer;
if (checkSocketPingTimer == sendSocketPingTimer) {
currentTimerForSocket = System.currentTimeMillis();
try {
detailSocketUtils.getSendRTTforPing(currentTimerForSocket + "");
} catch (Exception e) {
}
}
//Show ping (from search)
Constants.currentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
if (isShownPing) {
detailToolbar_ping.setVisibility(View.VISIBLE);
if (checkSocketPingTimer > 500) {
detailToolbar_ping.setText(checkSocketPingTimer + "");
detailToolbar_ping.setTextColor(Color.RED);
} else {
detailToolbar_ping.setText(checkSocketPingTimer + "");
detailToolbar_ping.setTextColor(Color.GREEN);
}
} else {
detailToolbar_ping.setVisibility(View.GONE);
}
}
});
socketPing = checkSocketPingTimer;
}
}
}, 500, startSocketPingTimer);
}
});
How can i run this timers in another thread and not freeze my app ?

It should be something similar to this code:
class MyActivity extends Activity
{
private void executeLoop()
{
Handler myHandler = new Handler()
{
public void handleMessage(Message msg)
{
if (isShownPing)
{
detailToolbar_ping.setVisibility(View.VISIBLE);
if (checkSocketPingTimer > 500) {
detailToolbar_ping.setText(checkSocketPingTimer + "");
detailToolbar_ping.setTextColor(Color.RED);
} else {
detailToolbar_ping.setText(checkSocketPingTimer + "");
detailToolbar_ping.setTextColor(Color.GREEN);
}
} else
{
detailToolbar_ping.setVisibility(View.GONE);
}
}
}
socketPingTimer.scheduleAtFixedRate(new TimerTask()
{
#Override
public void run()
{
if (isSendSocketPing)
{
checkSocketPingTimer += startSocketPingTimer;
if (checkSocketPingTimer == sendSocketPingTimer) {
currentTimerForSocket = System.currentTimeMillis();
try {
detailSocketUtils.getSendRTTforPing(currentTimerForSocket + "");
} catch (Exception e) {
}
}
myHandler.sendEmptyMessage();
socketPing = checkSocketPingTimer;
}
}
}, 500, startSocketPingTimer);
}
}

private void startTimerAtFixRate() {
android.os.Handler handler = new android.os.Handler();
Runnable updateTimerThread = new Runnable() {
public void run() {
//write here whatever you want to repeat
// Like I called Log statement
// After every 1 second this below statement will be executed
Log.e("CALLED-->", "TRUE");
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(updateTimerThread, 100);
}

Related

Why i'm getting exception ViewRootImpl$CalledFromWrongThreadException?

And how should i solve it ?
This is my button click method that i call it from inside onCreate:
public void addListenerOnButton()
{
btnClick = (Button) findViewById(R.id.checkipbutton);
btnClick.setOnClickListener(new OnClickListener()
{
byte[] response = null;
#Override
public void onClick(View arg0)
{
text = (TextView) findViewById(R.id.textView2);
Thread t = new Thread(new Runnable()
{
#Override
public void run()
{
for (int i = 0; i < ipaddresses.length; i++)
{
try
{
response = Get(ipaddresses[i]);
if (response == null)
{
text.setText("Connection Failed: " + generateRunnablePrinter(i));
}
}
catch (Exception e)
{
String err = e.toString();
}
if (response != null)
{
try
{
final String a = new String(response, "UTF-8");
text.post(new Runnable()
{
#Override
public void run()
{
text.setText(a);
}
});
iptouse = ipaddresses[i].substring(0, 26);
connectedtoipsuccess = true;
Logger.getLogger("MainActivity(inside thread)").info(a);
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
Logger.getLogger("MainActivity(inside thread)").info("encoding exception");
}
Logger.getLogger("MainActivity(inside thread)").info("test1");
break;
}
else
{
}
}
}
});
t.start();
}
});
}
At this place in the method inside the FOR loop the variable 'i' should be final:
text.setText("Connection Failed: " + generateRunnablePrinter(i));
But since 'i' is also the variable of the FOR loop i can't make it final.
So i added the method : generateRunnablePrinter
private Runnable generateRunnablePrinter(final int value)
{
return new Runnable() {
public void run()
{
text.setText("Connection Failed: " + ipaddresses[value]);
}
};
}
But now using this method I'm getting the exception:
ViewRootImpl$CalledFromWrongThreadException
You can't change the UI "text of the TextView" from another thread so you can try AsyncTask to do the work in the background in doInBackground() method then change the UI in the method onPostExecute().
Check out the AsyncTask:
http://developer.android.com/reference/android/os/AsyncTask.html
Since you're adjusting your UI, you'll need to run it from the UI thread. I'd recommend this function:
runOnUiThread(new Runnable() {
#Override
public void run() {
// Your code here...
}
});
If you're calling it from anywhere else but an Activity, you'll need to either pass down the activity or get the activity using getActivity() (i.e. from a fragment), and then call the function from the activity, i.e. getActivity().runOnUiThread() { ... }

I want to show a loading animation while connecting to a websocket

I'm trying to show an animation in my app while connecting to a web server, just so that the user doesn't think that it's crashed/frozen.
Here's the bit in the code that may be relevant:
private void waitForWebSocketConnect() {
long start = System.currentTimeMillis();
long end = start + 3*1000; // 3 seconds
while (!mWebSocketClient.isOpen()) {
try {
Thread.sleep(200);
if(System.currentTimeMillis() >= end){
throw new InterruptedException();
}
} catch (InterruptedException e) {
fatalError("WebSocket did not connect. Please try again.");
}
}
}
I think this might also be of use:
private void connectWebSocket() {
final Activity faActivity = super.getActivity();
URI uri;
try {
String uriString;
if(isRegistering){
//uriString = "ws://app.touchtechpayments.com:80/reg";
uriString = "wss://ec2-52-16-13-241.eu-west-1.compute.amazonaws.com/reg";
} else {
//uriString = "ws://app.touchtechpayments.com:80/trans";
uriString = "wss://ec2-52-16-13-241.eu-west-1.compute.amazonaws.com/trans";
}
Log.d("uriString", uriString);
uri = new URI(uriString);
} catch (URISyntaxException e) {
e.printStackTrace();
return;
}
mWebSocketClient = new WebSocketClient(uri) {
#Override
public void onOpen(ServerHandshake serverHandshake) {
this.progressBar.setVisibility(View.GONE);
Log.d("Websocket", "Opened");
}
#Override
public void onMessage(String s) {
Log.d("Websocket", "Received message " + s);
if(isRegistering) {
confirmRegistration(s);
} else {
confirmTransaction(s);
}
}
#Override
public void onClose(int i, String s, boolean b) {
Log.d("Websocket", "Closed " + s);
if(!allDone) {
if (triedTwice) {
final String printToast = "Error received: " + s + "\nPlease try again.";
faActivity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(context, printToast, Toast.LENGTH_LONG).show();
faActivity.getFragmentManager().popBackStack();
}
});
} else {
Log.d("Websocket", "Trying for second time.");
triedTwice = true;
if (lastInputToServer != null) {
setupSSL();
connectWebSocket();
waitForWebSocketConnect();
mWebSocketClient.send(lastInputToServer);
}
}
}
}
#Override
public void onError(Exception e) {
this.progressBar.setVisibility(View.GONE);
Log.d("Websocket", "Error " + e.getMessage());
}
};
setupSSL();
mProgressBar.setVisibility(View.VISIBLE);
mWebSocketClient.connect();
}
The webSocketClient isn't actually defined in onCreate(), but the above method IS used in onCreate() anyway.
First define a ProgressBar in your layout.xml and enable the indeterminate mode by using indeterminate parameter:
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible"
android:indeterminate = "true"/>
Then hide your progressBar as soon as the websocket connection has been established:
public void onCreate(){
[...]
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
mWebSocketClient = new WebSocketClient(uri) {
#Override
public void onOpen(ServerHandshake serverHandshake){
this.progressBar.setVisibility(View.GONE); // or INVISIBLE
}
#Override
public void onMessage(String s) {
}
#Override
public void onClose(int i, String s, boolean b) {
}
#Override
public void onError(Exception e) {
this.progressBar.setVisibility(View.GONE); // or INVISIBLE
}
};
mProgressBar.setVisibility(View.VISIBLE);
mWebSocketClient.connect();
}
You can also define your ProgressBar as invisible and show it later before mWebSocketClient.connect() call.
P.S. I'm using this java websocket library in this example
dependencies {
compile "org.java-websocket:Java-WebSocket:1.3.0"
}
you can use j Progress bar in the program simultaneously with timer so it will be ok for the user to see the moving progress bar...if you want so reply me i will give you the coding of how to use the progress bar...

Link java class to xml file in android

I would like to link java class to my xml file.
There is no error in the coding however, it gave me force close.
I would like to know what's wrong with it.
Can anyone please advice me?
I've one main java class, having the same code as this, as I would like to display the same thing for both xml layout.
The main java class work perfectly fine, however, when I try to convert the coding to second java class, the force close error occurs.
Here is my coding.
public class event extends ListActivity{
ArrayList<String> psi;
public TextView psi_text;
TextView weather;
ImageView image;
private static Handler mHandler = new Handler();
class MyWeather{
String conditiontext;
String conditiontemp;
String conditiondate;
public String forecastToString(){
return
conditiontext + "\n" + " " + conditiontemp + "°C" ;
}
}
String[] Category = {
"Scientist for a day",
"Science Trail",
"Megalog Return"
};
String [] dates = {
"Today",
"Tomorrow",
"This Week"
};
Spinner s1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.event);
weather = (TextView)findViewById(R.id.weather);
image = (ImageView)findViewById(R.id.image);
psi = new ArrayList<String>();
psi_text = (TextView) findViewById(R.id.psi_text);
TabHost th =(TabHost)findViewById(R.id.tabhost);
th.setup();
TabSpec specs = th.newTabSpec("tag1");
specs.setContent(R.id.tab1);
specs.setIndicator("Suggested");
th.addTab(specs);
specs = th.newTabSpec("tag2");
specs.setContent(R.id.tab2);
specs.setIndicator("All");
th.addTab(specs);
TabWidget tw = (TabWidget) th.findViewById(android.R.id.tabs);
View tab1 = tw.getChildTabViewAt(0);
TextView tv = (TextView) tab1.findViewById(android.R.id.title);
tv.setTextSize(15);
tv.setPadding(0, 0, 0, 50);
View tab2 = tw.getChildTabViewAt(1);
TextView tv1 = (TextView) tab2.findViewById(android.R.id.title);
tv1.setTextSize(15);
tv1.setPadding(0, 0, 0, 50);
//GridView
setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,Category));
//SpinnerView
s1 = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, dates);
s1.setAdapter(adapter);
s1.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> arg0,View arg1, int arg2, long arg3) {
int index = s1.getSelectedItemPosition();
Toast.makeText(getBaseContext(), "You have seleted item :" + dates[index] , Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?>arg0) {}
});
try {
URL url = new URL(
"http://app2.nea.gov.sg/data/rss/nea_psi.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("item");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
Element fstElmnt = (Element) node;
NodeList websiteList = fstElmnt.getElementsByTagName("psi");
Element websiteElement = (Element) websiteList.item(0);
websiteList = websiteElement.getChildNodes();
psi.add(""+ ((Node) websiteList.item(0)).getNodeValue());
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
String temp = Html.fromHtml(psi.get(0)).toString();
String a[] = temp.split("\\)");
psi_text.setText(""+a[0]+")");
Thread myThread = new Thread(new Runnable(){
#Override
public void run() {
String weatherString = QueryYahooWeather();
Document weatherDoc = convertStringToDocument(weatherString);
final MyWeather weatherResult = parseWeather(weatherDoc);
runOnUiThread(new Runnable(){
#Override
public void run() {
weather.setText(weatherResult.forecastToString());
}});
}});
myThread.start();
}
private MyWeather parseWeather(Document srcDoc){
MyWeather myWeather = new MyWeather();
//<yweather:condition.../>
Node conditionNode = srcDoc.getElementsByTagName("yweather:condition").item(0);
String weatherCode = conditionNode.getAttributes()
.getNamedItem("code")
.getNodeValue()
.toString();
// thunderstorms
if(weatherCode.equals("4")){
mHandler.post(new Runnable() {
#Override
public void run() {
// This gets executed on the UI thread so it can safely modify
// Views
image.setImageResource(R.drawable.thunderstorm);
}
});
}
//isolated thunderstorms
else if ( weatherCode.equals("37")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.thunderstorm);
}
});
}
//scattered thunderstorms
else if ( weatherCode.equals("38")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.thunderstorm);
}
});
}
//scattered thunderstorms
else if ( weatherCode.equals("39")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.thunderstorm);
}
});
}
//thundershowers
else if ( weatherCode.equals("45")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.thunderstorm);
}
});
}
//isolated thundershowers
else if ( weatherCode.equals("47")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.thunderstorm);
}
});
}
//drizzle
else if ( weatherCode.equals("9")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.rainy);
}
});
}
//showers
else if ( weatherCode.equals("11")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.rainy);
}
});
}
//showers
else if ( weatherCode.equals("12")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.rainy);
}
});
}
//scattered showers
else if ( weatherCode.equals("40")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.rainy);
}
});
}
//hail
else if ( weatherCode.equals("17")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.hail);
}
});
}
//mixed rain and hail
else if ( weatherCode.equals("35")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.hail);
}
});
}
//foggy
else if ( weatherCode.equals("20")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.foggy);
}
});
}
//haze
else if ( weatherCode.equals("21")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.foggy);
}
});
}
//smoky
else if ( weatherCode.equals("22")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.foggy);
}
});
}
//windy
else if ( weatherCode.equals("24")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.windy);
}
});
}
//cloudy
else if ( weatherCode.equals("26")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.cloudy);
}
});
}
//fair (night)
else if ( weatherCode.equals("33")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.cloudy);
}
});
}
//fair (day)
else if ( weatherCode.equals("34")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.cloudy);
}
});
}
//partly cloudy
else if ( weatherCode.equals("44")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.cloudy);
}
});
}
//mostly cloudy (night)
else if ( weatherCode.equals("27")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.night_cloudy);
}
});
}
//partly cloudy (night)
else if ( weatherCode.equals("29")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.night_cloudy);
}
});
}
//mostly cloudy (day)
else if ( weatherCode.equals("28")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.day_cloudy);
}
});
}
//partly cloudy (day)
else if ( weatherCode.equals("30")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.day_cloudy);
}
});
}
//clear(night)
else if ( weatherCode.equals("31")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.moon);
}
});
}
//sunny
else {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.sunny);
}
});
}
myWeather.conditiontext = conditionNode.getAttributes()
.getNamedItem("text")
.getNodeValue()
.toString();
myWeather.conditiontemp = conditionNode.getAttributes()
.getNamedItem("temp")
.getNodeValue()
.toString();
return myWeather;
}
private Document convertStringToDocument(String src){
Document dest = null;
DocumentBuilderFactory dbFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder parser;
try {
parser = dbFactory.newDocumentBuilder();
dest = parser.parse(new ByteArrayInputStream(src.getBytes()));
} catch (ParserConfigurationException e1) {
e1.printStackTrace();
Toast.makeText(event.this,
e1.toString(), Toast.LENGTH_LONG).show();
} catch (SAXException e) {
e.printStackTrace();
Toast.makeText(event.this,
e.toString(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(event.this,
e.toString(), Toast.LENGTH_LONG).show();
}
return dest;
}
private String QueryYahooWeather(){
String qResult = "";
String queryString = "http://weather.yahooapis.com/forecastrss?w=1062617&u=c";
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(queryString);
try {
HttpEntity httpEntity = httpClient.execute(httpGet).getEntity();
if (httpEntity != null){
InputStream inputStream = httpEntity.getContent();
Reader in = new InputStreamReader(inputStream);
BufferedReader bufferedreader = new BufferedReader(in);
StringBuilder stringBuilder = new StringBuilder();
String stringReadLine = null;
while ((stringReadLine = bufferedreader.readLine()) != null) {
stringBuilder.append(stringReadLine + "\n");
}
qResult = stringBuilder.toString();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
Toast.makeText(event.this,
e.toString(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(event.this,
e.toString(), Toast.LENGTH_LONG).show();
}
return qResult;
}
public void onListItemClick(ListView parent, View v, int position,long id)
{
Toast.makeText(this, "You have selected " + Category[position], Toast.LENGTH_SHORT).show();
}
}
You don't have the
setContentView(R.layout.YOUR_XML_NAME);
in your activity. That's why you could not connect your java class and xml file

setBackgroundResource doesn't set the image

Handler hnd = new Handler() {
#Override
public void handleMessage(Message msg) {
int id = sequence.get(msg.arg1);
if(msg.arg1 % 2 == 0) {
sq.get(id-1).setBackgroundResource(R.drawable.square_show);
} else {
sq.get(id-1).setBackgroundResource(R.drawable.square);
}
}
};
#Override
public void onResume() {
super.onResume();
Thread background = new Thread(new Runnable() {
public void run() {
try {
for(int i = 0; i < sequence.size()-1; i++) {
record_tv.setText(""+i);
Thread.sleep(200);
Message msg = hnd.obtainMessage();
msg.arg1 = i;
msg.sendToTarget();
}
} catch(Throwable t) {
}
}
});
background.start();
}
[CODE UPDATED] now it goes through the first loop and stops
do you have any idea why the code in the first runOnUiThread gets executed but it doesn't do what i want?
what i want is: change the image to "square", wait 2 seconds, change the image to "square_show", wait 2 secs and repeat the loop
i've been struggling for an hour now...
You can easily set image using following code.
sq.get(id-1).setImageResource(R.drawable.square_show);
sq.get(id-1).setImageResource(R.drawable.square);
public void show(int size) {
// CICLE THROUGH EACH SQUARE
for(int i = 0; i <= size-1; i++) {
Thread thrd = new Thread() {
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
sq.get(id-1).setImageResource(R.drawable.square_show);
// System.out.println("1st..........");
try {
sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sq.get(id-1).setImageResource(R.drawable.square);
// System.out.println("2nd..........");
try {
sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
};
thrd.start();
}
}
This is a wrong way to achieve it. This may help you.
http://developer.android.com/guide/topics/graphics/2d-graphics.html#tween-animation
I would suggest you to use a handler
int drawablebkg[] ={R.drawable.ic_launcher,R.drawable.icon};
Handler m_handler;
Runnable m_handlerTask ;
ImageView iv;
iv = (ImageView)findViewById(R.id.imageView1);
m_handler = new Handler();
m_handlerTask = new Runnable()
{
#Override
public void run() {
iv.setImageResource(android.R.color.transparent);
if(i<2)
{
ivsetBackgroundResource(drawablebkg[i]);
i++;
}
else
{
i=0;
}
m_handler.postDelayed(m_handlerTask, 2000);
}
};
m_handlerTask.run();
In onPause() of your activity
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
//_t.cancel();
m_handler.removeCallbacks(m_handlerTask);
}
Another way
iv= (ImageView)findViewById(R.id.imageView1);
AnimationDrawable animation = new AnimationDrawable();
animation.addFrame(getResources().getDrawable(R.drawable.ic_launcher), 2000);
iv.setImageResource(android.R.color.transparent);
animation.addFrame(getResources().getDrawable(R.drawable.icon), 2000);
animation.setOneShot(false);
iv.setBackgroundDrawable(animation);
//set setBackgroundDrawable(animation) is decprecreated i guess. not sure in which api
// start the animation!
animation.start();
Another way
Define background.xml in drawable folder
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false">
<item android:drawable="#drawable/ic_launcher" android:duration="2000" />
<item android:drawable="#drawable/icon" android:duration="2000" />
</animation-list>
I your activity onCreate();
ImageView iv = (ImageView)findViewById(R.id.imageView1);
iv.setBackgroundResource(R.drawable.background);
AnimationDrawable animation= (AnimationDrawable)loadingRaven.getBackground();
loadingRaven.setImageResource(android.R.color.transparent);
animation.start();
Note to stop the animation you need to call animation.stop()
Because the resource changes in the UI thread and you are sleeping your background thread. The UI thread is running normally.
Use handlers:
public class MainActivity extends Activity {
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) findViewById(R.id.button1);
}
Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (msg.arg1 % 2 == 0) {
b.setBackgroundResource(R.drawable.analytic_icon);
} else {
b.setBackgroundResource(R.drawable.ic_launcher);
}
}
};
#Override
public void onResume() {
super.onResume();
Thread background = new Thread(new Runnable() {
public void run() {
try {
for (int i = 0; i < 20; i++) {
Thread.sleep(2000);
Message msg = handler.obtainMessage();
msg.arg1 = i;
msg.sendToTarget();
}
} catch (Throwable t) {
// just end the background thread
}
}
});
background.start();
}
}
Try this,It will work:
public void show(final int size) {
Thread thrd = new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i <= size - 1; i++) {
id = (Integer) sequence.get(i);
runOnUiThread(new Runnable() {
#Override
public void run() {
sq.get(id - 1).setBackgroundResource(
R.drawable.square_show);
}
});
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
sq.get(id - 1).setBackgroundResource(
R.drawable.square);
}
});
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thrd.start();
}

Why does "msg.sendToTarget" stop the loop?

Handler hnd = new Handler() {
#Override
public void handleMessage(Message msg) {
int id = sequence.get(msg.arg1);
if(msg.arg1 % 2 == 0) {
sq.get(id-1).setBackgroundResource(R.drawable.square_show);
} else {
sq.get(id-1).setBackgroundResource(R.drawable.square);
}
}
};
#Override
public void onResume() {
super.onResume();
Thread background = new Thread(new Runnable() {
public void run() {
try {
for(int i = 0; i <= sequence.size()-1; i++) {
Thread.sleep(200);
Message msg = hnd.obtainMessage();
msg.arg1 = i;
msg.setTarget(hnd); // EDITED
msg.sendToTarget();
record_tv.setText(""+i);
}
} catch(Throwable t) {
}
}
});
background.start();
}
the code arrives to msg.sendToTarget(), does its things and then never came back
sendToTarget(); throws a null pointer exception it you have no set a receiver with setTarget(Handler).
Also, in your code I see
record_tv.setText(""+i);
this line, inside your thread will throw a
android.view.ViewRoot$CalledFromWrongThreadException

Categories

Resources