Насочено известие за Android: Вземете данни, съхранявайте и показвайте нова дейност при щракване върху известие

Разработвам приложение, което има функционалност за насочени известия. Проследих следната връзка като насочено известие за Android

Опитах се и успешно да изпратя URL адрес и да отворя уеб страницата при щракване върху известие, като направих следната промяна в кода на generateNotification().

/**
 * 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. Ако приложението е затворено, след като кликнете върху известието, приложението ще започне.

Така че, моля, насочете ме какви стъпки трябва да следвам, за да изпълня горната задача.


comment
Искате ли дресинг отстрани?   -  person Sherif elKhatib    schedule 21.02.2014


Отговори (3)


Реших проблемите като:

  1. Изпращайте JSON данни чрез насочено известие. A. Възможност за изпращане на данни от СЪРВЪР с помощта на PHP JSON услуга с размер 4kb.

  2. Запазете данните в SQLite база данни. A. Записва данните в SQLite, когато данните идват от насочено известие в onMessage()

    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. Отворете нова дейност при щракване върху насочено известие. О. Направих това, използвайки чакащо намерение във функцията за генериране на известия, извикана от 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. Показване на данни, идващи от насочено известие за нова дейност. О. Това се постига, когато нова дейност се извиква при щракване върху известие (от горния код на точка 3), получавам данни от SQLite в основната дейност onCreate().

    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. Ако приложението е затворено, след като кликнете върху известието, приложението ще започне. А. Тази задача се постига от точка № 3.

person Manoj Fegde    schedule 26.02.2014

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

        }
    }

Тази кодова база в блога, който споменахте, използвах в едно от моите приложения, които разработвам. Това ще покаже известие при получаване на ново известие и ще отвори нова дейност, когато потребителят щракне върху известието.

Винаги изпращай не изпращай всички данни чрез насочено известие. просто изпращате малко съобщение като данни, след което изтегляте данните от сървъра, след като съобщението е получено във вашето устройство, след това го съхранявайте в db.

person CoolMonster    schedule 21.02.2014
comment
Можете ли да ми дадете стъпките как да показвам данни за насочено известие при нова дейност при щракване върху известие, когато приложението не работи. - person Manoj Fegde; 21.02.2014
comment
Intent notificationIntent = ново намерение (контекст, lap_gcm.class); notificationIntent.putExtra(съобщение, съобщение); в generateNotification вижте това изпратих съобщението чрез намерение за дейност - person CoolMonster; 21.02.2014
comment
Следвах същото, но при щракване върху данните за известия не се показват. - person Manoj Fegde; 21.02.2014
comment
създадохте ли дейност lap_gcm. Трябва да стартирате дейността си - person CoolMonster; 21.02.2014

Изпращайте 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 в кода на вашия сървър, който бихте получили, когато избутате GCM от сървъра и по-късно извършите анализ на JSON и правите каквото искате.

person Ajay S    schedule 22.02.2014
comment
нов NotificationCompat.Builder(това); е остарял в Android Oreo, моля, проверете документите и използвайте внедряването на Notification Channel. - person TapanHP; 26.04.2018