接收到库项目的推送通知(库项目中的Android C2DM)

接收到库项目的推送通知(库项目中的Android C2DM),android,push-notification,android-c2dm,white-labelling,Android,Push Notification,Android C2dm,White Labelling,我有一个项目作为另一个项目的库,因为我需要为它添加白标签(其他合作伙伴需要更多项目)。在图书馆项目中,我实现了推送通知系统。我把图书馆项目作为一个正常的项目来执行,推动工作就像一个魅力。我的问题发生在我将此项目作为库导入另一个项目时。从未呼叫过接收者 有一个帖子有同样的问题,但解决方案对我不起作用。我快疯了 主要问题是我没有收到来自C2DM的消息。我的代码是下一个: 这两个项目的清单(我在两个项目中都有相同的代码)(我使用标签lib_项目和app_项目来明确): } Ant这是我的C2DM接收

我有一个项目作为另一个项目的库,因为我需要为它添加白标签(其他合作伙伴需要更多项目)。在图书馆项目中,我实现了推送通知系统。我把图书馆项目作为一个正常的项目来执行,推动工作就像一个魅力。我的问题发生在我将此项目作为库导入另一个项目时。从未呼叫过接收者

有一个帖子有同样的问题,但解决方案对我不起作用。我快疯了

主要问题是我没有收到来自C2DM的消息。我的代码是下一个:

这两个项目的清单(我在两个项目中都有相同的代码)(我使用标签lib_项目和app_项目来明确):

}

Ant这是我的C2DM接收器:

public class C2DMReceiver extends C2DMBaseReceiver {

public static final String EXTRA_DATETIME = "datetime";
public static final String EXTRA_CAM_ID = "cam_id";
public static final String EXTRA_TYPE = "type";
public static final String GCM_PROJECT_ID = "58312821729";


public static void getC2DMRegistration(Context context){
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO){
        String id = C2DMessaging.getRegistrationId(context);
        if(id.equals(""))
            C2DMessaging.register(context, C2DMReceiver.GCM_PROJECT_ID);
        else                
            C2DMReceiver.registerPushDevice(context, id);

        Log.d("restored id: " + id);
    }
}

public static String getDeviceID(Context context){
    String out = null;

    try {
        TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(TELEPHONY_SERVICE);
        out = telephonyManager.getDeviceId();
    } catch (Exception e) {
        Log.w("Error getting device uid", e);
    }

    return out;
}

public static void registerPushDevice(Context context, String registrationId){
    try {
        CameraManager app = null;
        if(context instanceof Activity)
        {
            app = (CameraManager)(((Activity)context).getApplication());
        }
        else if(context instanceof Service)
        {
            app = (CameraManager)(((Service)context).getApplication());
        }
        else if(context instanceof Application)
        {
            app = (CameraManager)context;
        }

        if(app != null && app.isLoggedIn())
        {
            HashMap<String, String> keyValues = new HashMap<String, String>(app.getUserSessionKeys());
            keyValues.put("imei", getDeviceID(context));
            keyValues.put("registration_id", registrationId);
            keyValues.put("application_id", context.getString(R.string.application_id));
            keyValues.put("gcm", "true");

            new ServerCall(context, Script.MOBILE, Method.ADD_REGISTRATION_ID, keyValues, null)
            .execute();
        }
    } catch (Exception e) {
        Log.e("Failed to register C2DM", e);
    }
}

public C2DMReceiver() {
    super(GCM_PROJECT_ID);
}

@Override
public void onRegistered(Context context, String registrationId) {
    Log.i("onRegistered: " + registrationId);
    registerPushDevice(context, registrationId);
}

@Override
public void onUnregistered(Context context) {
    Log.i("onUnregistered");
}

@Override
public void onError(Context context, String errorId) {
    Log.w("onError: " + errorId);
}

