Push-уведомление Android: получайте данные, сохраняйте и отображайте их при новой активности по щелчку уведомления.

Я разрабатываю приложение с функцией push-уведомлений. Я перешел по следующей ссылке как Пуш-уведомление 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);

Я могу отправить данные с помощью push-уведомления с сервера. Теперь я хочу выполнить следующие задачи:

  1. Отправлять данные JSON через push-уведомления.

  2. Сохраните данные в базе данных SQLite.

  3. Открытие новой активности по щелчку push-уведомления.

  4. Отображение данных, поступающих из push-уведомлений о новой активности.

  5. Если приложение закрыто, то после нажатия на уведомление приложение запустится.

Поэтому, пожалуйста, помогите мне, какие шаги я должен выполнить, чтобы выполнить вышеуказанную задачу.


comment
Хотите повязку на боку?   -  person Sherif elKhatib    schedule 21.02.2014


Ответы (3)


Я решил проблемы как:

  1. Отправлять данные JSON через push-уведомления. A. Возможность отправки данных с СЕРВЕРА с помощью службы PHP JSON размером 4 КБ.

  2. Сохраните данные в базе данных SQLite. A. Сохранены данные в SQLite, когда данные поступают из push-уведомления в 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. Открытие новой активности по щелчку push-уведомления. О. Я сделал это, используя ожидающее намерение в функции генерации уведомлений, вызываемой из 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. Отображение данных, поступающих из push-уведомлений о новой активности. A. Это достигается тем, что когда новая активность вызывается по щелчку уведомления (из приведенного выше кода пункта 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. Если приложение закрыто, то после нажатия на уведомление приложение запустится. A. Эта задача достигается с точки № 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

        }
    }

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

Всегда отправлять, не отправлять все данные через push-уведомления. Вы просто отправляете небольшое сообщение, такое как данные, затем извлекаете данные с сервера, как только сообщение получено на вашем устройстве, а затем сохраняете его в БД.

person CoolMonster    schedule 21.02.2014
comment
Не могли бы вы дать мне шаги, как отображать данные push-уведомления о новой активности при нажатии уведомления, когда приложение не запущено. - person Manoj Fegde; 21.02.2014
comment
Уведомление о намеренииIntent = новое намерение (контекст, lap_gcm.class); уведомлениеIntent.putExtra(сообщение, сообщение); в generateNotification см. это, я отправил сообщение через намерение к действию - person CoolMonster; 21.02.2014
comment
Я следовал тому же, но при нажатии на данные уведомления не отображаются. - person Manoj Fegde; 21.02.2014
comment
Вы создали активность lap_gcm. Вы должны запустить свою деятельность - person CoolMonster; 21.02.2014

Отправить данные JSON через push-уведомление

Вы можете отправить JSON в качестве данных в уведомлении из кода на стороне сервера. Как только вы получите уведомление, вы получите JSON в сообщении, где вы можете делать все, что хотите.

Сохраните данные в базе данных SQLite

Это просто в соответствии с вашим требованием, вы можете вставить данные, полученные в JSON. Вы можете получить данные из JSON после разбора.

Открытие новой активности по щелчку push-уведомления.

Вы можете сделать, как показано ниже

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());

Отображение данных, поступающих из push-уведомлений о новой активности.

Вы можете отображать данные, полученные из push-сообщения, но вам нужно проанализировать 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, пожалуйста, проверьте документы и используйте реализацию канала уведомлений. - person TapanHP; 26.04.2018