Android and google cluod messaging
<p>Hello I have a google cloud messaging in my app This is code my Main:</p>

<pre><code>import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import pdf2app.actionBars.ActionBarMain;
import pdf2app.config.GlobalConfig;
import pdf2app.database.ObjectsDBAdapter;
import pdf2app.debug.MY_DEBUG;
import pdf2app.gallery.ListViewGallery;
import pdf2app.helpers.ThumbnailsGalleryGenerator;
import pl.spot.p2a.R;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Window;
import com.google.android.gcm.GCMRegistrar;
import com.radaee.pdf.Global; 


public class MainActivity extends Activity{
    public static final int DELETE = 0;
    public static final String SENDER_ID = "410016639123";
    private static final int APP_ID = 1;
    public static int VIEW_ID = 2; 
    private String registrationStatus = "Not yet registered";
    private boolean listviewSelected;
    private String TAG = "push";
     private String regId = "";
    Bundle extras;
    IntentFilter gcmFilter;
    private String broadcastMessage = "No broadcast message";
    /** Called when the activity is first created. */
     private BroadcastReceiver gcmReceiver = new BroadcastReceiver() {


            @Override
            public void onReceive(Context context, Intent intent) {
                broadcastMessage = intent.getExtras().getString("gcm");

                if (broadcastMessage != null) {
                    // display our received message
                    Log.v("Broadcast", broadcastMessage);
                }

            }
        };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

//      checkNotNull(SENDER_ID, "SENDER_ID");
//      GCMRegistrar.checkDevice(this);
//      GCMRegistrar.checkManifest(this);


        requestWindowFeature(Window.FEATURE_ACTION_BAR);
        setContentView(R.layout.activity_main);
        extras = getIntent().getExtras();


        if (savedInstanceState == null) {

            if(extras == null) {
                GlobalConfig.setAPPLICATION_ID(APP_ID);

            } else {

                GlobalConfig.setAPPLICATION_ID(extras.getInt("application_id", 0));
            }
        } else {
           MY_DEBUG.print("SavedInstanceState is not null");
        }
        GlobalConfig.setBookmark(0);

        gcmFilter = new IntentFilter();
        gcmFilter.addAction("GCM_RECEIVED_ACTION");

        registerClient();

//      //notifications
//      final String regId = GCMRegistrar.getRegistrationId(this);
//      
//       
//      if (regId.equals("")) {
//          GCMRegistrar.register(this, SENDER_ID);
//      } else {
//          Log.v(TAG, "Already registered");
//          }
//
//      Log.v(TAG, "registration id  "+regId);


        SharedPreferences preferences = getSharedPreferences(GlobalConfig.getApp(), MODE_WORLD_READABLE);
        listviewSelected = preferences.getBoolean(ActionBarMain.LISTVIEW_SELECTED, false);
        GlobalConfig.setLastUpdate(preferences.getLong(ObjectsDBAdapter.TIMESTAMP, 0));
        GlobalConfig.getUser(this);

        Intent intent1 = new Intent(this, DownloaderService.class);
        intent1.putExtra(DownloaderService.TYPE, DownloaderService.GET_CONFIG);
        startService(intent1);