@SuppressWarnings("unchecked")
@Override
protected void onMessage(Context context, Intent receiveIntent){

    Bundle extras = receiveIntent.getExtras();

    CameraManager app = null;
    if(context instanceof Activity)
    {
        app = (CameraManager)(((Activity)context).getApplication());
    }
    else if(context instanceof Service)
    {
        app = (CameraManager)(((Service)context).getApplication());
    }
    else if(context instanceof Application)
    {
        app = (CameraManager)context;
    }

    boolean activateNotificationsphone = app.getUserStorage().getBoolean(Constants.PUSH_NOTIFI_ACTIVATE_FROM_PHONE, true);

    if(extras != null && activateNotificationsphone)
    {
        Log.e(""+extras.keySet());
        Iterator<String> i = extras.keySet().iterator();
        while(i.hasNext())
        {
            String key = i.next();

            if(key.equalsIgnoreCase(Constants.EXTRA_ALARM_MOTION) || key.equalsIgnoreCase(Constants.EXTRA_CAMERA_DOWN) || key.equalsIgnoreCase(Constants.EXTRA_LSU_DOWN))
            {
                NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                Notification notification = new Notification(R.drawable.ic_launcher, context.getString(R.string.app_name), System.currentTimeMillis());

                Intent notificationIntent = new Intent(context, FragmentTabs.class);

                String type = key.toUpperCase();
                String value = receiveIntent.getStringExtra(key);
                String collapse_key = receiveIntent.getStringExtra("collapse_key");

                String message = "";
                String[] pair = value.split("[:]");


                if(pair.length == 2)
                {
                    notificationIntent
                    .putExtra(EXTRA_TYPE, type)
                    .putExtra(EXTRA_CAM_ID, pair[0])
                    .putExtra(EXTRA_DATETIME, pair[1])
                    .setAction(collapse_key);

                    Log.e("Type c2dm:"+type);
                    Log.e("Cam ID c2dm: " + pair[0]);
                    Log.e("DateTime c2dm: " + pair[1]);

                    ArrayList<CamerasFeedItem> cameras = null;
                    XMLObject settings = null;
                    ArrayList<EventItem> listEvents = null;
                    User user = null;
                    try 
                    {
                        user = (User)Utils.deserializeObject(new File(getFilesDir(), CameraManager.USER_OBJ_FILE));
                        cameras = (ArrayList<CamerasFeedItem>)Utils.deserializeObject(new File(getFilesDir(), user.getUserId() + "_" + CameraManager.CAMERAS_OBJ_FILE));
                        settings = (XMLObject)Utils.deserializeObject(new File(getFilesDir(), user.getUserId() + "_" + CameraManager.SETTINGS_OBJ_FILE));

                        //List of events:
                        if(user!=null)
                        {
                            listEvents = (ArrayList<EventItem>)Utils.deserializeObject(new File(getFilesDir(), user.getUserId() + "_" + CameraManager.LIST_EVENTS_OBJ_FILE));
                        }
                    } 
                    catch (Exception e) 
                    { }

                    CamerasFeedItem item = null;
                    if(settings == null || cameras == null || (item = isItemExists(cameras, pair[0])) == null)
                    {
                        return;
                    }


                    if(type.equals(Constants.EXTRA_ALARM_MOTION))
                    {
                        if(settings.getValue("motion", "no").equals("no"))
                        {
                            return;
                        }
                        GregorianCalendar curTime = new GregorianCalendar();
                        long offset = curTime.get(Calendar.ZONE_OFFSET) + curTime.get(Calendar.DST_OFFSET);
                        Calendar c = Calendar.getInstance();
                        c.setTimeZone(TimeZone.getTimeZone("UTC"));
                        c.setTimeInMillis(Long.parseLong(pair[1]) + offset);

                        String when = DateFormat.format("dd-MM-yyyy kk:mm:ss", c).toString();

                        message = context.getString(R.string.push_motion_on_camera, item.getName(), when);
                    }
                    else if(type.equals(Constants.EXTRA_CAMERA_DOWN))
                    {
                        if(settings.getValue("cameraDown", "no").equals("no"))
                        {
                            return;
                        }
                        message = context.getString(R.string.push_camera_is_down, item.getName(), getDownString(pair[1]));
                        //typeIndex = 1;
                    }
                    else if(type.equals(Constants.EXTRA_LSU_DOWN))
                    {
                        //typeIndex = 3;
                        message = "";
                    }
                }

                if(!message.equals(""))
                {
                    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION | Intent.FLAG_ACTIVITY_CLEAR_TOP);

                    notification.defaults |= Notification.DEFAULT_SOUND;
                    notification.flags |= Notification.FLAG_AUTO_CANCEL;

                    RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.notification);
                    contentView.setTextViewText(R.id.title, context.getString(R.string.app_name));
                    contentView.setTextViewText(R.id.text, message);
                    notification.contentView = contentView;
                    notification.contentIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), notificationIntent, 0);

                    mNotificationManager.notify(collapse_key, (int)Math.random(), notification);
                }  

                return;
            }
        }
    }   
}

