问题
I have a problem. I'm using a FileObserver
, which moves new files from the watched directories to another, former specified directory. In my thoughts there should be shown a toast message that says 'File xy has been moved', as long as the observer watches the directory, also if the applications is only in the background. But I didn't get it working.
It always tells me, that there is a RuntimeException
, and that it cannot been done without calling Looper.prepare()
.
05-11 13:21:28.484: WARN/System.err(3397): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
I tried the way with using an handler too, but I also didn't get it to work.
Has someone else an idea? Thanks in advance.
Best regards, Tobi
回答1:
Obviously, your FileObserver runs(or is) another thread. You can not modify the UI from non-UI thread. Pass a Handler to your FileObserver and send messages from it. Read about Handlers.
回答2:
Before your Toast statement add the following :
runOnUiThread(new Runnable() {
public void run()
{
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
});
This will make it run on UI thread. Hope this helps.
回答3:
What are you using for the context of the Toast message? That will have to have a way to display something on the screen.
回答4:
Put the following code in your class:
// Need handler for callbacks to UI Threads
// For background operations
final Handler mHandler = new Handler();
// Create Runnable for posting results
final Runnable mUpdateResults = new Runnable() {
public void run() {
// Show the toast here.
}
};
and in your fileobserver's thread call place following fragment of code:
mHandler.post(mUpdateResults);
and don't use the getApplicationContext()
instead try YourClassPhysicalName.java
for the context of the Toast.
来源:https://stackoverflow.com/questions/5963438/toast-from-fileobserver