        AsyncTask&lt;Void, Void, Void&gt; task = new AsyncTask&lt;Void, Void, Void&gt;(){

            @Override
            protected Void doInBackground(Void... params) {
                CopyAssets();
                return null;
            }
            protected void onPostExecute(Void result) {
            };
        }.execute();
        finish();
    }

    public void registerClient() {

        try {
            // Check that the device supports GCM (should be in a try / catch)
            GCMRegistrar.checkDevice(this);

            // Check the manifest to be sure this app has all the required
            // permissions.
            GCMRegistrar.checkManifest(this);

            // Get the existing registration id, if it exists.
            regId = GCMRegistrar.getRegistrationId(this);

            if (regId.equals("")) {

                registrationStatus = "Registering...";

                // register this device for this project
                GCMRegistrar.register(this, SENDER_ID);
                regId = GCMRegistrar.getRegistrationId(this);

                registrationStatus = "Registration Acquired";

                // This is actually a dummy function.  At this point, one
                // would send the registration id, and other identifying
                // information to your server, which should save the id
                // for use when broadcasting messages.
                sendRegistrationToServer();

            } else {

                registrationStatus = "Already registered";

            }


        } catch (Exception e) {

            e.printStackTrace();
            registrationStatus = e.getMessage();

        }

        Log.d(TAG, registrationStatus);

        // This is part of our CHEAT.  For this demo, you'll need to
        // capture this registration id so it can be used in our demo web
        // service.
        Log.d(TAG, regId);

    }

     private void sendRegistrationToServer() {
            // This is an empty placeholder for an asynchronous task to post the
            // registration
            // id and any other identifying information to your server.
        }

        @Override
        public void onSaveInstanceState(Bundle savedInstanceState) {

            super.onSaveInstanceState(savedInstanceState);

            savedInstanceState.putString("BroadcastMessage", broadcastMessage);

        }

        @Override
        public void onRestoreInstanceState(Bundle savedInstanceState) {

            super.onRestoreInstanceState(savedInstanceState);

            broadcastMessage = savedInstanceState.getString("BroadcastMessage");
            Log.v("BroadCastMes", broadcastMessage);

        }   
    private void checkNotNull(Object reference, String name) {
        if (reference == null) {
            throw new NullPointerException(
                    getString(R.string.error_config, name));
        }
    }

    @Override
    protected void onPause() {
        GCMRegistrar.unregister(this);
        super.onPause();

    }
    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(gcmReceiver, gcmFilter);

    }

    @Override
    public void onDestroy() {

        GCMRegistrar.onDestroy(this);

        super.onDestroy();
    }
    /**
     * checks whether the sdcard is mounted
     * @param requireWriteAccess
     * @return whether the sdcard is mounted 
     */
    static public boolean hasStorage(boolean requireWriteAccess) {
        //TODO: After fix the bug,  add "if (VERBOSE)" before logging errors.
        String state = Environment.getExternalStorageState();
        Log.v("tag", "storage state is " + state);

        if (Environment.MEDIA_MOUNTED.equals(state)) {
            if (requireWriteAccess) {
                boolean writable = checkFsWritable();
                Log.v("tag", "storage writable is " + writable);
                return writable;
            } else {
                return true;
            }
        } else if (!requireWriteAccess &amp;&amp; Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            return true;
        }
        return false;
    }

    private static boolean checkFsWritable() {
        // Create a temporary file to see whether a volume is really writeable.
        // It's important not to put it in the root directory which may have a
        // limit on the number of files.
        String directoryName = Environment.getExternalStorageDirectory().toString() + "/DCIM";
        File directory = new File(directoryName);
        if (!directory.isDirectory()) {
            if (!directory.mkdirs()) {
                return false;
            }
        }
        return directory.canWrite();
    }

    /**
     * copies all assets (icons, terms document) to the sdcard if they are missing. 
     */
    private void CopyAssets() {
        Global.Init(this);

        File f = new File(GlobalConfig.getBaseDirectory());
        if (!f.exists())
            f.mkdirs();

            File file = new File(GlobalConfig.getTermsFile());
            if(file.exists()){
                MY_DEBUG.LOG(getClass(), "getApplicationID" + GlobalConfig.getApplicationID());
                MY_DEBUG.LOG(getClass(), "getAPPLICATION_ID" + GlobalConfig.getAPPLICATION_ID());
                ThumbnailsGalleryGenerator.generateTermsThumbs(GlobalConfig.getTermsFile(), this);
                // TODO generate terms database pages
            } else {
                if(GlobalConfig.getAPPLICATION_ID() == APP_ID) {
                    AssetManager assetManager = getAssets();
                    String[] files = null;
                    try {
                        files = assetManager.list("Files");
                    } catch (IOException e) {
                        MY_DEBUG.print(e);
                    }

                    InputStream in = null;
                    OutputStream out = null;

                    try {
                        in = assetManager.open("Files/terms.pdf");

                        out = new FileOutputStream(GlobalConfig.getTermsFile());

                        copyFile(in, out);
                        in.close();
                        in = null;
                        out.flush();
                        out.close();
                        out = null;
                    } catch (IOException e) {
//                      e.printStackTrace();
//                      Log.e("tag", e.getMessage());
                    } 
                    ThumbnailsGalleryGenerator.generateTermsThumbs(GlobalConfig.getTermsFile(), this);
                }
            }

//        String[] icons = null;
//        try {
//          File iconsDir = new File(f.getPath() + "/icons");
//          if (!iconsDir.exists())
//              iconsDir.mkdirs();
//          
//          icons = assetManager.list("Files/icons");
//            for(String icon : icons) {
//              in = null;
//                out = null;
//                if(!(new File(GlobalConfig.getBaseDirectory() +"/icons" + icon).exists())){
//                  in = assetManager.open("Files/icons/"+icon);   // if files resides inside the "Files" directory itself
//                  out = new FileOutputStream(GlobalConfig.getBaseDirectory() + "/icons/" + icon);
//              
//                  copyFile(in, out);
//                  in.close();
//                  in = null;
//                  out.flush();
//                  out.close();
//                  out = null;
//                }
//            }
//        } catch (Exception e) {
//            Log.e("tag", e.getMessage());
//        }
    }

    private void copyFile(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[1024];
        int read;
        while((read = in.read(buffer)) != -1){
          out.write(buffer, 0, read);
        }
    }

    @Override
    public void finish() {
        Intent intent = new Intent();
        if (listviewSelected) {
            intent = new Intent(MainActivity.this, ListViewGallery.class);
            intent.putExtra("ClassName", "action_bar_listView_icon");
            startActivity(intent);
        } else {
            intent = new Intent(MainActivity.this, CoverFlowActivity.class);
            intent.putExtra("ClassName", "action_bar_coverView_icon");
            startActivity(intent);
        }

        super.finish();
    }


}
</code></pre>

