2

Я сначала делал приложение по видео уроку https://youtu.be/XM3THjZkRQM Там о том как получать уведомления от GCM и показывать уведомления в трее. Приложение работает. Но у меня задача немного отличается от видео урока. С сервера в GCM отправляется сообщение, от GCM оно принимается сервисом, и вот дальше в сервисе надо вместо показа пуш уведомления в трее, отправить определённую команду в активити приложения (и в приложении будет много разных активити, так что надо, чтобы эту команду приняла та активити, которая в данный момент открыта). Я решил начать с малого и попробовать сделать приём сообщения в MainActivity. Там уже реализован BroadCastReceiver, который был в уроке. Но он был настроен на приём статуса регистрации в GCM.

Вот код главной активити:

public class MainActivity extends AppCompatActivity {
    private BroadcastReceiver mRegistrationBroadcastReciever;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mRegistrationBroadcastReciever = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Log.d("INTENT",intent.getAction());
                if(intent.getAction().equals(GCMRegistrationIntentService.REGISTRATION_SUCCESS)){
                    String token = intent.getStringExtra("token");
                    Toast.makeText(getApplicationContext(),"GCM token: "+token, Toast.LENGTH_LONG).show();
                }
                else if(intent.getAction().equals(GCMRegistrationIntentService.REGISTRATION_ERROR)){
                    Toast.makeText(getApplicationContext(),"GCM registration error!!!!", Toast.LENGTH_LONG).show();
                }
                else {
                    //tobe define
                }
            }
        };

        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());

        if(ConnectionResult.SUCCESS != resultCode){
            if(GooglePlayServicesUtil.isUserRecoverableError(resultCode)){
                Toast.makeText(getApplicationContext(),"Google Play Service is not installed/enable in this device", Toast.LENGTH_LONG).show();
                GooglePlayServicesUtil.showErrorNotification(resultCode,getApplicationContext());
            }
            else {
                Toast.makeText(getApplicationContext(),"This device do not support Google Play Service", Toast.LENGTH_LONG).show();
            }
        }
        else{
            Intent intent=new Intent(this,GCMRegistrationIntentService.class);
            startService(intent);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.w("Main Activity","onResume");
        LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReciever,
                new IntentFilter(GCMRegistrationIntentService.REGISTRATION_SUCCESS));
        LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReciever,
                new IntentFilter(GCMRegistrationIntentService.REGISTRATION_ERROR));
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.w("Main Activity","onPause");
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReciever);
    }
}

А вот файл манифеста:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="test3.gcmtest">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <permission
        android:name="test3.gcmtest.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />
    <uses-permission android:name="test3.gcmtest.permission.C2D_MESSAGE" />


    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver
            android:name="com.google.android.gms.gcm.GcmReceiver"
            android:exported="true"
            android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE"/>
                <category android:name="test3.gcmtest"/>
            </intent-filter>
        </receiver>

        <service android:name=".GCMPushReceiverService" android:exported="false">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE"/>
            </intent-filter>
        </service>
        <service android:name=".GCMRegistrationIntentService" android:exported="false">
            <intent-filter>
                <action android:name="com.google.android.gms.iid.InstanceID"/>
            </intent-filter>
        </service>

    </application>

</manifest>

Это сервис, который отвечает за приём сообщений от GCM и показ пушей:

public class GCMPushReceiverService extends GcmListenerService {
    @Override
    public void onMessageReceived(String from, Bundle data) {
        String message = data.getString("message");
        String messageType = data.getString("messagetype");
        Log.w("MESSAGE_TYPE",messageType);
        if(messageType.equals("push")){
            Log.d("START","sender");
            Intent pushIntent=new Intent("pusher");
            LocalBroadcastManager.getInstance(this).sendBroadcast(pushIntent);
        }
        else {
            sendNotification(message);
        }

    }

    private void sendNotification(String message){
        Intent intent = new Intent(this,MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        int requestCode = 0;
        PendingIntent pendingIntent=PendingIntent.getActivity(this, requestCode,intent,PendingIntent.FLAG_ONE_SHOT);
        Uri sound= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder noBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentText("My GCM message")
                .setContentText(message)
                .setAutoCancel(true)
                .setContentIntent(pendingIntent);
        NotificationManager notificationManager= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0,noBuilder.build());
    }
}

В нём мне надо обработать полученное сообщение и вытащить ключ, в котором будет тип сообщения. В одном случае должен сработать пуш в трее, а вдругом случае надо в главной активити запустить определённое действите (потом там надо будет в текстовом поле определённое значение менять)

Первый вопрос: правильно ли я отправляю интент?

                Intent pushIntent=new Intent("pusher");
                LocalBroadcastManager.getInstance(this).sendBroadcast(pushIntent);

Второй вопрос: как правильно этот интент принять в MainActivity?

1 ответ 1

2

Пока ждал ответа, сам разобрался))

Я не знаю почему до этого не получалось, но сделал так (В любой активити, не только в главной):

    @Override
    protected void onResume() {
        super.onResume();
        LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
                new IntentFilter(GCMPushReceiverService.MESSAGE_SENDER));
    }


    private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //Действие, которое надо выполнить при получении сообщения:
            String message = intent.getStringExtra("message");
            Log.d("receiver", "Got message: "+message);
            testTXT.setText(testTXT.getText()+"\n"+message);
        }
    };

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

Где GCMPushReceiverService.MESSAGE_SENDER это статическая текстовая константа, которая содержит имя пакета и произвольное название. Но я не думаю что её содержимое должно содержать название пакета.

Так же в решении вопроса помог этот источник: http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.