private CamerasFeedItem isItemExists(ArrayList<CamerasFeedItem> cameras, String id){        
    for(CamerasFeedItem item: cameras)
    {
        if(item.getID().equals(id))
        {
            return item;
        }

        if(item.isFolderItem())
        {
            LSUItem lsu = ((FolderItem)item).getLsuItem();

            if(lsu != null && lsu.getID().equals(id))
            {
                return lsu;
            }               
            CamerasFeedItem result = isItemExists(CamerasFeedItem.parse(item), id);
            if(result != null)
            {
                return result;
            }
        }
    }

    return null;
}

private String getDownString(String hours){
    StringBuilder out = new StringBuilder();
    int total = Integer.parseInt(hours);

    int m = total / 720;
    total = total % 720;        

    int w = total / 168;
    total = total % 168; 

    int d = total / 24;
    total = total % 24;

    if(m > 0)
    {
        out.append(getResources().getQuantityString(R.plurals.push_month, m, m));
        out.append(" ");
    }
    if(w > 0)
    {
        out.append(getResources().getQuantityString(R.plurals.push_weeks, w, w));
        out.append(" ");
    }
    if(d > 0)
    {
        out.append(getResources().getQuantityString(R.plurals.push_days, d, d));
        out.append(" ");
    }
    if(total > 0)
    {
        out.append(getResources().getQuantityString(R.plurals.push_hours, total, total));
        out.append(" ");
    }

    return out.toString().trim();
}
最后一个:C2D消息:

public class C2DMessaging {
public static final String EXTRA_SENDER = "sender";
public static final String EXTRA_APPLICATION_PENDING_INTENT = "app";
public static final String REQUEST_UNREGISTRATION_INTENT = "com.google.android.c2dm.intent.UNREGISTER";
public static final String REQUEST_REGISTRATION_INTENT = "com.google.android.c2dm.intent.REGISTER";
public static final String LAST_REGISTRATION_CHANGE = "last_registration_change";
public static final String BACKOFF = "backoff";
public static final String GSF_PACKAGE = "com.google.android.gsf";

// package
static final String PREFERENCE = "com.google.android.c2dm";

private static final long DEFAULT_BACKOFF = 30000;

/**
 * Initiate c2d messaging registration for the current application
 */
public static void register(Context context, String senderId) {
    try {
        Intent registrationIntent = new Intent(REQUEST_REGISTRATION_INTENT);
        registrationIntent.setPackage(GSF_PACKAGE);
        registrationIntent.putExtra(EXTRA_APPLICATION_PENDING_INTENT, PendingIntent.getBroadcast(context, 0, new Intent(), 0));
        registrationIntent.putExtra(EXTRA_SENDER, senderId);
        context.startService(registrationIntent);
    } catch (Exception e) {
        Log.w("Couldn't use C2DM, check OS version", e);    
    }
}

/**
 * Unregister the application. New messages will be blocked by server.
 */
public static void unregister(Context context) {
    Intent regIntent = new Intent(REQUEST_UNREGISTRATION_INTENT);
    regIntent.setPackage(GSF_PACKAGE);
    regIntent.putExtra(EXTRA_APPLICATION_PENDING_INTENT, PendingIntent.getBroadcast(context, 0, new Intent(), 0));
    context.startService(regIntent);
}

/**
 * Return the current registration id.
 *
 * If result is empty, the registration has failed.
 *
 * @return registration id, or empty string if the registration is not complete.
 */
public static String getRegistrationId(Context context) {
    final SharedPreferences prefs = context.getSharedPreferences(
            PREFERENCE,
            Context.MODE_PRIVATE);
    String registrationId = prefs.getString("dm_registration", "");
    return registrationId;
}

public static long getLastRegistrationChange(Context context) {
    final SharedPreferences prefs = context.getSharedPreferences(
            PREFERENCE,
            Context.MODE_PRIVATE);
    return prefs.getLong(LAST_REGISTRATION_CHANGE, 0);
}

static long getBackoff(Context context) {
    final SharedPreferences prefs = context.getSharedPreferences(
            PREFERENCE,
            Context.MODE_PRIVATE);
    return prefs.getLong(BACKOFF, DEFAULT_BACKOFF);
}

static void setBackoff(Context context, long backoff) {
    final SharedPreferences prefs = context.getSharedPreferences(
            PREFERENCE,
            Context.MODE_PRIVATE);
    Editor editor = prefs.edit();
    editor.putLong(BACKOFF, backoff);
    editor.commit();

}

// package
static void clearRegistrationId(Context context) {
    final SharedPreferences prefs = context.getSharedPreferences(
            PREFERENCE,
            Context.MODE_PRIVATE);
    Editor editor = prefs.edit();
    editor.putString("dm_registration", "");
    editor.putLong(LAST_REGISTRATION_CHANGE, System.currentTimeMillis());
    editor.commit();

}

// package
static void setRegistrationId(Context context, String registrationId) {
    final SharedPreferences prefs = context.getSharedPreferences(
            PREFERENCE,
            Context.MODE_PRIVATE);
    Editor editor = prefs.edit();
    editor.putString("dm_registration", registrationId);
    editor.commit();

  }
}

