0

我正在使用包含在 android sdk 文件夹中的 android 推送通知的示例代码。我面临一个问题,即当我在通知栏中单击通知时,它会显示一个空白活动,我也尝试使用显示警报对话,但如果我在活动中,那么它将显示消息(在 TextView 中)和警报对话也不会。我该怎么做才能显示消息。我只想在单击通知时显示警报对话框。

GCMIntentService.java

package com.example.testgcm;

import static com.example.testgcm.CommonUtilities.SENDER_ID;
import static com.example.testgcm.CommonUtilities.displayMessage;

import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;
import com.google.android.gcm.GCMBaseIntentService;


public class GCMIntentService extends GCMBaseIntentService{

    public GCMIntentService()
    {
        super(SENDER_ID);
    }

    @Override
    public void onRegistered(Context context, String regId)
    {
        Log.i(TAG, "Device registered: regId = " + regId);
        String msg="Your device registred with GCM"+regId;
        //displayMessage(context, msg);
        /*Log.d("NAME", MainActivity.name);
        Server.register(context, MainActivity.name, regId);*/

    }

    @Override
    public void onUnregistered(Context context, String regId)
    { 
        Log.i(TAG, "Device unregistered");
        displayMessage(context, getString(R.string.gcm_unregistered));
        Server.unregister(context, regId);
    }

    @Override
    public void onMessage(Context context, Intent intent)
    {
        String message = intent.getExtras().getString("message");
        Log.i(TAG, "Received message");
        Log.i("Message: ", message);

        displayMessage(context, message);

        // notifies user
        generateNotification(context, message);
    }

    @Override
    protected void onError(Context context, String errorMsg) {
        Log.i(TAG, "Received error: " + errorMsg);
        displayMessage(context, getString(R.string.gcm_error, errorMsg));

    }

    @Override
    protected boolean onRecoverableError(Context context, String errorMsg) {
        Log.i(TAG, "Received recoverable error: " + errorMsg);
        displayMessage(context, getString(R.string.gcm_recoverable_error,errorMsg));
        return super.onRecoverableError(context, errorMsg);
    }

     @SuppressWarnings("deprecation")
    private static void generateNotification(Context context, String message) {
            int icon = R.drawable.ic_launcher;
            long when = System.currentTimeMillis();
            NotificationManager notificationManager = (NotificationManager)
                    context.getSystemService(Context.NOTIFICATION_SERVICE);
            @SuppressWarnings("deprecation")
            Notification notification = new Notification(icon, message, when);

            String title = context.getString(R.string.app_name);

            Intent notificationIntent = new Intent(context, MainActivity.class);
            notificationIntent.putExtra("NEW", message);
            // set intent so it does not start a new activity
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
                    Intent.FLAG_ACTIVITY_SINGLE_TOP);

            PendingIntent intent =
                    PendingIntent.getActivity(context, 0, notificationIntent, 0);
            notification.setLatestEventInfo(context, title, message, intent);
            notification.flags |= Notification.FLAG_AUTO_CANCEL;

            // Play default notification sound
            notification.defaults |= Notification.DEFAULT_SOUND;

            // Vibrate if vibrate is enabled
            notification.defaults |= Notification.DEFAULT_VIBRATE;
            notificationManager.notify(0, notification);     
        }

}

MainActivity.java

package com.example.testgcm;

import static com.example.testgcm.CommonUtilities.DISPLAY_MESSAGE_ACTION;
import static com.example.testgcm.CommonUtilities.EXTRA_MESSAGE;
import static com.example.testgcm.CommonUtilities.SENDER_ID;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gcm.GCMRegistrar;



public class MainActivity extends Activity {

    AsyncTask<Void, Void, Void> mRegisterTask;
    TextView mDisplay;

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


        mDisplay = (TextView) findViewById(R.id.display);

        GCMRegistrar.checkDevice(this);
        GCMRegistrar.checkManifest(this);

        registerReceiver(mHandleMessageReceiver, new IntentFilter(
                DISPLAY_MESSAGE_ACTION));

