【发布时间】:2016-03-31 08:00:44
【问题描述】:
我想将 GCM 从 Receiver 接收数据共享到 Activity。如果活动处于活动/onResume/onPause 状态,我想向活动显示数据。如果活动被破坏,那么我想在通知栏中显示该信息。
接收者 -> GcmMessageHandler.class
import android.os.Bundle;
import com.google.android.gms.gcm.GcmListenerService;
public class GcmMessageHandler extends GcmListenerService {
@Override
public void onMessageReceived(String from, Bundle data) {
String message = data.getString("message");
createNotification(message);
}
private void createNotification(String body) {
String sendDataToActivity = body; // This is value i want to pass to activity
}
}
Activity -> MainActivity.class
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
String RECEIVER_VALUE;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
textView.setText(RECEIVER_VALUE); // Here i want to set the receiver valiue
}
}
这里是通知功能。
private void Notify(String notificationMessage){
Notification notification = new Notification.Builder(getBaseContext())
.setContentText(notificationMessage) // Show the Message Here
.setSmallIcon(R.drawable.ic_menu_gallery)
.setWhen(System.currentTimeMillis())
.build();
notification.notify();
}
我已经使用意图从 Activity 中的 onNewIntent 方法接收。
来自接收者 ->
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("message",message);
getApplicationContext().startActivity(intent);
并从活动 ->
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
String message = intent.getExtras().getString("message").toString();
textView.setText(message);
}
但问题是,如果我的活动已关闭,它会重新打开活动。除了这个还有其他解决方案吗?
【问题讨论】:
-
您可以将数据从 Broadcastreceiver 广播到活动。在 OnCreate 的 Activity 中注册接收器并在 onDestroy 中取消注册。此外,您可以在 SharedPreference 中添加一个变量以更新每次活动恢复、活动、暂停也 onDestroy。同样,您可以从您的广播接收器中检查是否将数据发送到活动。
-
但是,我认为当应用程序关闭时它不会运行或通知。
-
在你的函数 createNotification(String body) > 只需检查来自 SharedPreference 的活动状态的值,如果活动正在运行,则将数据传递给它,否则显示通知。
标签: android google-cloud-messaging android-broadcastreceiver