1

I am quite busy with a new application. However I created a service which calls a method like this:

MessageProcessor mp = new MessageProcessing(MessageService.this);
wa.setNewMessageBind(mp);

However since it's added into a service instead of an Activity this error shows up:

nl.giovanniterlingen.whatsapp.MessageService cannot be cast to android.app.Activity

And yes, I searched a lot on the internet, but still I couldn't find an answer that fits my need. Here is the MessageProcessing source:

((Activity) context).runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(
                            context,
                            msg.getFrom() + "(" + msg.getGroupId() + "): "
                                    + msg.getText(), Toast.LENGTH_SHORT)
                            .show();
                }
            });

When I replace the toast with system.out like this:

System.out.println(msg.getFrom() + "(" + msg.getGroupId()
                    + "): " + msg.getText());

Then it's working fine, but I want a toast so that's why I am asking.

For a more clearer view see my Github and the latest commits from 09-07-2015

https://github.com/gi097/WhatsApi-Android

3 Answers3

1

You can't cast your MessageService, which extends Service, to a Activity.

You need to access your UiThread from a Service. Check this question, maybe it'll help you: Accessing UI thread handler from a service

Handler handler = new Handler(Looper.getMainLooper());

handler.post(something_to_run_on_main_thread);
Community
  • 1
  • 1
B. Kemmer
  • 1,517
  • 1
  • 14
  • 32
0

You can use

Handler handler = new Handler(Looper.getMainLooper());
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(context, "Your msg here" + msg.getText(), Toast.LENGTH_LONG);
                    }
                });
architjn
  • 1,397
  • 2
  • 13
  • 30
-1

private Toast myToast; // Declare as Field

myToast = Toast.makeText(this, "DummyMessage", Toast.LENGTH_LONG); // In onCreate(Bundle b)

myToast.setText("yourActualMessage");    // set msg Inside service or whatever

myToast.show();                    // Display in service or anywhere you want
Azim Ansari
  • 1,378
  • 11
  • 20