        final String regId = GCMRegistrar.getRegistrationId(this);
        if (regId.equals("")) 
        {
            GCMRegistrar.register(this, SENDER_ID);
            String rid=GCMRegistrar.getRegistrationId(this);
            Log.e("Registration ID: ", rid);
            Toast.makeText(getApplicationContext(), "Registration ID: " + rid, Toast.LENGTH_LONG).show();
            mDisplay.append("Registration ID: " + regId);
        } 
        else 
        {
            if (GCMRegistrar.isRegisteredOnServer(this)) 
            {
                Log.v(getClass().getSimpleName(), "Already registered");
                Log.e("Registration ID: ", regId);
                Toast.makeText(getApplicationContext(), "Registration ID: " + regId, Toast.LENGTH_LONG).show();
                mDisplay.append("Registration ID: \n" + regId);
            }
            else
            {
                final Context context = this;
                mRegisterTask = new AsyncTask<Void, Void, Void>() {

                    @Override
                    protected Void doInBackground(Void... arg0) {
                        // TODO Auto-generated method stub

                        //   Server.register(context, name,  regId);

                        return null;
                    }
                    @Override
                    protected void onPostExecute(Void result) {
                        mRegisterTask = null;
                    }   
                };
                mRegisterTask.execute(null, null, null);
            }
        }
    }

    private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);

            String message = intent.getExtras().getString("NEW");
            // Waking up mobile if it is sleeping
            WakeLocker.acquire(getApplicationContext());

            // Showing received message
            mDisplay.append(newMessage + "\n");
        //  Toast.makeText(getApplicationContext(), newMessage, Toast.LENGTH_LONG).show();
            displayAlert(newMessage);
            //  displayAlert( newMessage);

            // Releasing wake lock
            WakeLocker.release();
        }
    };

    @Override
    protected void onDestroy() {
        if (mRegisterTask != null) {
            mRegisterTask.cancel(true);
        }
        try {
            unregisterReceiver(mHandleMessageReceiver);
            GCMRegistrar.onDestroy(this);
        } catch (Exception e) {
            Log.e("UnRegister Receiver Error", "> " + e.getMessage());
        }
        super.onDestroy();
    }

    private void displayAlert(String message)
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(message).setCancelable(
                false).setPositiveButton("Yes",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                }).setNegativeButton("No",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }
}

CommonUtilities.java

package com.example.testgcm;

import android.content.Context;
import android.content.Intent;

public class CommonUtilities {

    static final String SERVER_URL = "http://10.0.2.2/api/Product?";

    // Google project id
    static final String SENDER_ID = "xxxxxxxxxxxxx"; 

    static final String TAG = "Test App";

    static final String DISPLAY_MESSAGE_ACTION =
            "com.example.testgcm.DISPLAY_MESSAGE";

    static final String EXTRA_MESSAGE = "message";

    static void displayMessage(Context context, String message) {
        Intent intent = new Intent(DISPLAY_MESSAGE_ACTION);
        intent.putExtra(EXTRA_MESSAGE, message);
        context.sendBroadcast(intent);
    }
}
4

2 回答 2

0

The problem is that the piece of code that sends the message broadcast intent gets executed when the notifications arrives, but not when the user opens the notification.

@Override
public void onMessage(Context context, Intent intent)
{
    String message = intent.getExtras().getString("message");
    Log.i(TAG, "Received message");
    Log.i("Message: ", message);

    displayMessage(context, message);

    // notifies user
    generateNotification(context, message);
}

At the point where displayMessage(context, message) is executed, there's no BroadcastListener to catch your message event.

However, if the user has the activity open an another notification arrives, it will be displayed, since you have registered the listener within the activity context.

You should set the message to the TextView and on the MainActivity.onCreate or MainActivity.onResume method considering that you already have the "MSG" extra at that point. Leave the broadcaste receiver to update the activity textview everytime a new notification arrives.

于 2012-11-17T04:07:34.257 回答
0

检查您是否已在AndroidManifest.xml

于 2015-10-08T11:17:30.767 回答