Android
Android

Reputation: 2393

GCM Registration id create every time when app start?

My application start Registration id create every time and send to server.

public class MariTimeGlobalNewsSplash extends Activity {
    /** Called when the activity is first created. */

    public final static String AUTH = "authentication";
    AsyncTask<Void, Void, Void> mRegisterTask;
    String TAG = "MariTimeGlobalNewsSplash";
    TextView mDisplay;
    @Override    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.maritimes_global_news_splash);
        mDisplay = (TextView) findViewById(R.id.display);

        Thread threadMenu = new Thread(new Runnable() {
            public void run() {
                try {                   
                    Thread.sleep(2000);
                    HandlerMenu.sendEmptyMessage(0);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        threadMenu.start();

        Log.i(TAG,
                "================Inside OnCreate Method==============================");
        checkNotNull(SERVER_URL, "SERVER_URL");
        checkNotNull(SENDER_ID, "SENDER_ID");
        // Make sure the device has the proper dependencies.
        GCMRegistrar.checkDevice(getBaseContext());
        // Make sure the manifest was properly set - comment out this line
        // while developing the app, then uncomment it when it's ready.
        GCMRegistrar.checkManifest(getBaseContext());

        registerReceiver(mHandleMessageReceiver, new IntentFilter(
                DISPLAY_MESSAGE_ACTION));
        final String regId = GCMRegistrar.getRegistrationId(this);
        if (regId.equals("")) {
            Log.i(TAG,
                    "================Inside if in regId=null ==============================");
            // Automatically registers application on startup.
            GCMRegistrar.register(this, SENDER_ID);
        } else {
            Log.i(TAG,
                    "================Inside else in regId=null ==============================");
            // Device is already registered on GCM, needs to check if it is
            // registered on our server as well.
            if (GCMRegistrar.isRegisteredOnServer(this)) {
                // Skips registration.
                Log.i(TAG,  "================Inside else in regId=null Already register on Server =============================");
                mDisplay.append(getString(R.string.already_registered) + "\n");
                Log.i("m Display regId",""+ mDisplay);
            } else {
                Log.i(TAG,
                        "================Inside else in regId=null trying to  register on Server =============================");
                // Try to register again, but not in the UI thread.
                // It's also necessary to cancel the thread onDestroy(),
                // hence the use of AsyncTask instead of a raw thread.
                final Context context = this;
                mRegisterTask = new AsyncTask<Void, Void, Void>() {

                    @Override
                    protected Void doInBackground(Void... params) {
                        Log.i(TAG,
                                "================Inside doInBackground Method==============================");
                        boolean registered = ServerUtilities.register(context,
                                regId);
                        // At this point all attempts to register with the app
                        // server failed, so we need to unregister the device
                        // from GCM - the app will try to register again when
                        // it is restarted. Note that GCM will send an
                        // unregistered callback upon completion, but
                        // GCMIntentService.onUnregistered() will ignore it.
                        if (!registered) {
                            GCMRegistrar.unregister(context);
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void result) {
                        Log.i(TAG,
                                "================Inside onPostExecute Method==============================");
                        mRegisterTask = null;
                    }

                };
                mRegisterTask.execute(null, null, null);
            }
        }       

    }

      public void register(View view) {
        Log.i("C2DM", "start registration process");
        Intent intent = new Intent("com.google.android.c2dm.intent.REGISTER");
        intent.putExtra("app", PendingIntent.getBroadcast(this, 0,new Intent(), 0));
        intent.putExtra("sender", "60905422365");        
        startService(intent);
    }

    public void showRegistrationId(View view) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        String string = prefs.getString(AUTH, "n/a");
        Toast.makeText(this, string, Toast.LENGTH_LONG).show();
        Log.i("C2DM RegId", string);

    }           

    Handler HandlerMenu = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            new Handler().postDelayed(new Runnable(){

                public void run() {

                    Intent i = new Intent(MariTimeGlobalNewsSplash.this,NewsScreenActivity.class);
                    startActivity(i);

                    finish();
                }

            }, 0);

            finish();
        }
    };
    @Override
    protected void onDestroy() {
        Log.i(TAG,
                "================Inside  OnDestroy  Method==============================");
        if (mRegisterTask != null) {
            mRegisterTask.cancel(true);
        }
        unregisterReceiver(mHandleMessageReceiver);
        GCMRegistrar.onDestroy(getBaseContext());
        super.onDestroy();
    }

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

    private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i(TAG,
                    "================Inside OnReceive in BroadcastReceiver Method==============================");
            String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
            mDisplay.append(newMessage + "\n");
        }
    };
}

Upvotes: 3

Views: 6202

Answers (3)

Android
Android

Reputation: 2393

public class MariTimeGlobalNewsSplash extends Activity {
    /** Called when the activity is first created. */