您的问题在于此方法:

static void runIntentInService(Context context, Intent intent) {
    if (mWakeLock == null) {
        // This is called from BroadcastReceiver, there is no init.
        PowerManager pm = 
            (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, 
                WAKELOCK_KEY);
    }
    mWakeLock.acquire();

    // Use a naming convention, similar with how permissions and intents are 
    // used. Alternatives are introspection or an ugly use of statics. 
    String receiver = context.getPackageName() + ".C2DMReceiver";
    intent.setClassName(context, receiver);

    context.startService(intent);

}
在下一行中,
context.getPackageName()
返回应用程序的包(
com.app\u project.android

但是,
.C2DMReceiver
位于您的库项目(
com.lib_project.android
)中,这就是为什么在您尝试从应用程序使用库项目时找不到此类的原因

解决此问题的方法是明确引用
C2DMReceiver
类:

String receiver = C2DMReceiver.class.getName ();

首先,如果应用程序包是
com.app\u project
,那么权限应该是
com.app\u project.permission.C2D\u MESSAGE
(不带android)。接收器中的类别也是如此。除此之外,请显示广播接收器的代码。包名为com.app_project.android和com.lib_project.android.Eran,有一个问题,但是否可能?我在尝试一些可行或不可行的事情?谢谢Shuan,当然有可能。看看我的答案。曼恩!!这就是问题所在…真的非常感谢Eran…给我的应用程序添加白标签将其导入库将为我节省很多时间。现在我可以使用ant命令使用白标签了,推送通知将不需要将任何java文件导入到白标签项目中就可以工作了……谢谢Eran
public class C2DMReceiver extends C2DMBaseReceiver {

public static final String EXTRA_DATETIME = "datetime";
public static final String EXTRA_CAM_ID = "cam_id";
public static final String EXTRA_TYPE = "type";
public static final String GCM_PROJECT_ID = "58312821729";


public static void getC2DMRegistration(Context context){
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO){
        String id = C2DMessaging.getRegistrationId(context);
        if(id.equals(""))
            C2DMessaging.register(context, C2DMReceiver.GCM_PROJECT_ID);
        else                
            C2DMReceiver.registerPushDevice(context, id);

        Log.d("restored id: " + id);
    }
}

public static String getDeviceID(Context context){
    String out = null;

    try {
        TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(TELEPHONY_SERVICE);
        out = telephonyManager.getDeviceId();
    } catch (Exception e) {
        Log.w("Error getting device uid", e);
    }

    return out;
}

public static void registerPushDevice(Context context, String registrationId){
    try {
        CameraManager app = null;
        if(context instanceof Activity)
        {
            app = (CameraManager)(((Activity)context).getApplication());
        }
        else if(context instanceof Service)
        {
            app = (CameraManager)(((Service)context).getApplication());
        }
        else if(context instanceof Application)
        {
            app = (CameraManager)context;
        }

        if(app != null && app.isLoggedIn())
        {
            HashMap<String, String> keyValues = new HashMap<String, String>(app.getUserSessionKeys());
            keyValues.put("imei", getDeviceID(context));
            keyValues.put("registration_id", registrationId);
            keyValues.put("application_id", context.getString(R.string.application_id));
            keyValues.put("gcm", "true");

            new ServerCall(context, Script.MOBILE, Method.ADD_REGISTRATION_ID, keyValues, null)
            .execute();
        }
    } catch (Exception e) {
        Log.e("Failed to register C2DM", e);
    }
}

public C2DMReceiver() {
    super(GCM_PROJECT_ID);
}

@Override
public void onRegistered(Context context, String registrationId) {
    Log.i("onRegistered: " + registrationId);
    registerPushDevice(context, registrationId);
}

@Override
public void onUnregistered(Context context) {
    Log.i("onUnregistered");
}

@Override
public void onError(Context context, String errorId) {
    Log.w("onError: " + errorId);
}

@SuppressWarnings("unchecked")
@Override
protected void onMessage(Context context, Intent receiveIntent){

    Bundle extras = receiveIntent.getExtras();

    CameraManager app = null;
    if(context instanceof Activity)
    {
        app = (CameraManager)(((Activity)context).getApplication());
    }
    else if(context instanceof Service)
    {
        app = (CameraManager)(((Service)context).getApplication());
    }
    else if(context instanceof Application)
    {
        app = (CameraManager)context;
    }

    boolean activateNotificationsphone = app.getUserStorage().getBoolean(Constants.PUSH_NOTIFI_ACTIVATE_FROM_PHONE, true);

    if(extras != null && activateNotificationsphone)
    {
        Log.e(""+extras.keySet());
        Iterator<String> i = extras.keySet().iterator();
        while(i.hasNext())
        {
            String key = i.next();

            if(key.equalsIgnoreCase(Constants.EXTRA_ALARM_MOTION) || key.equalsIgnoreCase(Constants.EXTRA_CAMERA_DOWN) || key.equalsIgnoreCase(Constants.EXTRA_LSU_DOWN))
            {
                NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                Notification notification = new Notification(R.drawable.ic_launcher, context.getString(R.string.app_name), System.currentTimeMillis());

                Intent notificationIntent = new Intent(context, FragmentTabs.class);

                String type = key.toUpperCase();
                String value = receiveIntent.getStringExtra(key);
                String collapse_key = receiveIntent.getStringExtra("collapse_key");

                String message = "";
                String[] pair = value.split("[:]");


                if(pair.length == 2)
                {
                    notificationIntent
                    .putExtra(EXTRA_TYPE, type)
                    .putExtra(EXTRA_CAM_ID, pair[0])
                    .putExtra(EXTRA_DATETIME, pair[1])
                    .setAction(collapse_key);

                    Log.e("Type c2dm:"+type);
                    Log.e("Cam ID c2dm: " + pair[0]);
                    Log.e("DateTime c2dm: " + pair[1]);

                    ArrayList<CamerasFeedItem> cameras = null;
                    XMLObject settings = null;
                    ArrayList<EventItem> listEvents = null;
                    User user = null;
                    try 
                    {
                        user = (User)Utils.deserializeObject(new File(getFilesDir(), CameraManager.USER_OBJ_FILE));
                        cameras = (ArrayList<CamerasFeedItem>)Utils.deserializeObject(new File(getFilesDir(), user.getUserId() + "_" + CameraManager.CAMERAS_OBJ_FILE));
                        settings = (XMLObject)Utils.deserializeObject(new File(getFilesDir(), user.getUserId() + "_" + CameraManager.SETTINGS_OBJ_FILE));

                        //List of events:
                        if(user!=null)
                        {
                            listEvents = (ArrayList<EventItem>)Utils.deserializeObject(new File(getFilesDir(), user.getUserId() + "_" + CameraManager.LIST_EVENTS_OBJ_FILE));
                        }
                    } 
                    catch (Exception e) 
                    { }

                    CamerasFeedItem item = null;
                    if(settings == null || cameras == null || (item = isItemExists(cameras, pair[0])) == null)
                    {
                        return;
                    }


                    if(type.equals(Constants.EXTRA_ALARM_MOTION))
                    {
                        if(settings.getValue("motion", "no").equals("no"))
                        {
                            return;
                        }
                        GregorianCalendar curTime = new GregorianCalendar();
                        long offset = curTime.get(Calendar.ZONE_OFFSET) + curTime.get(Calendar.DST_OFFSET);
                        Calendar c = Calendar.getInstance();
                        c.setTimeZone(TimeZone.getTimeZone("UTC"));
                        c.setTimeInMillis(Long.parseLong(pair[1]) + offset);

                        String when = DateFormat.format("dd-MM-yyyy kk:mm:ss", c).toString();

                        message = context.getString(R.string.push_motion_on_camera, item.getName(), when);
                    }
                    else if(type.equals(Constants.EXTRA_CAMERA_DOWN))
                    {
                        if(settings.getValue("cameraDown", "no").equals("no"))
                        {
                            return;
                        }
                        message = context.getString(R.string.push_camera_is_down, item.getName(), getDownString(pair[1]));
                        //typeIndex = 1;
                    }
                    else if(type.equals(Constants.EXTRA_LSU_DOWN))
                    {
                        //typeIndex = 3;
                        message = "";
                    }
                }

                if(!message.equals(""))
                {
                    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION | Intent.FLAG_ACTIVITY_CLEAR_TOP);

                    notification.defaults |= Notification.DEFAULT_SOUND;
                    notification.flags |= Notification.FLAG_AUTO_CANCEL;

                    RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.notification);
                    contentView.setTextViewText(R.id.title, context.getString(R.string.app_name));
                    contentView.setTextViewText(R.id.text, message);
                    notification.contentView = contentView;
                    notification.contentIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), notificationIntent, 0);

                    mNotificationManager.notify(collapse_key, (int)Math.random(), notification);
                }  

                return;
            }
        }
    }   
}

