some user
some user

Reputation: 1775

Service not working correctly

I am trying to learn services and background threads that can update UI, here, this service is started by calling startService() method from MainActivity, the problem is: when the loop runs for a larger value of i, Toasts are not shown for all of the values (interestingly Toast made after the loop also not showing ), but this time I tested with 10/20 etc and working perfectly.

Here are codes, of MyService.java:

public class MyService extends IntentService {

    Handler mhandler;

    public MyService() {
        super("Hello");
    }

    @Override
    public void onCreate() {

        Toast.makeText(this, "Service Starting!", Toast.LENGTH_SHORT).show();
        super.onCreate();

        mhandler = new Handler();

    }


    @Override
    protected void onHandleIntent(@Nullable Intent intent) {


        mhandler.post(new Runnable() {
            @Override
            public void run() {

                int i;
                for (i = 0; i < 100; i++) {
                    Toast.makeText(MyService.this, "i is: " + i, Toast.LENGTH_SHORT).show();
                }
                Toast.makeText(MyService.this, "finally i is: "+i, Toast.LENGTH_SHORT).show();
            }
        });


    }
}

And request for some really helpful resources for very beginner on Android Services, Background Tasks, Broadcast receiver. I got developer.android.com (Not too.. helpful for beginner), www.vogella.com, etc. Thanks in advance.

Upvotes: 0

Views: 46

Answers (1)

Pythogen
Pythogen

Reputation: 640

I believe the reason you are only seeing the first few values of i is because android will not allow an application to spam the toast queue.

As mentioned by @David Wasser in the OP post's comments, Toast is not a reliable debugging tool. Use the logcat instead:

Log.v("TAG", "Message")

Upvotes: 2

Related Questions