    TextView mDisplay;
    AsyncTask<Void, Void, Void> mRegisterTask;
    String TAG="MariTimeGlobalNews";
    public final static String AUTH = "authentication";


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.maritimes_global_news_splash);
        Thread threadMenu = new Thread(new Runnable() {
            public void run() {
                try {                   
                    Thread.sleep(2000);
                    HandlerMenu.sendEmptyMessage(0);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        threadMenu.start();


         checkNotNull(SERVER_URL, "SERVER_URL");
            checkNotNull(SENDER_ID, "SENDER_ID");
            // Make sure the device has the proper dependencies.
            GCMRegistrar.checkDevice(this);
            // Make sure the manifest was properly set - comment out this line
            // while developing the app, then uncomment it when it's ready.
            GCMRegistrar.checkManifest(this);
       //     setContentView(R.layout.main);
            mDisplay = (TextView) findViewById(R.id.display);
            registerReceiver(mHandleMessageReceiver,
                    new IntentFilter(DISPLAY_MESSAGE_ACTION));
            final String regId = GCMRegistrar.getRegistrationId(this);
            if (regId.equals("")) {
                Log.i(TAG, "================Inside if in regId=null ==============================");
                // Automatically registers application on startup.
                GCMRegistrar.register(this, SENDER_ID);
            } else {
                Log.i(TAG, "================Inside else in regId=null ==============================");
                // Device is already registered on GCM, needs to check if it is
                // registered on our server as well.
                if (GCMRegistrar.isRegisteredOnServer(this)) {
                    // Skips registration.
                    Log.i(TAG, "================Inside else in regId=null Already register on Server =============================");
                    mDisplay.append(getString(R.string.already_registered) + "\n");
                } else {
                    Log.i(TAG, "================Inside else in regId=null trying to  register on Server =============================");
                    // Try to register again, but not in the UI thread.
                    // It's also necessary to cancel the thread onDestroy(),
                    // hence the use of AsyncTask instead of a raw thread.
                    final Context context = this;
                    mRegisterTask = new AsyncTask<Void, Void, Void>() {

                        @Override
                        protected Void doInBackground(Void... params) {
                            Log.i(TAG, "================Inside doInBackground Method==============================");
                            boolean registered =
                                    ServerUtilities.register(context, regId);
                            // At this point all attempts to register with the app
                            // server failed, so we need to unregister the device
                            // from GCM - the app will try to register again when
                            // it is restarted. Note that GCM will send an
                            // unregistered callback upon completion, but
                            // GCMIntentService.onUnregistered() will ignore it.
                            if (!registered) {
                                GCMRegistrar.unregister(context);
                            }
                            return null;
                        }

                        @Override
                        protected void onPostExecute(Void result) {
                            Log.i(TAG, "================Inside onPostExecute Method==============================");
                            mRegisterTask = null;
                        }

                    };
                    mRegisterTask.execute(null, null, null);
                }

            }

    }


      public void register(View view) {
            Log.i("C2DM", "start registration process");
            Intent intent = new Intent("com.google.android.c2dm.intent.REGISTER");
            intent.putExtra("app", PendingIntent.getBroadcast(this, 0,new Intent(), 0));
            intent.putExtra("sender", "123456789101");       
            startService(intent);
        }

        public void showRegistrationId(View view) {
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
            String string = prefs.getString(AUTH, "n/a");
            Toast.makeText(this, string, Toast.LENGTH_LONG).show();
            Log.i("C2DM RegId", string);

        }           


    Handler HandlerMenu = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            Intent i = new Intent(MariTimeGlobalNewsSplash.this,NewsScreenActivity.class);
            startActivity(i);
            finish();
        }
    };

      @Override
        protected void onDestroy() {
            Log.i(TAG, "================Inside  OnDestroy  Method==============================");
            if (mRegisterTask != null) {
                mRegisterTask.cancel(true);
            }
            unregisterReceiver(mHandleMessageReceiver);
            GCMRegistrar.onDestroy(getBaseContext());
            super.onDestroy();
        }

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

        private final BroadcastReceiver mHandleMessageReceiver =
                new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                Log.i(TAG, "================Inside OnReceive in BroadcastReceiver Method==============================");
                String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
                mDisplay.append(newMessage + "\n");
            }
        };

        public static void trimCache(MariTimeGlobalNewsSplash context) {
            try {
                File dir = context.getCacheDir();
                if (dir != null && dir.isDirectory()) {
                    deleteDir(dir);

                }
            } catch (Exception e) {
                // TODO: handle exception
            }

        }

        public static boolean deleteDir(File dir) {
            if (dir!=null && dir.isDirectory()) {
                String[] children = dir.list();
                for (int i = 0; i < children.length; i++) {
                    boolean success = deleteDir(new File(dir, children[i]));
                    if (!success) {
                        return false;
                    }
                }
            }

            // The directory is now empty so delete it
            return dir.delete();
        }


}

Upvotes: 0

Rajendra
Rajendra

Reputation: 1698

This is because of your local server error. You may not be able to successfully save your registration id on your server or may not connect to your local server. So check the connectivity to server.