<p>This is GMCIntentService:</p>

<pre><code>public class GCMIntentService extends GCMBaseIntentService {

    private static final String PROJECT_ID = "410016639123";

    private static final String TAG = "GCMIntentService";

    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");

        sendGCMIntent(ctx, message);

    }


    private void sendGCMIntent(Context ctx, String message) {

        Intent broadcastIntent = new Intent();
        broadcastIntent.setAction("GCM_RECEIVED_ACTION");

        broadcastIntent.putExtra("gcm", message);

        ctx.sendBroadcast(broadcastIntent);

    }


    @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

    }

}
</code></pre>

<p>and manifest: </p>

<pre><code>&lt;manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.test"
    android:versionCode="2"
    android:versionName="1"
    android:installLocation="auto"&gt;

    &lt;uses-sdk
        android:minSdkVersion="12" /&gt;

    &lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"&gt;&lt;/uses-permission&gt;
    &lt;uses-permission android:name="android.permission.INTERNET"&gt;&lt;/uses-permission&gt;
    &lt;uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /&gt;
    &lt;permission android:name="pl.spot.p2a.permission.C2D_MESSAGE" android:protectionLevel="signature" /&gt;
    &lt;uses-permission android:name="pl.spot.p2a.permission.C2D_MESSAGE" /&gt; 
    &lt;!-- App receives GCM messages. --&gt;
    &lt;uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" /&gt;
    &lt;!-- GCM requires a Google account. --&gt;
    &lt;uses-permission android:name="android.permission.GET_ACCOUNTS" /&gt;
    &lt;!-- Keeps the processor from sleeping when a message is received. --&gt;
    &lt;uses-permission android:name="android.permission.WAKE_LOCK" /&gt;
    &lt;uses-permission android:name="android.permission.USE_CREDENTIALS" /&gt;

    &lt;uses-permission android:name="android.permission.READ_OWNER_DATA" /&gt;

    &lt;application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.Holo"
        android:largeHeap="true" &gt;
        &lt;activity
            android:name="pdf.activities.MainActivity"
            android:label="@string/title_activity_main" &gt;
            &lt;intent-filter&gt;
                &lt;action android:name="android.intent.action.MAIN" /&gt;

                &lt;category android:name="android.intent.category.LAUNCHER" /&gt;
            &lt;/intent-filter&gt;
        &lt;/activity&gt;





        &lt;receiver android:name="com.google.android.gcm.GCMBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND" &gt;
            &lt;intent-filter&gt;
                &lt;action android:name="com.google.android.c2dm.intent.RECEIVE" /&gt;
                &lt;action android:name="com.google.android.c2dm.intent.REGISTRATION" /&gt;
                &lt;category android:name="com.example.test" /&gt;  
            &lt;/intent-filter&gt;   
        &lt;/receiver&gt;
        &lt;service
            android:name="com.example.test"&gt;
        &lt;/service&gt;
    &lt;/application&gt;
    &lt;supports-screens
        android:anyDensity="true"
        android:largeScreens="true"
        android:normalScreens="true"
        android:smallScreens="true" /&gt;

&lt;/manifest&gt;
</code></pre>

<p>In logs I don't get a api key.</p>