private CamerasFeedItem isItemExists(ArrayList<CamerasFeedItem> cameras, String id){        
    for(CamerasFeedItem item: cameras)
    {
        if(item.getID().equals(id))
        {
            return item;
        }

        if(item.isFolderItem())
        {
            LSUItem lsu = ((FolderItem)item).getLsuItem();

            if(lsu != null && lsu.getID().equals(id))
            {
                return lsu;
            }               
            CamerasFeedItem result = isItemExists(CamerasFeedItem.parse(item), id);
            if(result != null)
            {
                return result;
            }
        }
    }

    return null;
}

private String getDownString(String hours){
    StringBuilder out = new StringBuilder();
    int total = Integer.parseInt(hours);

    int m = total / 720;
    total = total % 720;        

    int w = total / 168;
    total = total % 168; 

    int d = total / 24;
    total = total % 24;

    if(m > 0)
    {
        out.append(getResources().getQuantityString(R.plurals.push_month, m, m));
        out.append(" ");
    }
    if(w > 0)
    {
        out.append(getResources().getQuantityString(R.plurals.push_weeks, w, w));
        out.append(" ");
    }
    if(d > 0)
    {
        out.append(getResources().getQuantityString(R.plurals.push_days, d, d));
        out.append(" ");
    }
    if(total > 0)
    {
        out.append(getResources().getQuantityString(R.plurals.push_hours, total, total));
        out.append(" ");
    }

    return out.toString().trim();
}
public class C2DMBroadcastReceiver extends BroadcastReceiver {

