Reputation: 16622
I've a class named by MyService which extends Service below. Everything will be ran until
I remove the Toast.makeText...
line in the run method of Thread.
Why? And how can I get access to the Activity components from the run method of Thread class?
public class MyService extends Service {
@Override
public IBinder onBind(Intent intent) { return null; }
@Override
public void onCreate() {
Toast.makeText(this, "This msg will be shown", Toast.LENGTH_LONG).show();
Log.d("Bilgi", "This msg will be shown.");
super.onCreate();
}
@Override
public void onStart(Intent intent, int startId) {
Toast.makeText(this, "This msg will be shown", Toast.LENGTH_LONG).show();
super.onStart(intent, startId);
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
try {
Log.d("This msg will ","be shown"); //if I remove next line
Toast.makeText(this, "This msg will NOT be shown", Toast.LENGTH_LONG).show();
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, 5000, 8000);
}
Upvotes: 0
Views: 2370
Reputation: 15755
The UI widgets are not thread-safe so you can not update the the UI widget unless in the Main(UI) Thread , in your case, making Toast
is in another thread which is forbidden.
You may need to use something like Handler
, and use Messenger
to send message to the handler created in the activity UI thread. And then deal with the widgets in method handleMessage(Message msg)
.
Upvotes: 0
Reputation: 1006624
And how can I get access to the Activity components from the run method of Thread class?
You don't. Use Messenger
to send Message
objects from the service to the activity's Handler
. The activity -- and only the activity -- can update its widgets, and that only from the main application thread.
Here is a sample application demonstrating this.
Upvotes: 1
Reputation: 5212
When creating the Toast, pass in the ApplicationContext which you can get through getApplicationContext()
Upvotes: 0
Reputation: 10948
Don't use Threads - use AyncTasks. Also, you shouldn't be accessing the Activity methods/UI through threads/tasks. Take a look at the first link to get an idea of how the Activity and its "threads" work together.
Upvotes: 1
Reputation: 12366
The only method I know is to use broadcast receiver inside your activity, which will catch you messages and update UI or whatever you want.
Upvotes: 0