<pre><code>This is log:
12-18 10:54:58.132: D/dalvikvm(4582): WAIT_FOR_CONCURRENT_GC blocked 0ms
12-18 10:54:58.192: D/dalvikvm(4582): GC_FOR_ALLOC freed 102K, 8% free 12264K/13319K, paused 14ms, total 14ms
12-18 10:54:58.192: I/dalvikvm-heap(4582): Grow heap (frag case) to 13.447MB for 614416-byte allocation
12-18 10:54:58.212: D/dalvikvm(4582): GC_CONCURRENT freed 1K, 8% free 12863K/13959K, paused 12ms+1ms, total 21ms
12-18 10:54:58.227: D/dalvikvm(4582): GC_FOR_ALLOC freed 0K, 8% free 12863K/13959K, paused 11ms, total 11ms
12-18 10:54:58.227: I/dalvikvm-heap(4582): Grow heap (frag case) to 15.789MB for 2457616-byte allocation
12-18 10:54:58.252: D/dalvikvm(4582): GC_CONCURRENT freed 0K, 7% free 15263K/16391K, paused 11ms+2ms, total 23ms
12-18 10:54:58.252: D/dalvikvm(4582): WAIT_FOR_CONCURRENT_GC blocked 6ms
12-18 10:54:58.277: D/GCMRegistrar(4582): resetting backoff for com.example.test
12-18 10:54:58.277: V/GCMRegistrar(4582): Registering app com.example.test of senders 410016639123
12-18 10:54:58.287: D/push(4582): Registration Acquired
12-18 10:54:58.302: D/dalvikvm(4582): Trying to load lib /data/data/pl.spot.p2a/lib/librdpdf.so 0x42818728
12-18 10:54:58.312: D/dalvikvm(4582): Added shared lib /data/data/pl.spot.p2a/lib/librdpdf.so 0x42818728
12-18 10:54:58.377: V/MainActivity(4582): getApplicationID1
12-18 10:54:58.377: V/MainActivity(4582): getAPPLICATION_ID1
12-18 10:54:58.377: V/generateTermsThumbs(4582): doc.open: /storage/sdcard0/pdf2app/1/terms.pdf
12-18 10:55:01.662: D/dalvikvm(4582): GC_CONCURRENT freed 997K, 12% free 15264K/17223K, paused 34ms+4ms, total 72ms
12-18 10:55:11.222: V/GCMBroadcastReceiver(4582): onReceive: com.google.android.c2dm.intent.REGISTRATION
12-18 10:55:11.222: V/GCMBroadcastReceiver(4582): GCM IntentService class: pl.spot.p2a.GCMIntentService
12-18 10:55:11.227: V/GCMBaseIntentService(4582): Acquiring wakelock
</code></pre>

<p>When I change in manifest line: <code>android:name="com.example.test"</code> on </p>

<pre><code>android:name=".GCMIntentService" I get error:
12-18 11:04:10.412: E/AndroidRuntime(6424): FATAL EXCEPTION: main
12-18 11:04:10.412: E/AndroidRuntime(6424): java.lang.RuntimeException: Unable to instantiate service com.example.test.GCMIntentService: java.lang.ClassNotFoundException: pl.spot.p2a.GCMIntentService
12-18 11:04:10.412: E/AndroidRuntime(6424):     at android.app.ActivityThread.handleCreateService(ActivityThread.java:2388)
12-18 11:04:10.412: E/AndroidRuntime(6424):     at android.app.ActivityThread.access$1600(ActivityThread.java:140)
12-18 11:04:10.412: E/AndroidRuntime(6424):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1309)
12-18 11:04:10.412: E/AndroidRuntime(6424):     at android.os.Handler.dispatchMessage(Handler.java:99)
12-18 11:04:10.412: E/AndroidRuntime(6424):     at android.os.Looper.loop(Looper.java:137)
12-18 11:04:10.412: E/AndroidRuntime(6424):     at android.app.ActivityThread.main(ActivityThread.java:4898)
12-18 11:04:10.412: E/AndroidRuntime(6424):     at java.lang.reflect.Method.invokeNative(Native Method)
12-18 11:04:10.412: E/AndroidRuntime(6424):     at java.lang.reflect.Method.invoke(Method.java:511)
12-18 11:04:10.412: E/AndroidRuntime(6424):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
12-18 11:04:10.412: E/AndroidRuntime(6424):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
12-18 11:04:10.412: E/AndroidRuntime(6424):     at dalvik.system.NativeStart.main(Native Method)
12-18 11:04:10.412: E/AndroidRuntime(6424): Caused by: java.lang.ClassNotFoundException: com.example.test.GCMIntentService
12-18 11:04:10.412: E/AndroidRuntime(6424):     at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:61)
12-18 11:04:10.412: E/AndroidRuntime(6424):     at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
12-18 11:04:10.412: E/AndroidRuntime(6424):     at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
12-18 11:04:10.412: E/AndroidRuntime(6424):     at android.app.ActivityThread.handleCreateService(ActivityThread.java:2385)
12-18 11:04:10.412: E/AndroidRuntime(6424):     ... 10 more
</code></pre>

<p>Could you tell me why?</p>