  @Override
  public final void onReceive(Context context, Intent intent) {
      // To keep things in one place.
      C2DMBaseReceiver.runIntentInService(context, intent);
      setResult(Activity.RESULT_OK, null /* data */, null /* extra */);        
  }
}
public class C2DMessaging {
public static final String EXTRA_SENDER = "sender";
public static final String EXTRA_APPLICATION_PENDING_INTENT = "app";
public static final String REQUEST_UNREGISTRATION_INTENT = "com.google.android.c2dm.intent.UNREGISTER";
public static final String REQUEST_REGISTRATION_INTENT = "com.google.android.c2dm.intent.REGISTER";
public static final String LAST_REGISTRATION_CHANGE = "last_registration_change";
public static final String BACKOFF = "backoff";
public static final String GSF_PACKAGE = "com.google.android.gsf";

// package
static final String PREFERENCE = "com.google.android.c2dm";

private static final long DEFAULT_BACKOFF = 30000;

/**
 * Initiate c2d messaging registration for the current application
 */
public static void register(Context context, String senderId) {
    try {
        Intent registrationIntent = new Intent(REQUEST_REGISTRATION_INTENT);
        registrationIntent.setPackage(GSF_PACKAGE);
        registrationIntent.putExtra(EXTRA_APPLICATION_PENDING_INTENT, PendingIntent.getBroadcast(context, 0, new Intent(), 0));
        registrationIntent.putExtra(EXTRA_SENDER, senderId);
        context.startService(registrationIntent);
    } catch (Exception e) {
        Log.w("Couldn't use C2DM, check OS version", e);    
    }
}

/**
 * Unregister the application. New messages will be blocked by server.
 */
public static void unregister(Context context) {
    Intent regIntent = new Intent(REQUEST_UNREGISTRATION_INTENT);
    regIntent.setPackage(GSF_PACKAGE);
    regIntent.putExtra(EXTRA_APPLICATION_PENDING_INTENT, PendingIntent.getBroadcast(context, 0, new Intent(), 0));
    context.startService(regIntent);
}

/**
 * Return the current registration id.
 *
 * If result is empty, the registration has failed.
 *
 * @return registration id, or empty string if the registration is not complete.
 */
public static String getRegistrationId(Context context) {
    final SharedPreferences prefs = context.getSharedPreferences(
            PREFERENCE,
            Context.MODE_PRIVATE);
    String registrationId = prefs.getString("dm_registration", "");
    return registrationId;
}

public static long getLastRegistrationChange(Context context) {
    final SharedPreferences prefs = context.getSharedPreferences(
            PREFERENCE,
            Context.MODE_PRIVATE);
    return prefs.getLong(LAST_REGISTRATION_CHANGE, 0);
}

static long getBackoff(Context context) {
    final SharedPreferences prefs = context.getSharedPreferences(
            PREFERENCE,
            Context.MODE_PRIVATE);
    return prefs.getLong(BACKOFF, DEFAULT_BACKOFF);
}

static void setBackoff(Context context, long backoff) {
    final SharedPreferences prefs = context.getSharedPreferences(
            PREFERENCE,
            Context.MODE_PRIVATE);
    Editor editor = prefs.edit();
    editor.putLong(BACKOFF, backoff);
    editor.commit();

}

// package
static void clearRegistrationId(Context context) {
    final SharedPreferences prefs = context.getSharedPreferences(
            PREFERENCE,
            Context.MODE_PRIVATE);
    Editor editor = prefs.edit();
    editor.putString("dm_registration", "");
    editor.putLong(LAST_REGISTRATION_CHANGE, System.currentTimeMillis());
    editor.commit();

}

// package
static void setRegistrationId(Context context, String registrationId) {
    final SharedPreferences prefs = context.getSharedPreferences(
            PREFERENCE,
            Context.MODE_PRIVATE);
    Editor editor = prefs.edit();
    editor.putString("dm_registration", registrationId);
    editor.commit();

  }
}
static void runIntentInService(Context context, Intent intent) {
    if (mWakeLock == null) {
        // This is called from BroadcastReceiver, there is no init.
        PowerManager pm = 
            (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, 
                WAKELOCK_KEY);
    }
    mWakeLock.acquire();

    // Use a naming convention, similar with how permissions and intents are 
    // used. Alternatives are introspection or an ugly use of statics. 
    String receiver = context.getPackageName() + ".C2DMReceiver";
    intent.setClassName(context, receiver);

    context.startService(intent);

}
String receiver = context.getPackageName() + ".C2DMReceiver";
String receiver = C2DMReceiver.class.getName ();