if (!registered) {
    GCMRegistrar.unregister(context);
}
return null;

This code will unregister your device from the GCM Server if you are not able to successfully register to your server.

Upvotes: 1

Karn Shah
Karn Shah

Reputation: 501

Just extend your class with Application.so that It will not call every time.It will call only first time after app installed.

public class MariTimeGlobalNewsSplash extends Application {

public final static String AUTH = "authentication";

AsyncTask<Void, Void, Void> mRegisterTask;

String TAG = "MariTimeGlobalNewsSplash";

TextView mDisplay;

@Override    
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.maritimes_global_news_splash);
    mDisplay = (TextView) findViewById(R.id.display);

    Thread threadMenu = new Thread(new Runnable() {
        public void run() {
            try {                   
                Thread.sleep(2000);
                HandlerMenu.sendEmptyMessage(0);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });
    threadMenu.start();

    Log.i(TAG,
            "================Inside OnCreate Method==============================");
    checkNotNull(SERVER_URL, "SERVER_URL");
    checkNotNull(SENDER_ID, "SENDER_ID");
    // Make sure the device has the proper dependencies.
    GCMRegistrar.checkDevice(getBaseContext());
    // Make sure the manifest was properly set - comment out this line
    // while developing the app, then uncomment it when it's ready.
    GCMRegistrar.checkManifest(getBaseContext());

    registerReceiver(mHandleMessageReceiver, new IntentFilter(
            DISPLAY_MESSAGE_ACTION));
    final String regId = GCMRegistrar.getRegistrationId(this);
    if (regId.equals("")) {
        Log.i(TAG,
                "================Inside if in regId=null ==============================");
        // Automatically registers application on startup.
        GCMRegistrar.register(this, SENDER_ID);
    } else {
        Log.i(TAG,
                "================Inside else in regId=null ==============================");
        // Device is already registered on GCM, needs to check if it is
        // registered on our server as well.
        if (GCMRegistrar.isRegisteredOnServer(this)) {
            // Skips registration.
            Log.i(TAG,  "================Inside else in regId=null Already register on Server =============================");
            mDisplay.append(getString(R.string.already_registered) + "\n");
            Log.i("m Display regId",""+ mDisplay);
        } else {
            Log.i(TAG,
                    "================Inside else in regId=null trying to  register on Server =============================");
            // Try to register again, but not in the UI thread.
            // It's also necessary to cancel the thread onDestroy(),
            // hence the use of AsyncTask instead of a raw thread.
            final Context context = this;
            mRegisterTask = new AsyncTask<Void, Void, Void>() {

                @Override
                protected Void doInBackground(Void... params) {
                    Log.i(TAG,
                            "================Inside doInBackground Method==============================");
                    boolean registered = ServerUtilities.register(context,
                            regId);
                    // At this point all attempts to register with the app
                    // server failed, so we need to unregister the device
                    // from GCM - the app will try to register again when
                    // it is restarted. Note that GCM will send an
                    // unregistered callback upon completion, but
                    // GCMIntentService.onUnregistered() will ignore it.
                    if (!registered) {
                        GCMRegistrar.unregister(context);
                    }
                    return null;
                }

                @Override
                protected void onPostExecute(Void result) {
                    Log.i(TAG,
                            "================Inside onPostExecute Method==============================");
                    mRegisterTask = null;
                }

            };
            mRegisterTask.execute(null, null, null);
        }
    }       

}

  public void register(View view) {
    Log.i("C2DM", "start registration process");
    Intent intent = new Intent("com.google.android.c2dm.intent.REGISTER");
    intent.putExtra("app", PendingIntent.getBroadcast(this, 0,new Intent(), 0));
    intent.putExtra("sender", "60905422365");        
    startService(intent);
}

public void showRegistrationId(View view) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    String string = prefs.getString(AUTH, "n/a");
    Toast.makeText(this, string, Toast.LENGTH_LONG).show();
    Log.i("C2DM RegId", string);

}           

Handler HandlerMenu = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        new Handler().postDelayed(new Runnable(){

            public void run() {

                Intent i = new Intent(MariTimeGlobalNewsSplash.this,NewsScreenActivity.class);
                startActivity(i);

                finish();
            }

        }, 0);

        finish();
    }
};
@Override
protected void onDestroy() {
    Log.i(TAG,
            "================Inside  OnDestroy  Method==============================");
    if (mRegisterTask != null) {
        mRegisterTask.cancel(true);
    }
    unregisterReceiver(mHandleMessageReceiver);
    GCMRegistrar.onDestroy(getBaseContext());
    super.onDestroy();
}

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

private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i(TAG,
                "================Inside OnReceive in BroadcastReceiver Method==============================");
        String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
        mDisplay.append(newMessage + "\n");
    }
};

}

Don't forget to put this class path to manifest application tag.

<application
    android:name=".packagepath.class"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name">

Upvotes: 0

Related Questions