2016-03-28 3 views
0

Я имею GCM с PHP и мой код работать без каких-либо проблем его идея получить уведомление от PHP и показать его на панели уведомлений и когда щелчок по уведомлению его показать мне сообщение на TextView я просто хотите обновить эту TextView на операцию без щелчка по уведомлениюандроид изменение TextView из другого класса

теперь позвольте мне показать код понять меня этого дома активность то будет содержать TextView

import android.app.Activity; 
    import android.os.Bundle; 
    import android.widget.TextView; 


    public class Home_Activity extends Activity { 
    TextView view_msg; 
// i try make it public static TextView view_msg; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.home); 

    view_msg = (TextView) findViewById(R.id.message); 
    } 
    public void onResume() 
    { 
    super.onResume(); 
    String str = getIntent().getStringExtra("msg"); 
    if (str != null) { 
     view_msg.setText(str); 
    } 
    } 
    } 

мы можем увидеть его

onResume

проверить, есть ли какие-либо дополнительные данные, но я хочу, чтобы обновить эту TextView только тогда, когда новое сообщение гсм Получать

теперь код, который Получать сообщения

import android.app.IntentService; 
import android.app.Notification; 
import android.app.NotificationManager; 
import android.app.PendingIntent; 
import android.content.Context; 
import android.content.Intent; 
import android.os.Bundle; 
import android.support.v4.app.NotificationCompat; 

import com.medo.alex.Home_Activity; 
import com.medo.alex.R; 
import com.google.android.gms.gcm.GoogleCloudMessaging; 


public class Gcm_Notification_Intent_Service extends IntentService { 
// Sets an ID for the notification, so it can be updated 
public static final int notifyID = 9001; 

public Gcm_Notification_Intent_Service() { 
    super("GcmIntentService"); 
} 


@Override 
protected void onHandleIntent(Intent intent) { 
    Bundle extras = intent.getExtras(); 
    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()); 
     } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE 
       .equals(messageType)) { 

      sendNotification("" + extras.get(Gcm_Application_Constants.MSG_KEY)); //When Message is received normally from GCM Cloud Server 
     } 
    } 
    Gcm_Broadcast_Receiver.completeWakefulIntent(intent); 
} 

private void sendNotification(String msg) { 
    Intent resultIntent = new Intent(this, Home_Activity.class); 
    resultIntent.putExtra("msg", msg); 
    PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, 
      resultIntent, PendingIntent.FLAG_ONE_SHOT); 

    NotificationCompat.Builder mNotifyBuilder; 
    NotificationManager mNotificationManager; 

    mNotificationManager = (NotificationManager)  getSystemService(Context.NOTIFICATION_SERVICE); 

    mNotifyBuilder = new NotificationCompat.Builder(this) 
      .setContentTitle("NEW MESSAGE") 
      .setSmallIcon(R.mipmap.ic_launcher); 
    // Set pending intent 
    mNotifyBuilder.setContentIntent(resultPendingIntent); 

    // Set Vibrate, Sound and Light 
    int defaults = 0; 
    defaults = defaults | Notification.DEFAULT_LIGHTS; 
    defaults = defaults | Notification.DEFAULT_VIBRATE; 
    defaults = defaults | Notification.DEFAULT_SOUND; 

    mNotifyBuilder.setDefaults(defaults); 
    // Set the content for Notification 
    mNotifyBuilder.setContentText("YOU HAVE NEW MESSAGE"); 
    // Set autocancel 
    mNotifyBuilder.setAutoCancel(true); 
    // Post a notification 
    mNotificationManager.notify(notifyID, mNotifyBuilder.build()); 


    // MainActivity.view_msg.setText(msg); // iam try use this and make my view_msg public and static when i add this line and run my project and say progect name has stopped just when add this line 
    } 
} 

теперь мой вопрос о том, как обновить view_msg и его на Home_activity при возврате messgae из Gcm i пишу в коде, что я пытаюсь сделать, но его сказать, что мой проект был st опнут Теперь ПОЗАБЫТЬ попытки и просто дать мне представление о том, как обновить view_msg TextView из другого класса

+0

Если вы попытались получить контекст или действие, в котором вы хотите изменить свой текст; на вашей процедуре получения сообщений msg вы можете получить свое решение. –

+0

Я использую этот MainActivity.view_msg.setText (msg); но мой проект остановлен –

+0

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

ответ

1

Похоже, что вам нужно Service bounding

некоторые удивительный пример вы можете найти HERE

просто пытаются связать ваш Activity, и когда это можно сделать, просто отправьте Message с контентом. когда Activity отсутствует, например. keep Notification popping

+0

Thankyou. Я даже не знал, что такое существует. Другим вариантом обновления является прослушивание уведомлений через NotificationListenerService и выполнение необходимых действий в его onNotificationPosted() –

+0

true, и еще один способ - создать 'singleTop'' Activity', если он может находиться в этом режиме запуска, и передать новый 'Intent' to [onNewIntent] (http://developer.android.com/reference/android/app/Activity.html#onNewIntent%28android.content.Intent%29). также «NotificationListenerService» вводится в API 18, немного для меня в данный момент, все еще поддерживается ниже;) – snachmsm

+0

Я начинаю, могу сделать для меня простое решение:/ –

Смежные вопросы