• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Toast message not showing in service

cchang

Lurker
Hi! I'm having trouble coding a service example. My service is a very simple one that only displays a message at a given interval. Here's my code:

AndroidManifest.xml

<service android:name=".BuggingService" android:enabled="true" />

BuggingService.java

public class BuggingService extends Service {
private Timer timer;
private int counter;
private TimerTask executeAgain = new TimerTask() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), "I poop on you", Toast.LENGTH_LONG).show();
}
};

@Override
public void onCreate() {
timer = new Timer("buggingService");
timer.scheduleAtFixedRate(executeAgain, 0, 5000);
}

@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}

Hello.class

startService(new Intent(this, BuggingService.class));

The service is running, but the message is never displayed and I don't understand why. If I debug my service the timer is executing every 5 seconds. Can anyone offer an explanation for this?

Thanks in advance.
 
I'd like an answer to this too. Mine is slightly different that this (I'm calling from another thread), but close enough that I think it's the same problem.
 
I'm sorry, but I have the same problem, and this tip does'n hepl me.
I write this code:
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}

@Override
public void onCreate()
{
super.onCreate();


timer.scheduleAtFixedRate(
new TimerTask() {
public void run() {
getAdsFromServer();
}
},
0,
UPDATE_INTERVAL);
}

private void getAdsFromServer()
{
Log.v("stop11", "stop11");
Looper.prepare();
Toast.makeText(etApplicationContext(), "I poop on you", Toast.LENGTH_LONG).show();
Looper.loop();
}

But even Log.v in this case write in log only one time.

If I doesn't use Looper, Log.v working, but toasts doesn't show.
 
Try this:
//a member
private Handler handler;

//
public void onCreate() {
...
handler = new Handler(Looper.getMainLooper());
...
timer.scheduleAtFixedRate(
new TimerTask() {
public void run() {
getAdsFromServer();
}
},
0,
UPDATE_INTERVAL);
}

private void getAdsFromServer()
{
Log.v("stop11", "stop11");

handler.post(new Runnable() {

public void run() {
Toast.makeText(etApplicationContext(), "I poop on you", Toast.LENGTH_LONG).show();
}
});


}
 
Back
Top Bottom