gpt4 book ai didi

android - 从 GCMIntentService 发送数据并在主要 Activity 中接收它

转载 作者:行者123 更新时间:2023-11-29 21:07:07 24 4
gpt4 key购买 nike

您好,我想从 GCMIntentService 发送数据到我的主要 Activity ,我想在那里接收它?我该如何实现?

我非常坚持这一点在我的主要 Activity 中,我有一个列表,我想根据收到的消息更新它。

public class GcmIntentService extends IntentService {


public GcmIntentService() {
super("GcmIntentService");
}
public static final String TAG = "GCM Service";

@Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
// The getMessageType() intent parameter must be the intent you received
// in your BroadcastReceiver.
String messageType = gcm.getMessageType(intent);

if (!extras.isEmpty()) { // has effect of unparcelling Bundle
/*
* Filter messages based on message type. Since it is likely that GCM will be
* extended in the future with new message types, just ignore any message types you're
* not interested in, or that you don't recognize.
*/
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
sendData("Send error: " + extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
sendData("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(5000);
} catch (InterruptedException e) {
}
}
Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
// Post notification of received message.
sendData("Received: " + extras.toString());
Log.i(TAG, "Received: " + extras.toString());
}
}
// Release the wake lock provided by the WakefulBroadcastReceiver.
GcmBroadcastReceiver.completeWakefulIntent(intent);
}


private void sendData(String msg) {

//I want to send the data to main activity and Iam stuck here
//should I use sendBroadcast and broadcast receiver or something else ?
}
}

最佳答案

要做到这一点,您需要首先覆盖您的 Activity onNewIntent 上的方法并更改 Activity 的启动模式。

list .xml

android:launchMode="singleTop"

为您服务

Intent intent = new Intent(context, YourActivityClass.class);

// This make the magic
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

//add some data extra
intent.putExtra("data","from outside");

getApplicationContext().startActivity(intent);

关于你的 Activity

@Override
protected void onNewIntent(Intent intent) {

}

关于android - 从 GCMIntentService 发送数据并在主要 Activity 中接收它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24207216/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com