简体   繁体   中英

Display GCM message in Android

I code app for android, which will communicate with GCM. I can get message, but I would like to display it on screen and get error.
There is my code, I have problem in line Activity act = (Activity) context;
I get error "The JAR of this class file belong to container 'Android dependencies' which does not allow modifications to source attachments on its entries "

@Override
protected void onMessage(Context context, Intent indent) {

    String message = indent.getExtras().getString("message").toString();

    Log.i(TAG, "new message= " + message);

    Activity act = (Activity) context;  
    if(act != null)
    {
        TextView pushNotification = (TextView) act.findViewById(R.id.txtPushNotify);    
        pushNotification.setText(message);
    }
}

What I make wrong?? This method is in class

public class GCMIntentService extends GCMBaseIntentService {...}

There is my LogCat

FATAL EXCEPTION: IntentService[GCMIntentService-19193409722-1] java.lang.ClassCastException: android.app.Application
at com.sagar.gcma.GCMIntentService.onMessage(GCMIntentService.java:41)
at com.google.android.gcm.GCMBaseIntentService.onHandleIntent(GCMBaseIntentService.java:223)
at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:59)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.os.HandlerThread.run(HandlerThread.java:60)

Try following code.

Intent myIntent = new Intent(context.getApplicationContext(), YourActivity.class);
Bundle bundle = new Bundle();
bundle.putString("message", message);
myIntent.putExtras(bundle);
context.getApplicationContext().startActivity(myIntent);

Then write message displaying code inside that activity .

The error message "The JAT of this class file belong to container 'Android dependencies' which does not allow modifications to source attachments on its entries" seems to be (somehow) unrelated to me, as it is a error message generated by the IDE, unrelated to your actual code.

I would be careful with the cast in the code:

Activity act = (Activity) context;  

Are you certain that the passed context is in fact (in any case) your activity?

Edit:

Reading your edit, I can confirm that the context you receive is your application, not the activity.

And you somehow need to relay that message (which your service receives) to a foreground activity (if active). If there is no foreground activity, use a notification or something similar.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM