简体   繁体   中英

How to send message to main activity from broadcastreceiver

I know this is a basic question, and there a lot of similar questions on here, BUT, I've looked through dozens and they all ask their questions in a specific way, and their answer does not fix my problem.

inside my main activity class I have:

public static class GcmBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
            }
}

I want to transition to a new screen/activity when I get a certain gcm message. This needs to be done from the context of mainActivity. so how do I send a message to main activity to tell it to perform this action. I think I'm supposed to use a handler, but I dont know what the exact syntax is, in this case. I never "create" the broadcastreceiver, so I cant pass in some handler in its constructor. The BCR is set up through an intent filter through my manifest file. this is how the android tutorial on gcm has it set up, so I prefer not to create a broadcast receiver dynamically (unless its the only way).

public class GCMIntentService extends GCMBaseIntentService {

    public static final String PROJECT_ID = "345657565857";
    private static final String TAG = "GCMIntentService";
    ModelNotificationMessage modelNotificationMessage;

    public GCMIntentService() {
        super(PROJECT_ID);
        Log.d(TAG, "GCMIntentService init");
    }

    @Override
    protected void onError(Context ctx, String sError) {
        // TODO Auto-generated method stub
        Log.d(TAG, "Error: " + sError);

    }

    @Override
    protected void onMessage(Context ctx, Intent intent) {

        Log.d(TAG, "Message Received");

        String message = intent.getStringExtra("message");

        Log.d(TAG, "Message Received" + message);



                    sendNotification(message);
            Intent broadcastIntent = new Intent();
            broadcastIntent.setAction("GCM_RECEIVED_ACTION");
            broadcastIntent.putExtra("gcm", message);
            ctx.sendBroadcast(broadcastIntent);

    }

    private void sendNotification(String message) {
        // this
        String ns = Context.NOTIFICATION_SERVICE;
        NotificationManager mNotificationManager = (NotificationManager)                            getSystemService(ns);

        int icon = R.drawable.notification;
        CharSequence tickerText = message; // ticker-text
        long when = System.currentTimeMillis();
        Context context = getApplicationContext();
        CharSequence contentTitle = modelNotificationMessage.getKey();
        CharSequence contentText = message;
        Intent notificationIntent = null;

        int NOTIFICATION_ID = 9999;

                NOTIFICATION_ID = CommonVariable.notification_message;
                notificationIntent = new Intent(this, ViewMessages.class);



        // and this
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                notificationIntent, 0);
        Notification notification = new Notification(icon, tickerText, when);
        // Play default notification sound
        notification.defaults |= Notification.DEFAULT_ALL;
        notification.setLatestEventInfo(context, contentTitle, contentText,
                contentIntent);
        mNotificationManager.notify(NOTIFICATION_ID, notification);
    }

    @Override
    protected void onRegistered(Context ctx, String regId) {
        // TODO Auto-generated method stub
        // send regId to your server
        Log.d(TAG, regId);

    }

    @Override
    protected void onUnregistered(Context ctx, String regId) {
        // TODO Auto-generated method stub
        // send notification to your server to remove that regId

    }

}

then the broadcast receiver call in your mainactivity on the onresume method.

public void onResume() {

        gcmFilter = new IntentFilter();
        gcmFilter.addAction("GCM_RECEIVED_ACTION");
        viewMessages.registerReceiver(gcmReceiver, gcmFilter);

    }





// A BroadcastReceiver must override the onReceive() event.
    private BroadcastReceiver gcmReceiver = new BroadcastReceiver() {

        private String broadcastMessage;

        @Override
        public void onReceive(Context context, Intent intent) {

            broadcastMessage = intent.getExtras().getString("gcm");

            if (broadcastMessage != null && viewMessages != null) {
                // display our received message
                 onResume();
            }
        }
    };

i hope it is useful to you.

I think on receive of a GCM message you want to switch to some activity/screen. For doing so, below is the code to start an activity from your BroadcastReceiver :

public static class GcmBroadcastReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
             //start activity
             Intent i = new Intent();
             //syntax: i.setClassName("packageName","Activity to start inside packageName:);
             i.setClassName("com.test", "com.test.MainActivity");
             i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
             context.startActivity(i);  
        }
 }

Handler is a means of communication between the work thread that you are starting and the main thread.

Since you are just starting an activity, you don't need a handler to do so.

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