1

В настоящее время я работаю над GCM (облачная служба Google), я хотел бы, чтобы пользователь запустил приложение, когда они нажимают на полученное уведомление, проблема в том, что он не может точно проверить было ли приложение запущено, поэтому он всегда запускает новую активность, даже если приложение уже запущено. БлагодаряНажмите на уведомление и запустите приложение в android

Приемник

public class GcmBroadcastReceiver extends WakefulBroadcastReceiver{ 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     // TODO Auto-generated method stub 

     // Explicitly specify that GcmIntentService will handle the intent. 
     ComponentName comp = new ComponentName(context.getPackageName(), 
       GcmIntentService.class.getName()); 
     // Start the service, keeping the device awake while it is launching. 
     startWakefulService(context, (intent.setComponent(comp))); 
     setResultCode(Activity.RESULT_OK); 

    } 

} 

Намерение обработчик

public class GcmIntentService extends IntentService{ 
    Context context; 
    public static final int NOTIFICATION_ID = 1; 
    private NotificationManager mNotificationManager; 
    NotificationCompat.Builder builder; 
    public static final String TAG = "GCM"; 

    public GcmIntentService() { 
     super("GcmIntentService"); 
     // TODO Auto-generated constructor stub 
    } 

    @Override 
    protected void onHandleIntent(Intent intent) { 
     // TODO Auto-generated method stub 
     Bundle extras = intent.getExtras(); 
     String msg = null; 
     msg = intent.getStringExtra("message"); 
     GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this); 
     String messageType = gcm.getMessageType(intent); 

     if (!extras.isEmpty()) { 

      if (GoogleCloudMessaging. 
         MESSAGE_TYPE_SEND_ERROR.equals(messageType)) { 
        sendNotification("Send error: " + extras.toString()); 
       } else if (GoogleCloudMessaging. 
         MESSAGE_TYPE_DELETED.equals(messageType)) { 
        sendNotification("Deleted messages on server: " + 
          extras.toString()); 
       // If it's a regular GCM message, do some work. 
       } else if (GoogleCloudMessaging. 
         MESSAGE_TYPE_MESSAGE.equals(messageType)) { 
        // This loop represents the service doing some work. 
        for (int i=0; i<5; i++) { 
         Log.i(TAG, "Working... " + (i+1) 
           + "/5 @ " + SystemClock.elapsedRealtime()); 
         try { 
          Thread.sleep(500); 
         } catch (InterruptedException e) { 
         } 
        } 
        Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime()); 
        // Post notification of received message. 
        //sendNotification("Received: " + extras.toString()); 
        sendNotification(msg); 
        Log.i(TAG, "Received: " + extras.toString()); 
       } 
      } 
     GcmBroadcastReceiver.completeWakefulIntent(intent); 
    } 

    private void sendNotification(String msg) { 
     mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE); 
     String notifyMsg = ""; 
     JSONTokener tokener = new JSONTokener(msg); 

     if (tokener != null) { 
      try { 
       notifyMsg = new JSONObject(tokener).getString("msg"); 
      } catch (JSONException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
     } 

     Intent myintent = new Intent(this, MainActivity.class); 
     myintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
     PendingIntent contentIntent = PendingIntent.getActivity(this, 0, myintent, PendingIntent.FLAG_UPDATE_CURRENT); 

     NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) 
     .setSmallIcon(R.drawable.ic_launcher) 
     .setContentTitle(getResources().getString(R.string.notification_title)) 
     .setStyle(new NotificationCompat.BigTextStyle() 
     .bigText(notifyMsg)) 
     .setContentText(notifyMsg) 
     .setContentIntent(contentIntent); 

     mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); 
    } 
} 
+0

Это потому, что ваше приложение не работает в фоновом режиме, поэтому, когда вы нажимаете на уведомления, он всегда запускает приложение снова. –

ответ

1

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

Вашего код

private void sendNotification(String msg) { 
    mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE); 
    String notifyMsg = ""; 
    JSONTokener tokener = new JSONTokener(msg); 

    if (tokener != null) { 
     try { 
      notifyMsg = new JSONObject(tokener).getString("msg"); 
     } catch (JSONException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 

    Intent myintent = new Intent(this, MainActivity.class); 
    myintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, myintent, PendingIntent.FLAG_UPDATE_CURRENT); 

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) 
    .setSmallIcon(R.drawable.ic_launcher) 
    .setContentTitle(getResources().getString(R.string.notification_title)) 
    .setStyle(new NotificationCompat.BigTextStyle() 
    .bigText(notifyMsg)) 
    .setContentText(notifyMsg) 
    .setContentIntent(contentIntent); 

    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); 
} 

отредактирован Код:

private void sendNotification(String msg) { 
    mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE); 
    String notifyMsg = ""; 
    JSONTokener tokener = new JSONTokener(msg); 

    if (tokener != null) { 
     try { 
      notifyMsg = new JSONObject(tokener).getString("msg"); 
     } catch (JSONException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 

    Intent myintent = new Intent(this, MainActivity.class); 
    myintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);//changes 
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, myintent, PendingIntent.FLAG_UPDATE_CURRENT); 

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) 
    .setSmallIcon(R.drawable.ic_launcher) 
    .setContentTitle(getResources().getString(R.string.notification_title)) 
    .setStyle(new NotificationCompat.BigTextStyle() 
    .bigText(notifyMsg)) 
    .setContentText(notifyMsg) 
    .setContentIntent(contentIntent); 

    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); 
} 

Надеется, что это поможет.

1

По андроида документы, вам нужно использовать режим singleTop запуска для вашей деятельности.

The "standard" and "singleTop" modes differ from each other in just one respect: Every 
time there's new intent for a "standard" activity, a new instance of the class is created 
to respond to that intent. Each instance handles a single intent. Similarly, a new 
instance of a "singleTop" activity may also be created to handle a new intent. However, if 
the target task already has an existing instance of the activity at the top of its stack, 
that instance will receive the new intent (in an onNewIntent() call); a new instance is 
not created. In other circumstances — for example, if an existing instance of the 
"singleTop" activity is in the target task, but not at the top of the stack, or if it's at 
the top of a stack, but not in the target task — a new instance would be created and 
pushed on the stack. 
Смежные вопросы