【问题标题】:Android push notification: Get data, store and display on new activity on click of notificationAndroid推送通知:点击通知获取数据,存储和显示新活动
【发布时间】:2014-02-19 04:59:43
【问题描述】:

我正在开发一个具有推送通知功能的应用程序。我以Android Push Notification的身份关注了以下链接

通过对 generateNotification() 的代码进行以下更改,我尝试并成功发送 URL 并在单击通知时打开网页。

/**
 * Issues a notification to inform the user that server has sent a message.
 */
private static void generateNotification(Context context, String message) {
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(R.drawable.ic_launcher, "Message received", System.currentTimeMillis());
    // Hide the notification after its selected
    notification.flags |= Notification.FLAG_AUTO_CANCEL;

    //adding LED lights to notification
    notification.defaults |= Notification.DEFAULT_LIGHTS;

    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setData(Uri.parse(message));
    //startActivity(browserIntent);

    //PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
    notification.setLatestEventInfo(context, "Message", "New message received", pendingIntent);
    notificationManager.notify(0, notification);

我可以在服务器推送通知的帮助下发送数据。 现在我想要执行以下任务:

  1. 通过推送通知发送 JSON 数据。

  2. 将数据保存到 SQLite 数据库中。

  3. 点击推送通知打开新活动。

  4. 显示来自新活动推送通知的数据。

  5. 如果应用程序关闭,点击通知后应用程序启动。

所以请指导我应该按照哪些步骤来执行上述任务。

【问题讨论】:

  • 你要不要在旁边加个敷料?

标签: android notifications push-notification google-cloud-messaging android-notifications


【解决方案1】:

我解决了以下问题:

  1. 通过推送通知发送 JSON 数据。 A. 可以借助大小为 4kb 的 PHP JSON 服务从 SERVER 发送数据。

  2. 将数据保存到 SQLite 数据库中。 A. onMessage()中数据来自推送通知时将数据保存在SQLite中

    protected void onMessage(Context context, Intent intent) {
        Log.i(TAG, "Received message");
        String message = intent.getExtras().getString("price");
        Log.d("OnMSG",message);
    
        displayMessage(context, message);
    
        DataBaseHelper dataBaseHelper = new DataBaseHelper(context);
        dataBaseHelper.openDataBase();
        dataBaseHelper.insertData(message);
        dataBaseHelper.close();
    
        // notifies user
        generateNotification (context, message);
    }
    
  3. 点击推送通知打开新活动。 A. 我在从 onMessage() 调用的生成通知函数中使用未决意图来完成此操作。

    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);
        Notification notification = new Notification(icon, message, when);
    
        String title = context.getString(R.string.app_name);
    
        Intent notificationIntent = new Intent(context, MainActivity.class);
        notificationIntent.putExtra("ms", message);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        notification.setLatestEventInfo(context, title, message, intent);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
    
        notification.defaults |= Notification.DEFAULT_SOUND;
    
        notification.defaults |= Notification.DEFAULT_VIBRATE;
        notificationManager.notify(0, notification);     
    }
    
  4. 显示来自新活动推送通知的数据。 A. 当点击通知时调用新活动时(从上面的第 3 点代码)我在主活动 onCreate() 中从 SQLite 获取数据,就可以实现这一点。

    DataBaseHelper dataBaseHelper = new DataBaseHelper(this);
    dataBaseHelper.openDataBase();
    Cursor c = dataBaseHelper.getData();
    String data = null;
    if(c.getCount()>0){
        if(c.moveToFirst()){
            do{
            data = c.getString(0);
        } while(c.moveToNext());
        }
    } else {
        data = "No Data";
    }
    
  5. 如果应用程序已关闭,则单击通知后应用程序将启动。 A. 这个任务是从第 3 点开始完成的。

