Android :: Communicating With A Looper Thread
Feb 9, 2009I need a message queue in my background thread, so I created a looper thread.
CODE:...................
I need a message queue in my background thread, so I created a looper thread.
CODE:...................
Here is my code:
CODE:......
The problem is as follows: progressBar is showing correctly. mHandler obtains the message but only once(for the first time). But I need to make it in loop(as Looper.loop should have worked in this case), so it calls mHandler handleMessage in every loop(but its not happening in this case). The outcome progressBar kept on rotating though the condition in the handleMessage (if(location!=null) )is getting satisfied in the mean time of the active progressbar. How can I make mHandle,sendEmptyMessage to call in each loop so I can check for this (if(location!=null)) condition.
What does the following exception mean? And how can I fix it?
This is the code:Toast toast = Toast.makeText(mContext, 'Somthing', Toast.LENGTH_SHORT);
This is the exception:
D/VVM ( 684): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
D/VVM ( 684): at android.os.Handler.(Handler.java:121)
D/VVM ( 684): at android.widget.Toast.(Toast.java:68)
D/VVM ( 684): at android.widget.Toast.makeText(Toast.java:231)
I am using an Executor [fixed thread pool] with my own ThreadFactory that adds a Looper:
CODE:...............
I am running a thread that makes network requests but if the network fails I would like a dialog message to be displayed to the user. This process is rather involving since it requires making AND displaying the request in the UI thread. I can wait for the user's response to the dialog by simply adding a Loop to the network thread and wait for a message to be send from the UI thread. This allows me to encapsulate the network requests in a while(tryAgain) thread. All works well except when the Looper.loop() method is called the second time (after a second network error dialog is displayed) and a message is sent by the dialog (in the UI thread) to the network thread's handler:
CODE:.............
In the AlertDialog instance is an OnClickListener:
CODE:...............
I've checked that the thread is still active with handler.getLooper().getThread().isAlive() which always returns true but it still gives me "sending message to a Handler on a dead thread". How is it that the Message/Handler has decided that the thread is dead? Shouldn't it rely on the .isAlive() method? In the end I am trying to avoid replicating the thread management build into the Android OS .
Trying to get my head around the specific ins/outs of the Looper object and how it interacts with Threads. Documentation is rather scant on this topic. This is one of those topics that is obvious to the Android core team, but to the rest of us, it's not so obvious.
Can someone point to better documentation or give a more complete account of Looper:
1. What is looper.
2. How does the Android phone use Looper to coordinate message handling?
3. What do I need to do when I get the "Can't create handler inside thread that has not called Looper.prepare()" message?
4. How do I use LocationManager.requestLocationUpdates with Looper, and why does this call require a Looper object?
I am getting reports of 'Can't create handler inside thread that has not called Looper.prepare()' once I added ScoreNinja to my Android app, and released it to the market. It seems that it isn't happening all the time as the ScoreNinja highscore has lots of entries from users. I have looked on the web for help but there are no clear directions on what to do. I have used the ScoreNinja code exactly as shown on the scoreninja website. BTW If anyone is having problems with ScoreNinja only displaying one score, check to see if the launchmode is not set to 'singleinstance' in your manifest. This fixed it for me!
View 6 Replies View RelatedI have a doubt in Looper. I want to know when we should use Looper. If any good link for more clarification, it would be great.
View 2 Replies View RelatedI have a thread that does all my rendering code for a game (including animations). I want to be able to communicate with that thread via Messages instead of locking / synchronization. This means that I need to both support a message queue and *also* support my own rendering loop. Normally I would just clear the message queue every frame of rendering so worst case scenario the messages sit on the queue for one frame before getting cleared out. This also gives a bit of priority to messages in that if the queue backs up the rendering will take a back seat until it empties out.
Everything was going fine until I realized that Looper doesn't have a "Clear the Queue" function! I looked at the source code for Looper.loop() and it appears that the code necessary to manually traverse the MessageQueue is protected, so I can't even write the ClearQueue function myself.
Does anyone here have any feedback on how I can have a thread that keeps the MessageQueue clear at the same time as allowing me to peg the CPU rendering as many frames per second as I can?
My current thought is to insert a message into the MessageQueue along the lines of "RenderOneFrame". When this message is popped off the queue I would render one game frame. Before returning from my rendering code though I would push another copy of the RenderOneFrame message back onto the queue. This means any messages added to the queue while I was busy rendering the frame would get processed before the RenderOneFrame mesage and once the queue was "clear" (ie: RenderOneFrame message was back on top) I would repeat the process.
I suspect that this will work, though I am open to suggestions for either a clear or faster method (I'm more interested in clean at this point, but at optimization time I'll be interested in faster if I bottleneck on this code).
I'm trying to initialize OpenFeint in my game like this:
CODE:...........
Result: 1. OpenFeint initialization sometimes take so song(network actions?). It blocks the main thread. 2. My application remains in onCreate() for too long. 3. My Dev Phone One display ANR(application not responding) dialog prompting me to choose between 'Force Close' and 'Wait' 4. Soon after that, OpenFeint has done its things and my game shows up behind the dialog. 5. Now pressing 'Wait' will dismiss the ANR dialog and I can continue my game properly.
But obviously we don't want ANR dialog. So now I put it in a Thread like this:
CODE:...............
----------------------------------------------------------------------------- Result: Problem solved. Everything seems to run fine now.
I put Looper.prepare() there because my game will crash if I don't. The log message told me to put it there. I put Looper.loop(); there because OpenFeint will not initialize at all if I don't. I've read the doc about Looper but honestly I don't understand what the doc says.
Question 1. The doc also tell me this: ------------------------------------------------- public static final void loop ()
Since: API Level 1 Run the message queue in this thread. Be sure to call quit() to end the loop. -------------------------------------------------- Can anyone explain when & where should I call quit()?
Question 2 What will happen if I don't call Looper.quit()?
Question 3 Let me ask this straight. Am I taking the correct approach? Is there some kind of loop running alongside my game all the time if I do this?
I have a thread I use to periodically update the data in my Activity. I create the thread and start a looper for using a handler with postDelay(). In onDestroy() for my activity, I call removeCallbacks() on my handler.
Should I then call handler.getLooper().quit()? Or not worry about it and let the OS deal with it? Or would it just run forever then, consuming CPU cycles?
I'd like to know if Looper can enable handler to handle one message at a time, instead of handling all the messages in the queue together in one blocking call when Looper.loop() is called.
Because the looper sends all the messages in the queue to the handler one after the other in one blocking call, my application displays the ANR message. Instead, I want to be able to handle one single message, one blocking call at a time - the instant it falls into the queue.
The following code illustrates my problem: (pls note the lines referred: 1,2,3,4&5) Question 1: After calling looper.loop in line3, line4 and 5 don't run. Why is this? I tried quit(), but it doesn't help. Question 2: Instead of displaying 0,1,2,3,4 in one blocking call (at line3), I'd like to have 5 different blocking calls for each. Essentially (sorry, if i sound repetitive), I want to be able to use looper in such a way that each time, it ensures only one message gets handled.
Is there a way to do this?
CODE:..................
I ran into some trouble trying to use a Looper inside an AsyncTask (its doInBackground method). Everything works fine until new Tasks are being created by AsyncTask.sThreadFactory, but once I reach the AsyncTask.CORE_POOL_SIZE limit and AsyncTask begins to recycle the threads, sending messages to my looper (created inside doInBackground) results in a MessageQueue RuntimeException: "sending message to a Handler on a dead thread".
The code I tried was:
CODE:....................
I want to create an application in Android which communicates with a server application (written in C#, doesn't matter what version of .NET) on the PC via TCP/IP. I was thinking about some kind of RPC like SOAP or XML-RPC. But I want to keep the server application as light and simple as possible. And I think in C# you rely on a Webserver to set up an RPC server. Or maybe is it better to communicate directly via the TcpListener?
View 2 Replies View RelatedI plugged my Hero, via USB cable, into my computer. The charge light is on but my computer is not seeing the device. I have rebooted the phone and the computer and it still won't see the device.
View 1 Replies View RelatedWhether its possible for an application and a widget to communicate data to each other directly? Basically I'd need the app to be able to check that the widget is running/visible, and would need the app to send information to the widget. I'm far from actually implementing anything yet, so I'm not really looking for any overly detailed explanations, just if whether or not what I'm looking to achieve is possible.
View 2 Replies View RelatedI'm fairly new to android programming and need some information for a 4th year forensics course project. Basically I am trying to create a suite of tools for live analysis of an android phone. I know how to get the information I need on the phone, but I was wondering if there was a way to communicate that information back to the PC? I want to be able to run a program from a PC, which, when the phone is docked, will allow the user to access information about the phone (ie currently running services/processes, bluetooth/wifi connections, etc). I have a bunch of methods that will run on the phone and get all the information, but I want to be able to call those methods from the PC, execute on the phone, then have the information sent back to the PC to display to the user instead of just displaying it on the phone. This is to leave as small a footprint on the phone as possible.
View 1 Replies View RelatedI come from a .Net background and recently x-training to java.
I wanted to develop an Android application that required simple functionality to communicate with a server. For example, functionality such as post a username/score to a website (or service), or request information such as top 10 scores.
What type of communications should I focus on? What is the common technology to use? Does Java have the equivalent of WCF? Or does it have some sort of simple web service? Can web services be secured with authentication?
Ive heard other references to xml-rpc. Should this be something I should look into?
Is it possible to update a currently running activity from a BroadcastReceiver? I want to update my activity from a BroadcastReceiver that runs alongside it. When I run my app (from Eclipse), my activity starts. When the BroadcastReceiver is triggered, it currently tries to start the activity (with extras in the bundle...this is the important part), but nothing happens, presumably because the activity is already running. So my question is, how do I get the new information to my Activity (or even just tell the activity that there's new information to get if I stick the information in a database)? This seems like it should be fairly straightforward, but I'm clearly missing something.
View 3 Replies View RelatedI am communicating with PHP web services in Android application. All the requests send from android are encoded with UTF-8 and the php scripts decodes it with utf-8.
But when any request is send with apostrophe ' the decode function of php doesn't seem to work the way it should.
For example, if I send the request as "Today's Horoscope" then its utf-8 encode will be "Today%27s+Horoscope". I tried to decode this with Android and it was successful. But in php it gives the same text after decoding.
The database is MySql. Is this a problem with database or php? I am not sure about it but is there any workaround to this problem?
I want to create an application to remote control my PC.
For example: Volume (get actual volume level, increase/decrease/mute volume), TVtime (start/quit tvtime, get actual channel, toggle fulscreen, channel up/down, toggle input source, toggle aspect ratio), Amarok (start/quit amarok, get current song, prev/next song, play/stop/ pause), etc.
The application for the PC is done (in python). The communication protocol used is very simple.
For example: "volume:get_level", "volume:up", "volume:mute", etc. Now I'm working on the android application.
What I have implemented till now is to create an activity, with: - an edittext to enter host:port - a button to connect/disconnect to/from server - the onCreate method creates a new thread for socket communication to send/receive messages to/from PC. - a textview to display information received from PC (eg. volume level) - a button to send command to PC I'm using handler to communicate between the tcpclient thread and the main activity.
It is working... But I want to use more than 1 activity. I want to use different activity for every program controlled. Searching for a solution to transfer the thread's handler to a new activity I have found that it is not possible, and I have to use a service.
So, my question is: how to send message from different activities to the same service, how to send message from service to the actual activity and how can I check in the service which is the actual activity? Because the service is running in the same thread as the activities I suppose that I still have to create a new thread for socket communication. How can I send the data received by the socket to the service?
Lets say I have 2 mobile phones which are 50 meters away from each other and I would like to send a very small packet of data from mobile-A to mobile-B, without using any communication to cellular tower. To make it simpler, I would like to build an app which implements a Peer to Peer connection for 2 mobiles in the same radius (in the same area). Is this feasible using the technology of smartphones these days?
View 2 Replies View RelatedI'm thinking about an Android app (with possibly an accompanying physical device), and i'm trying to figure out whether this is something that's feasible.
1) Let's say I plug my Android to my PC. Would it be possible for an app installed on the PC to communicate with an app running in the cell phone? I just need a very simplistic data exchange, it can even be one-way (just data pushed from the cell phone to the listening app on the PC, whenever the cell phone wants, I don't need any data sent from PC to phone).
When I plug it in, the phone gives me 4 options (charge, disk drive, HTC sync, tethering), which makes me think this is not doable, but still worth the shot.
2) Would it be possible for an app on the PC to talk to an app on the phone through any other way? (Wi-fi, bluetooth, etc). I'm guessing no on wi-fi since neither party has the other's IP (and I want this to kinda just work, not having to input IPs manually all the time).
3) If I make a device that's plugged to the little USB port at the bottom of the phone (and let's say this is a magical device that can do anything, I don't quite care about those details as long as it's doable). Can I have an Android app talk to that device?
4) Any other ideas to make the phone talk to a "device" that I make, or to an app in the PC are more than welcome. Going "through the web" could be an option (although there'd have to be a central server that I own as a middle man, I believe). But i'd prefer if the communication was direct between the two devices.
How can I implement a run() method of thread if I create a Thread Global?
I mean If I create a Thread Globally then can I implement its run() method {" public void run()"} anywhere in my Application?
In the run() method I have to write the code to perform some action.
IF I can do it then please can anyone show me briefly how to do it particularly.
I am writing an application in which i need to handle messages between the main thread(the deafult UI related thread) and the user created Gamethread.
The requirement is like this.
An activity(say "Activity_X") is setting the view by "setContentView(some "View_Y")". In "Activity_X" i have implemeted "onCreateOptionsMenu()" and "onOptionsItemSelected()" fucntions for creating menus & a switch case for action to be taken on selecting those menus.Menu has items like "resume/pause/zoom/" .
All action to be take on selecting these menus are implemented in "View_Y" in a separate Gamethread by extending "Thread" class.
So whenever a menu is selected in "Activity_X" i need to send a message to "View_Y". And on receiving this ,a particular action/method should be called in View_Y(GameThread).
How can i achieve this using Handlers?Is there any other way of doing this? Please do share with me some code snippets for these.
I have recently lost my voice, and wanted to know if there was a way or an app that I can use to type on my Samsung Mobile, messages or words and transmit them to show up on my tablet? via Wi-Fi, Bluetooth. It would make my life so much easier to communicate with people next to instead of passing the mobile around.
View 2 Replies View RelatedI have a separate thread running to get data from the internet. After that, I would like to update the ListView in the main thread by calling adapter.notifyDataSetChanged(). But it does not work. Any workaround for that?
View 1 Replies View RelatedI want to do the drawing in another thread to speed up the game(it is way to slow right now). I was told to do this but don't quite understand why that would speed things up. Is it GameView that should implement Runnable? Should I make the thread sleep when not drawing? where should I start the thread? package com.android.WWS;
import android.app.Activity; import android.content.Context; import android.graphics.*; import android.os.Bundle; import android.view.SurfaceView; import android.view.KeyEvent; import android.view.View; import android.view.View.OnKeyListener; import java.lang.Runnable; import java.lang.Thread;...................
For the past few weeks ive been trying to do a software update on my phone. i know 2.2 isnt available yet, but i just wanted to give it a try for sh!ts n giggles. my old captivate that i returned was able to connect to the att server and gave me a message saying that there are no updates available. the new captivate i have wont even connect to the att server. it sucks that i have to wait 24hours until i can try again. everytime ive done it, it gives me that error message. anyone else having this issue? i thought being rooted and having the one click lag fix was the problem so i undid the lag fix and unrooted, but i still got the same error message. im worried that when 2.2 is available, i wont be able to get it since i cant even connect to the att server.
View 6 Replies View RelatedI know that the stuff regarding the secure element inside certain phones is kept on a strictly need-to-know basis and Google only lets certain people have access, but how about the apps that are running on the phone, such as Google Wallet?
What I mean is, is it possible to write an App that communicates with something like Google Wallet (not necessarily this app specifically) instead of an NFC device? At its simplest, when you pass your phone over a credit card terminal, it communicates via the NFC chip to the wallet application. What I'm looking to do is bypass that terminal and just communicate directly with the app via another app, sending the necessary commands directly. Is this possible? (If so, I'm not looking for a how-to, just if it's doable or not).
I know it might be complicated and there's a lot to learn, APDU commands and all that - that's fine.
I need to suspend/resume a thread from another thread in the same process. I tried to look into thread apis,but I couldn't figured out a way to achieve this.Can anyone pls point me some references to look or give a tip to do this.
View 2 Replies View Related