当前位置: 首页 > 知识库问答 >
问题:

Android GCM示例-如何在现有项目中实现?

严信瑞
2023-03-14

我已经在GitHub上从Google下载了最新的GCM示例。

它工作得很好,但是我不能让它在我自己的项目中工作。我已经得到了甜甜圈和消息"生成InstanceID令牌..."

我不理解他们示例中与类GcmSender的链接。

这是我的密码

    public class MainActivity extends ActionBarActivity {

        private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
        private static final String TAG = "MainActivity";

        private BroadcastReceiver mRegistrationBroadcastReceiver;
        private ProgressBar mRegistrationProgressBar;
        private TextView mInformationTextView;

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

            setContentView(R.layout.activity_main);

            // url
            String url="http://www.monurl.org/";
            WebView mWview=(WebView) this.findViewById(R.id.webView);
            //autorise javascript
            mWview.getSettings().setJavaScriptEnabled(true);
            mWview.loadUrl(url);

            //partie notif

            mRegistrationProgressBar = (ProgressBar) findViewById(R.id.registrationProgressBar);
            mRegistrationBroadcastReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    mRegistrationProgressBar.setVisibility(ProgressBar.GONE);
                    SharedPreferences sharedPreferences =
                            PreferenceManager.getDefaultSharedPreferences(context);
                    boolean sentToken = sharedPreferences
                            .getBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false);
                    if (sentToken) {
                        mInformationTextView.setText(getString(R.string.gcm_send_message));
                    } else {
                        mInformationTextView.setText(getString(R.string.token_error_message));
                    }
                }
            };
            mInformationTextView = (TextView) findViewById(R.id.informationTextView);


            // check si Google Play Services APK est sur le phone
            if (checkPlayServices()) {
                // Start IntentService to register this application with GCM.
                Intent intent = new Intent(this, MyGcmRegistrationIntentService.class);
                startService(intent);
            }

        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.menu_main, menu);
            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();

            //noinspection SimplifiableIfStatement
            if (id == R.id.action_settings) {
                return true;
            }

            return super.onOptionsItemSelected(item);
        }



        /**
         * Check the device to make sure it has the Google Play Services APK. If
         * it doesn't, display a dialog that allows users to download the APK from
         * the Google Play Store or enable it in the device's system settings.
         */
        private boolean checkPlayServices() {
            int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
            if (resultCode != ConnectionResult.SUCCESS) {
                if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                    GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                            PLAY_SERVICES_RESOLUTION_REQUEST).show();
                } else {
                    Log.i(TAG, "Ce peripherique n'est pas supporte.");
                    finish();
                }
                return false;
            }
            return true;
        }
    }
    public class MyGcmListenerService extends GcmListenerService {

        private static final String TAG = "MyGcmListenerService";
        public MyGcmListenerService() {
        }


        /**
         * Called when message is received.
         *
         * @param from SenderID of the sender.
         * @param data Data bundle containing message data as key/value pairs.
         *             For Set of keys use data.keySet().
         */
        // [START receive_message]
        @Override
        public void onMessageReceived(String from, Bundle data) {
            String message = data.getString("message");
            Log.d(TAG, "From: " + from);
            Log.d(TAG, "Message: " + message);

            /**
             * Production applications would usually process the message here.
             * Eg: - Syncing with server.
             *     - Store message in local database.
             *     - Update UI.
             */

            /**
             * In some cases it may be useful to show a notification indicating to the user
             * that a message was received.
             */
            sendNotification(message);
        }
        // [END receive_message]



        /**
         * Create and show a simple notification containing the received GCM message.
         *
         * @param message GCM message received.
         */
        private void sendNotification(String message) {
            Intent intent = new Intent(this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                    PendingIntent.FLAG_ONE_SHOT);

            Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.ic_stat_ic_notification)
                    .setContentTitle("GCM Message")
                    .setContentText(message)
                    .setAutoCancel(true)
                    .setSound(defaultSoundUri)
                    .setContentIntent(pendingIntent);

            NotificationManager notificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());

            Log.v("notification message",message);
        }
    }
    public class MyGcmRegistrationIntentService extends IntentService {


        private static final String TAG = "MyGcmRegistrationIntentService";
        private static final String[] TOPICS = {"global"};




        /**
         * Starts this service to perform action Foo with the given parameters. If
         * the service is already performing a task this action will be queued.
         *
         * @see IntentService
         */
        // TODO: Customize helper method
        public static void startActionFoo(Context context, String param1, String param2) {
            Intent intent = new Intent(context, MyGcmRegistrationIntentService.class);
            intent.setAction(ACTION_FOO);
            intent.putExtra(EXTRA_PARAM1, param1);
            intent.putExtra(EXTRA_PARAM2, param2);
            context.startService(intent);
        }

        /**
         * Starts this service to perform action Baz with the given parameters. If
         * the service is already performing a task this action will be queued.
         *
         * @see IntentService
         */
        // TODO: Customize helper method
        public static void startActionBaz(Context context, String param1, String param2) {
            Intent intent = new Intent(context, MyGcmRegistrationIntentService.class);
            intent.setAction(ACTION_BAZ);
            intent.putExtra(EXTRA_PARAM1, param1);
            intent.putExtra(EXTRA_PARAM2, param2);
            context.startService(intent);
        }

        public MyGcmRegistrationIntentService() {
           // super("MyGcmRegistrationIntentService");
            // ajout
            super(TAG);
                    //fin ajout
        }

        @Override
        protected void onHandleIntent(Intent intent) {


            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

            try {
                // In the (unlikely) event that multiple refresh operations occur simultaneously,
                // ensure that they are processed sequentially.
                synchronized (TAG) {
                    // [START register_for_gcm]
                    // Initially this call goes out to the network to retrieve the token, subsequent calls
                    // are local.
                    // [START get_token]
                    InstanceID instanceID = InstanceID.getInstance(this);
                    String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
                            GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
                    // [END get_token]
                    Log.i(TAG, "GCM Registration Token: " + token);

                    // TODO: Implement this method to send any registration to your app's servers.
                    sendRegistrationToServer(token);

                    // Subscribe to topic channels
                    subscribeTopics(token);

                    // You should store a boolean that indicates whether the generated token has been
                    // sent to your server. If the boolean is false, send the token to your server,
                    // otherwise your server should have already received the token.
                    sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, true).apply();
                    // [END register_for_gcm]
                }
            } catch (Exception e) {
                Log.d(TAG, "Failed to complete token refresh", e);
                // If an exception happens while fetching the new token or updating our registration data
                // on a third-party server, this ensures that we'll attempt the update at a later time.
                sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false).apply();
            }
            // Notify UI that registration has completed, so the progress indicator can be hidden.
            Intent registrationComplete = new Intent(QuickstartPreferences.REGISTRATION_COMPLETE);
            LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);


        }

        /**
         * Handle action Foo in the provided background thread with the provided
         * parameters.
         */
        private void handleActionFoo(String param1, String param2) {
            // TODO: Handle action Foo
            throw new UnsupportedOperationException("Not yet implemented");
        }

        /**
         * Handle action Baz in the provided background thread with the provided
         * parameters.
         */
        private void handleActionBaz(String param1, String param2) {
            // TODO: Handle action Baz
            throw new UnsupportedOperationException("Not yet implemented");
        }


        private void subscribeTopics(String token) throws IOException {
            for (String topic : TOPICS) {
                GcmPubSub pubSub = GcmPubSub.getInstance(this);
                pubSub.subscribe(token, "/topics/" + topic, null);
            }
        }


        /**
         * Persist registration to third-party servers.
         *
         * Modify this method to associate the user's GCM registration token with any server-side account
         * maintained by your application.
         *
         * @param token The new token.
         */
        private void sendRegistrationToServer(String token) {
            // Add custom implementation, as needed.
        }

        private void sendTokenToServer(String token) {


        }


    }


    public class MyInstanceIDListenerService extends InstanceIDListenerService {
    public MyInstanceIDListenerService() {
    }

        @Override
        public IBinder onBind(Intent intent) {
                // TODO: Return the communication channel to the service.
                throw new UnsupportedOperationException("Not yet implemented");
        }

            // pour les notifs
        @Override
        public void onTokenRefresh() {
                // Fetch updated Instance ID token and notify our app's server of any changes (if applicable).
                Intent intent = new Intent(this, MyGcmRegistrationIntentService.class);
                startService(intent);
        }
    }

