3

我的应用程序每次都开始创建注册 ID 并发送到服务器。

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

3 回答 3

1

这是因为您的本地服务器错误。您可能无法在服务器上成功保存您的注册 ID,或者可能无法连接到本地服务器。所以检查与服务器的连接。

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

如果您无法成功注册到您的服务器,此代码将从 GCM 服务器注销您的设备。

于 2012-09-17T06:31:30.340 回答
0
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();
        }


}
于 2012-09-19T05:12:22.810 回答
0

只需使用 Application.so 扩展您的类,这样它就不会每次都调用。它只会在应用程序安装后第一次调用。

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

}

不要忘记将此类路径放在清单应用程序标记中。

<application
    android:name=".packagepath.class"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name">
于 2012-09-17T06:52:10.393 回答