从服务中调用正在运行的活动中的方法 [英] Call method in a running activity from a service

查看:141
本文介绍了从服务中调用正在运行的活动中的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在开发一个Android项目。到目前为止,我已经实现了Firebase,特别是FirebaseInstanceIdService和FirebaseMessagingService:

 

code> public class FirebaseIDService extends FirebaseInstanceIdService {
private static final String TAG =FirebaseIDService;

私有上下文上下文;

@Override
public void onTokenRefresh(){
context = getApplicationContext();
//获取更新的InstanceID令牌。
String refreshedToken = FirebaseInstanceId.getInstance()。getToken();
Log.e(TAG,Refreshed token:+ refreshedToken);

SharedPreferences sharedPreferences = context.getSharedPreferences(token,context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(token,refreshedToken);
editor.commit();

sendRegistrationToServer(refreshedToken);
}

/ **
*将令牌保存到后端。
* @param token新的令牌。
* /
private void sendRegistrationToServer(String token){
SendRegistrationKey task = new SendRegistrationKey(context);
task.execute(token);

code


$ b $ pre> public class MessagingService extends FirebaseMessagingService {

private static final String TAG =MsgService;

/ **
*收到消息时调用。
*
* @param remoteMessage表示从Firebase云消息收到的消息的对象。
* /
@Override
public void onMessageReceived(RemoteMessage remoteMessage){
Log.e(TAG,From:+ remoteMessage.getFrom());

//检查消息是否包含数据有效载荷。 (remoteMessage.getData()。size()> 0){
Log.e(TAG,Message data payload:+ remoteMessage.getData());
}

//检查消息是否包含通知负载。
if(remoteMessage.getNotification()!= null){
Log.e(TAG,Message Notification Body:+ remoteMessage.getNotification()。getBody());

sendNotification(remoteMessage);
}

//同样,如果您打算通过收到的FCM
//消息生成您自己的通知,那么这里是应该启动的地方。请参阅下面的sendNotification方法。
}
// [END receive_message]

private void sendNotification(RemoteMessage remoteMessage){
RemoteMessage.Notification notification = remoteMessage.getNotification();
PushNotificationManager PNManager = PushNotificationManager.getInstance(getApplicationContext());
PNManager.buildNotification(notification.getTitle(),notification.getBody());
}

我想要达到以下效果:



当App在后台时,我只想在通知中心进行一个简单的通知。 (这已经在工作)

但是,当应用程序在前台并且正在运行时,我想要有一个不同的行为:
我想要使用推送通知,并显示一个提醒。



但我的问题是:我如何能够与服务中的运行活动交互,或者什么是实现预期行为的正确方法?
Ther一定是一个简单的灵魂,对吧?


在此先感谢

解决方案

/ p>

  public Context currentactvity = null; 
public Context getCurrentactvity(){
return currentactvity;
}

public void setCurrentactvity(Context currentactvity){
this.currentactvity = currentactvity;
}

在onresume方法和onpause方法中, p>

  // inresume 
MyApplication.getInstance()。setCurrentactvity(this);

// onpause
MyApplication.getInstance()。setCurrentactvity(null);

现在您可以从服务类中调用活动方法了

if(MyApplication.getInstance()。getCurrentactvity()!= null&& MyApplication.getInstance()。getCurrentactvity()instanceof youractivityname){
((youractivityname )MyApplication.getInstance()。getCurrentactvity())。youmethodname(parameter);

}


I am currently working on a Android project.

So far, I have implemented Firebase, in particular the FirebaseInstanceIdService and the FirebaseMessagingService:

public class FirebaseIDService extends FirebaseInstanceIdService {
private static final String TAG = "FirebaseIDService";

private Context context;

@Override
public void onTokenRefresh() {
    context = getApplicationContext();
    // Get updated InstanceID token.
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.e(TAG, "Refreshed token: " + refreshedToken);

    SharedPreferences sharedPreferences = context.getSharedPreferences("token", context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString("token", refreshedToken);
    editor.commit();

    sendRegistrationToServer(refreshedToken);
}

/**
 * Persist token to backend.
 * @param token The new token.
 */
private void sendRegistrationToServer(String token) {
    SendRegistrationKey task = new SendRegistrationKey(context);
    task.execute(token);
}

}

public class MessagingService extends FirebaseMessagingService {

private static final String TAG = "MsgService";

/**
 * Called when message is received.
 *
 * @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
 */
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    Log.e(TAG, "From: " + remoteMessage.getFrom());

    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        Log.e(TAG, "Message data payload: " + remoteMessage.getData());
    }

    // Check if message contains a notification payload.
    if (remoteMessage.getNotification() != null) {
        Log.e(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());

        sendNotification(remoteMessage);
    }

    // Also if you intend on generating your own notifications as a result of a received FCM
    // message, here is where that should be initiated. See sendNotification method below.
}
// [END receive_message]

private void sendNotification(RemoteMessage remoteMessage) {
    RemoteMessage.Notification notification = remoteMessage.getNotification();
    PushNotificationManager PNManager = PushNotificationManager.getInstance(getApplicationContext());
    PNManager.buildNotification(notification.getTitle(), notification.getBody());
}

What I want to achieve is the following:

When the App is in background, I just want to have a simple notification in the notification center. (This is already working)

BUT, when the app is in foreground and currently running, I want to have a different behaviour: I want to consume the push notification and show an alert instead.

But my question is: how can I interact with the running activity from the service or what is the correct way to achieve the intended behaviour? Ther must be a simple soultion, right?

Thanks in advance

解决方案

write this code in application class

 public Context currentactvity = null;
public Context getCurrentactvity() {
    return currentactvity;
}

public void setCurrentactvity(Context currentactvity) {
    this.currentactvity = currentactvity;
}

write this code in each activity onresume method and in onpause method set null

 // in onresume
MyApplication.getInstance().setCurrentactvity(this);

// in onpause
MyApplication.getInstance().setCurrentactvity(null);

now you can call activity method from service class

  if (MyApplication.getInstance().getCurrentactvity() != null && MyApplication.getInstance().getCurrentactvity() instanceof youractivityname) {
            ((youractivityname) MyApplication.getInstance().getCurrentactvity()).youmethodname(parameter);

        }

这篇关于从服务中调用正在运行的活动中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