[英]Communication between Activity and GCMListenerService Android
I am working on an android application with push notification feature using GCM. 我正在使用GCM开发具有推送通知功能的android应用程序。 I have created a class called PushNotificationService which extends GCMListenerService. 我创建了一个名为PushNotificationService的类,该类扩展了GCMListenerService。 Inside the onMessageReceived(String from, Bundle data)
I am able to get the message in the push notification. 在onMessageReceived(String from, Bundle data)
我能够在推送通知中获取消息。
Now, I want to access a method inside my MainActivity class whenever a particular message is received in the push. 现在,无论何时在推送中收到特定消息时,我都想访问MainActivity类中的方法。
Below is my code :- 以下是我的代码:-
PushNotificationService.java PushNotificationService.java
public class PushNotificationService extends GcmListenerService {
@Override
public void onMessageReceived(String from, Bundle data) {
// TODO Auto-generated method stub
super.onMessageReceived(from, data);
String message = data.getString("message");
if(message.equalsIgnoreCase("Begin Task"))
{
//call method from MainActivity.class
}
}
}
MainActivty.java MainActivty.java
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void beginTask()
{
Log.d("GCM","Message Received from Server");
finish();
}
}
I want the beginTask() method to execute whenever the message "Begin Task" is received. 我希望每当收到消息“ Begin Task”时都执行beginTask()方法。
I know one approach is via Service->Interface->Activity architecture but I am not able to use this as I never create an object of PushNotificationService. 我知道一种方法是通过Service-> Interface-> Activity体系结构,但是我无法使用它,因为我从未创建过PushNotificationService的对象。
Please help. 请帮忙。
UPDATE :- I am now using Otto Library and below is my code. 更新:-我现在正在使用Otto库,下面是我的代码。
Added new MyBus.java 添加了新的MyBus.java
public class MyBus extends Bus {
private static Bus bus;
//isRegistered is used to track the current registration status
private static boolean isRegistered;
private Handler handler = new Handler(Looper.getMainLooper());
public MyBus() {
if (bus == null) {
//ANY will allow event bus to run even with services
//and broadcast receivers
bus = new Bus(ThreadEnforcer.ANY);
}
}
@Override
public void register(Object obj) {
//The bus is registered when an activity starts
bus.register(obj);
isRegistered = true;
}
@Override
public void unregister(Object obj) {
//The bus is unregistered when an activity goes to background
bus.unregister(obj);
isRegistered = false;
}
@Override
public void post(final Object event) {
if (Looper.myLooper() == Looper.getMainLooper()) {
//post the event in main thread or background thread
bus.post(event);
} else {
handler.post(new Runnable() {
@Override
public void run() {
bus.post(event);
}
});
}
}
public boolean isRegistered(){
return isRegistered;
}
}
PushNotificationService.java PushNotificationService.java
public class PushNotificationService extends GcmListenerService {
@Override
public void onMessageReceived(String from, Bundle data) {
// TODO Auto-generated method stub
super.onMessageReceived(from, data);
MyBus myBus = new MyBus();
myBus.register(myBus);
String message = data.getString("message");
if(message.equalsIgnoreCase("Begin Task"))
{
myBus.post(message);
}
}
}
MainActivity.java MainActivity.java
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Subscribe
public void beginTask()
{
Log.d("GCM","Message Received from Server");
}
}
The problem is still not solved . 问题仍然没有解决 。 The beginTask() inside MainActivity.java is still not getting called. MainActivity.java中的beginTask()仍未调用。
Use eventBus libraries to facilitate this process... 使用eventBus库促进此过程...
I use Otto for this process http://square.github.io/otto/ 我将Otto用于此过程http://square.github.io/otto/
Here is an another eventBus library https://greenrobot.github.io/EventBus/ 这是另一个eventBus库https://greenrobot.github.io/EventBus/
Steps: 脚步:
1.Create an event from the service 1.从服务创建事件
2.Add a listener in the activity 2.在活动中添加一个侦听器
3.If the activity is running the method will be executed 3.如果活动正在运行,该方法将被执行
**EDIT 1 : ** **编辑1:**
I have abstracted the otto bus like this. 我已经像这样抽象了otto总线。
package com.mypackage.eventBus;
import android.os.Handler;
import android.os.Looper;
import com.squareup.otto.Bus;
import com.squareup.otto.ThreadEnforcer;
/**
* Created by gowtham on 10/6/15.
*/
public class MyBus extends Bus {
private static Bus bus;
//isRegistered is used to track the current registration status
private static boolean isRegistered;
private Handler handler = new Handler(Looper.getMainLooper());
public MyBus() {
if (bus == null) {
//ANY will allow event bus to run even with services
//and broadcast receivers
bus = new Bus(ThreadEnforcer.ANY);
}
}
@Override
public void register(Object obj) {
//The bus is registered when an activity starts
bus.register(obj);
isRegistered = true;
}
@Override
public void unregister(Object obj) {
//The bus is unregistered when an activity goes to background
bus.unregister(obj);
isRegistered = false;
}
@Override
public void post(final Object event) {
if (Looper.myLooper() == Looper.getMainLooper()) {
//post the event in main thread or background thread
bus.post(event);
} else {
handler.post(new Runnable() {
@Override
public void run() {
bus.post(event);
}
});
}
}
public boolean isRegistered(){
return isRegistered;
}
}
create an instance of the above object and try posting event 创建上述对象的实例,然后尝试发布事件
EDIT 2 for Jcarlo's comment 编辑2对Jcarlo的评论
Follow these steps to find the state of the activity. 请按照以下步骤查找活动的状态。
In your GCM IntentService before posting the message 在发布消息之前,在您的GCM IntentService中
if(MyBus.getInstance().isRegistered()){ //app is alive //post data }else{ //show notification } if(MyBus.getInstance()。isRegistered()){//应用程序处于活动状态//发布数据} else {//显示通知}
Hope this helps 希望这可以帮助
You can use LocalBroadcastManager
. 您可以使用LocalBroadcastManager
。 Create a LocalBroadcastManager
object mBroadcaster = LocalBroadcastManager.getInstance(this);
创建一个LocalBroadcastManager
对象mBroadcaster = LocalBroadcastManager.getInstance(this);
on onCreate
of your GCMListener and send broadcast with 在您的GCMListener的onCreate
上发送
@Override
public void onCreate() {
super.onCreate();
mBroadcaster = LocalBroadcastManager.getInstance(this);
}
@Override
public void onMessageReceived(String from, Bundle data) {
super.onMessageReceived(from, data);
String message = data.getString("message");
if(message.equalsIgnoreCase("Begin Task")) {
Intent i = new Intent();
i.setAction("yourPackageName");
i.putExtra("DATA", yourData);
mBroadcaster.send(i);
}
}
Then you can receive message in MainActivity
using a BroadcastReceiver
. 然后,您可以使用BroadcastReceiver
在MainActivity
接收消息。
BroadCastReceiver mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
beginTask();
}
};
Also you need to register and unregister the receiver in onStart
and onStop
of your activity 另外,您还需要在活动的onStart
和onStop
中注册和注销接收者
@Override
protected void onStart() {
super.onStart();
IntentFilter filter = new IntentFilter();
filter.addAction("yourPackageName);
LocalBroadcastManager.getInstance(this).registerReceiver((mBroadcastReceiver), filter);
}
@Override
protected void onStop() {
super.onStop();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcastReceiver);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.