共有1个答案

巫煌
2023-03-14

你好,我找到了发生的事,我基本上忘了这件事


       @Override
        protected void onResume() {
            super.onResume();
            LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
                    new IntentFilter(QuickstartPreferences.REGISTRATION_COMPLETE));
        }

        @Override
        protected void onPause() {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
            super.onPause();
        }

 类似资料:
  • 我开始着手一个JavaFX项目,在这个项目中,我想添加一个复制的文本,而不必更改驱动程序中的格式和图像(它应该像open office一样工作)。图像应该能够放置在文本中不同的位置。因此,我需要一个可以处理rtf格式的控制字段。 为此,我找到了RichTextFX。文档中解释了如何使用Maven或Grandle运行RichTextFX。我不使用Maven或Grandle,因此我想知道是否有可能在不

  • 更新!!!! 观看缩进!我的插件部分在我的代码编辑器中缩进,因此它作为包主题的一部分读取。现在我至少有一个插件在工作,我觉得有点理智。现在开始调试另一个... 谢谢,留下这个以防其他人犯同样的错误! 作为参考: MKDocs 1.0.4 Pip 19.2.3 Python 3.8.1 很抱歉没有发布原始代码,因为这可能会有所帮助,因为需要另一个同事开发人员才能为我注意到这一点。 原帖子: 我不太确

  • 我觉得自己有点傻,但我就是不能让它发挥作用。。。。 我有一个现有的Android项目从我的另一台电脑复制,在文件夹中 (我在另一台pc上创建了该项目,将其复制到我的新pc上,然后另一台pc被分发)现在我想在Eclipse中打开该项目。所以我想我什么都试过了,但我似乎无法让它发挥作用。。。 我查找了类似于“”的内容,但没有找到它。 然后我尝试导入,但这不允许我导入它,因为它是相同的工作区(我使用相同

  • 我们有一个openshift容器平台url,它包含多个项目,如 项目1 项目2 项目3 每个项目都包含几个pod,我们目前正在使用NewRelic-like进行监控 pod1 pod2 pod3 我们正试图为所有这些项目分别实施普罗米修斯格拉法纳。 这与网上的文章太混乱了,因为它们都没有描述我们现在拥有的配置。 我们从哪里开始? 我们向泊坞窗映像添加了什么? 在openshift上是否有使用cAd

  • 本文向大家介绍Go实现短url项目的方法示例,包括了Go实现短url项目的方法示例的使用技巧和注意事项,需要的朋友参考一下 首先说一下这种业务的应用场景: 1.把一个长url转换为一个短url网址 2.主要用于微博,二维码,等有字数限制的场景 主要实现的功能分析: 1.把长url的地址转换为短url地址 2.通过短url获取对应的原始长url地址 3.相同长url地址是否需要同样的短url地址 这

  • 问题内容: 如果我已有使用和容器的Web应用程序。将Akka集成到其中的正确方法是什么? 就像我将要拥有的并且彼此交流一样。开始使用这些参与者的切入点是什么?(例如:1.放到那里2.更改配置3.获取对actor的引用) 我找到了http://doc.akka.io/docs/akka/2.2-M3/general/configuration.html,但是他没有给我胶水。只想获取集成的真实示例。