[英]Separated activity, intentservice and broadcastreveiver
Assuming we've got an activity, an intentservice and a broadcastreceiver in our project all separated in different java files. 假设我们的项目中有一个活动,一个intentservice和一个broadcastreceiver,它们都分别放在不同的java文件中。 Can anybody extendedly explain a scenario that the intentservice gets GCM push messages, the broadcastreceiver informs the activity about the incoming message and the activity instantly shows the message through a text box? 谁能扩展解释一下intentservice获取GCM推送消息,broadcastreceiver通知活动有关传入消息,活动立即通过文本框显示消息的情况吗? Thank you in advance. 先感谢您。
This is how to do it. 这是怎么做的。
Step 1 Create a base activity and all other activities should extend it. 步骤1创建一个基本活动,所有其他活动都应对其进行扩展。
Step 2 In your custom application (say MyApplication.class
) class add these four methods and two variables 步骤2在您的自定义应用程序(例如MyApplication.class
)类中,添加这四个方法和两个变量
private static boolean activityVisible = false;
private static Context activityOnTop = null;
public static boolean isActivityVisible() {
return activityVisible;
}
public static Context getActivityOnTop(){
return activityOnTop;
}
public static void activityResumed(Context classContext) {
activityVisible = true;
activityOnTop = classContext;
}
public static void activityPaused() {
activityVisible = false;
}
Step 3 In the base activity (which all other are extending) do this 步骤3在基本活动(所有其他活动都在扩展中)中执行此操作
@Override
protected void onResume() {
super.onResume();
MyApplication.activityResumed(this);
}
@Override
protected void onPaused() {
super.onPaused();
MyApplication.activityPaused(this);
}
Step 4 In your broadcast receiver when you get the notification event do this 步骤4当您收到通知事件时,在广播接收器中执行此操作
if(!MyApplication.isActivityVisible()){
//Show notification when app is not visible to user
return;
}
Context currContext = MyApplication.getActivityOnTop();
if(currContext == null)
return;
String currentActivity = currContext.getClass().getName();
if(!Strings.isNullOrEmpty(currentActivity)) {
try {
Intent i = new Intent(context, Class.forName(currentActivity));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
// Add the push notification message in the bundle here
context.startActivity(i);
}
catch (ClassNotFoundException e){
}
}
Step 5 In your base activity do this 步骤5在您的基本活动中执行此操作
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
//get push notification message in the bundle here and show the dialog
// DO NOT USE getIntent() here. USE THE intent THAT IS PASSED AS PARAMETER
}
NOTE: 注意:
Strings.isNullOrEmpty()
is just a method I have created as a utility function Strings.isNullOrEmpty()
只是我作为实用程序函数创建的一种方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.