开发者

Pass extra data to C2DMReceiver during C2DM register process?

I'm setting up C2DM on an existing client/server Android application. The app already has an established set of classes for communicating with a server, logging a user in, and maintaining an authentication token for use with the server.

Following the documentation, I added the code to register for C2DM and created a BroadcastReceiver to receive the responses. Within my BroadcastR开发者_Go百科eceiver, I am getting a call to the onReceive() method which contains the registration ID. I can see it in the debugger and log it to the console.

The problem is that I now need to send the ID to my server, but I cannot, because I have no access to the rest of my application. BroadcastReceiver is not an Intent or a Context or anything else I'm familiar with. I could work around this if I just had the user's authentication token, but I can't get that either. I tried passing it in as an extra to the registration intent, but it gets lost along the way.

What is the right way to obtain extras or application context in the onReceive() method?

Thanks, Frank


There are a few good resources on this which this is taken from:

@Override
public void onReceive(Context context, Intent intent)
{
    String action = intent.getAction();
    Log.d(TAG, "Got a reply from Google");
    if (action.equals(REGISTER_ACTION))
    {
        handleRegistration(context, intent);
    }
    else if (action.equals(RECEIVE_ACTION))
    {
        handleMessage(context, intent);         
    }
    else
    {
        Log.w(TAG, "Unexpected intent: " + intent);
    }
}


private void handleRegistration(Context context, Intent intent)
{
    String registrationId = intent.getStringExtra("registration_id");
    String error = intent.getStringExtra("error");
    String unregistered = intent.getStringExtra("unregistered");
    if (error != null)
    {
        Log.e(TAG, "Registration failed: " + error);
        this.getApp(context).disablePush();
    }
    else if (unregistered != null)
    {            
        Log.d(TAG, "Unregistered: " + unregistered);            
        context.startService(new Intent(RegistrationService.COMPLETE_UNREGISTER_ACTION));
    }
    else if (registrationId != null)
    {            
        Log.d(TAG, "Registered with registration ID [" + registrationId + "]");            
        // Send registrationId to the Application Server in a separate thread.
        Intent i = new Intent(RegistrationService.COMPLETE_REGISTER_ACTION);            
        i.putExtra("regId", registrationId);
        context.startService(i);
    }
    else
    {            
        Log.d(TAG, "Other registration response: " + intent.getExtras());            
    }
}

For more reading see Marakana

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