【讨论】:

    【解决方案2】:

    GCMIntentService.java

    import com.google.android.gcm.GCMBaseIntentService;
    import com.google.android.gcm.GCMRegistrar;
    
    import android.app.Notification;
    import android.app.NotificationManager;
    import android.app.PendingIntent;
    import android.content.Context;
    import android.content.Intent;
    import android.media.RingtoneManager;
    import android.net.Uri;
    import android.util.Log;
    /**
     * IntentService responsible for handling GCM messages.
     */
    public class GCMIntentService extends GCMBaseIntentService {
    
        @SuppressWarnings("hiding")
        private static final String TAG = "GCMIntentService";
    
        public GCMIntentService() {
            super(SENDER_ID);
        }
    
        @Override
        protected void onRegistered(Context context, String registrationId) {
            Log.i(TAG, "Device registered: regId = " + registrationId);
            displayMessage(context,"onregisterd");
            ServerUtilities.register(context, registrationId);
        }
    
        @Override
        protected void onUnregistered(Context context, String registrationId) {
            Log.i(TAG, "Device unregistered");
            displayMessage(context, "GCM unregistered");
            if (GCMRegistrar.isRegisteredOnServer(context)) {
                ServerUtilities.unregister(context, registrationId);
            } else {
                // This callback results from the call to unregister made on
                // ServerUtilities when the registration to the server failed.
                Log.i(TAG, "Ignoring unregister callback");
            }
        }
    
        @Override
        protected void onMessage(Context context, Intent intent) {
            Log.i(TAG, "Received message");
            String message =intent.getExtras().getString("message");
            displayMessage(context, message);
            // notifies user
            generateNotification(context,message );
        }
    
        @Override
        protected void onDeletedMessages(Context context, int total) {
            Log.i(TAG, "Received deleted messages notification");
            String message = ("total deleted"+ total);
            displayMessage(context, message);
            // notifies user
            generateNotification(context, message);
        }
    
        @Override
        public void onError(Context context, String errorId) {
            Log.i(TAG, "Received error: " + errorId);
            displayMessage(context, ("error:"+ errorId));
        }
    
        @Override
        protected boolean onRecoverableError(Context context, String errorId) {
            // log message
            Log.i(TAG, "Received recoverable error: " + errorId);
            displayMessage(context, ("Recover error:"+ errorId));
            return super.onRecoverableError(context, errorId);
        }
    
        /**
         * Issues a notification to inform the user that server has sent a message.
         */
        private static void generateNotification(Context context, String message) {
            int icon = R.drawable.icon;
            long when = System.currentTimeMillis();
            NotificationManager notificationManager = (NotificationManager)
                    context.getSystemService(Context.NOTIFICATION_SERVICE);
            Notification notification = new Notification(icon, "Dear Customer , New Product has been Launched", when);
            Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            notification.sound=soundUri;
            String title = context.getString(R.string.app_name);
            Intent notificationIntent = new Intent(context, lap_gcm.class);
            notificationIntent.putExtra("message", 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, PendingIntent.FLAG_CANCEL_CURRENT);
            notification.setLatestEventInfo(context, title, message, intent);
            notification.flags |= Notification.FLAG_AUTO_CANCEL;
            notificationManager.notify(0, notification);
        }
    
    }
    

    结果活动

    lap_gcm.java

    import android.app.Activity;
    import android.os.Bundle;
    import android.webkit.WebView;
    
    public class lap_gcm extends Activity{
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            String message=getIntent().getStringExtra("message");
            //Here is Your message
    
            }
        }
    

    此代码基于您提到的我在我开发的一个应用程序中使用的博客。这将在用户单击通知时显示收到新通知并打开新活动的通知。

    始终发送不要通过推送通知发送所有数据。您只需发送一些小消息,例如数据,然后从服务器中提取数据,一旦您的设备收到消息,然后将其存储在数据库中。

    【讨论】:

    • 您能否告诉我如何在应用未运行时在点击通知时显示新活动的推送通知数据。
    • Intent notificationIntent = new Intent(context, lap_gcm.class); notificationIntent.putExtra("message", message);在 generateNotification 看到这个我通过意图发送消息到活动
    • 我也照做了,但点击通知数据时没有显示。
    • 您是否创建了 lap_gcm 活动。你必须启动你的活动
    【解决方案3】:

    通过推送通知发送 JSON 数据

    您可以将 JSON 作为数据从服务器端代码发送到通知消息中。收到通知后,您将在消息中收到一个 JSON,您可以在其中做任何您想做的事情。

    将数据保存到 SQLite 数据库中

    这很简单,根据您的要求,您可以插入 JSON 中接收到的任何数据。解析后可以从JSON中获取数据。

    点击推送通知打开新活动。

    你可以像下面那样做

    mNotificationManager = (NotificationManager)
            this.getSystemService(Context.NOTIFICATION_SERVICE);
    
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, YourActivity.class), 0);
    
    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
    .setSmallIcon(R.drawable.ic_stat_gcm)
    .setContentTitle("GCM Notification")
    .setStyle(new NotificationCompat.BigTextStyle()
    .bigText(msg))
    .setContentText(msg);
    
    mBuilder.setContentIntent(contentIntent);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    

    显示来自新活动推送通知的数据。

    您可以显示从推送消息接收到的任何数据,但您必须解析 JSON。

    如果应用程序已关闭,则在单击通知后应用程序将启动。

    我上面的代码在这种情况下也适用于你。

    查看这里的 JSON 解析:http://www.vogella.com/tutorials/AndroidJSON/article.html

    总而言之,您必须将数据以 JSON 形式添加到服务器 cod 中,当您从服务器推送 GCM 并稍后执行解析 JSON 并执行您想要的任何操作时,您将获得这些数据。

    【讨论】:

    • 新 NotificationCompat.Builder(this);在 Android Oreo 中已弃用,请查看文档并使用通知通道实现。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-09
    相关资源
    最近更新 更多