2016-11-12 67 views
1

是否有可能在FirebaseInstanceIdService类中创建接口和侦听器并在活动中实现它?在FirebaseInstanceIdService上创建自定义侦听器以实现活动

因为我试图这样做,我得到了错误。

这里是我的代码:

public class _FirebaseInstanceIDService extends FirebaseInstanceIdService { 

    private static final String TAG = "MyFirebaseIIDService"; 
    private static Context mContext = null; 

    private onListener mListener = null; 




    /** 
    * Called if InstanceID token is updated. This may occur if the security of 
    * the previous token had been compromised. Note that this is called when the InstanceID token 
    * is initially generated so this is where you would retrieve the token. 
    */ 
    // [START refresh_token] 
    @Override 
    public void onTokenRefresh() { 
     mListener=(onListener)this; //i got error in here 
     // Get updated InstanceID token. 
     String refreshedToken = FirebaseInstanceId.getInstance().getToken(); 
     Log.e(TAG, "Refreshed token: " + refreshedToken); 

     if (!refreshedToken.isEmpty()){ 
      boolean b = PreferencesManager.init(this).saveToken(refreshedToken); 

      if (b) 
       if(mListener != null) 
        mListener.onTokenListener(refreshedToken); 
     } 

    } 
    // [END refresh_token] 




    public interface onListener{ 

     void onTokenListener(String token); 
    } 

} 

错误:

java.lang.ClassCastException: rezkyaulia.android.dont_do.services._FirebaseInstanceIDService cannot be cast to rezkyaulia.android.dont_do.services._FirebaseInstanceIDService$onListener 
    at rezkyaulia.android.dont_do.services._FirebaseInstanceIDService.onTokenRefresh(_FirebaseInstanceIDService.java:55) 

我想知道是否可以做还是不做。真的需要建议。

回答

-1

FirebaseInstanceIdService .onTokenRefresh由服务实现。它不能在一项活动中实施。

无法监控令牌刷新活动,因为当您的应用未处于活动状态时也可能发生令牌刷新。由于应用程序被终止时活动不会运行,因此您必须在服务中实施FirebaseInstanceIdService .onTokenRefresh以处理令牌刷新。

1

您所面临的问题,因为你的服务没有与onListener实现为您使用的“本”就意味着你是闯民宅落实到同一类初始化,但我得到了你在找什么:

你要动态服务和其他一些类 实现读心人之间具有约束力,但我要提出一个漫长的办法做到这一点 因为

FirebaseInstanceIdService

是服务和使用由服务接口不建议,您可以通过发送广播,如果您的应用程序没有运行需要从服务更新,如果你的应用程序正在运行,然后使用IPC做到这一点,并从信使送令牌

在你的活动或片段使用下面 第1步的代码:建立呼入处理程序

class IncomingHandler extends Handler { 
      @Override 
      public void handleMessage(Message msg) { 
       switch (msg.what) { 
        case MessengerService.MSG_SET_VALUE: 
         mCallbackText.setText("Received from service: " + msg.obj); 
         break; 
        default: 
         super.handleMessage(msg); 
       } 
      } 
     } 

     /** 
     * Target we publish for clients to send messages to IncomingHandler. 
     */ 
     final Messenger mMessenger = new Messenger(new IncomingHandler()); 

2:创建服务连接:

/** 
    * Class for interacting with the main interface of the service. 
    */ 
    private ServiceConnection mConnection = new ServiceConnection() { 
     public void onServiceConnected(ComponentName className, 
             IBinder service) { 
      // This is called when the connection with the service has been 
      // established, giving us the service object we can use to 
      // interact with the service. We are communicating with our 
      // service through an IDL interface, so get a client-side 
      // representation of that from the raw service object. 
      mService = new Messenger(service); 
      mCallbackText.setText("Attached."); 

      // We want to monitor the service for as long as we are 
      // connected to it. 
      try { 
       Message msg = Message.obtain(null, 
         MessengerService.MSG_REGISTER_CLIENT); 
       msg.replyTo = mMessenger; 
       mService.send(msg); 

       // Give it some value as an example. 
       msg = Message.obtain(null, 
         MessengerService.MSG_SET_VALUE, this.hashCode(), 0); 
       mService.send(msg); 
      } catch (RemoteException e) { 
       // In this case the service has crashed before we could even 
       // do anything with it; we can count on soon being 
       // disconnected (and then reconnected if it can be restarted) 
       // so there is no need to do anything here. 
      } 

     } 

     public void onServiceDisconnected(ComponentName className) { 
      // This is called when the connection with the service has been 
      // unexpectedly disconnected -- that is, its process crashed. 
      mService = null; 
     } 
    }; 

3:调用绑定befor Ë呼吁得到令牌

void doBindService() { 
      // Establish a connection with the service. We use an explicit 
      // class name because there is no reason to be able to let other 
      // applications replace our component. 
      bindService(new Intent(MessengerServiceActivities.this, 
        MessengerService.class), mConnection, Context.BIND_AUTO_CREATE); 
      mIsBound = true; 
     } 
FirebaseInstanceId.getInstance().getToken(); 

4:最后在你的FirebaseInstanceIdService类

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService { 

    private static final String TAG = "MyFirebaseIIDService"; 

    /** 
    * Keeps track of all current registered clients. 
    */ 
    ArrayList<Messenger> mClients = new ArrayList<Messenger>(); 
    /** 
    * Holds last value set by a client. 
    */ 

    /** 
    * Command to the service to register a client, receiving callbacks 
    * from the service. The Message's replyTo field must be a Messenger of 
    * the client where callbacks should be sent. 
    */ 
    public static final int MSG_REGISTER_CLIENT = 1; 

    /** 
    * Command to the service to unregister a client, ot stop receiving callbacks 
    * from the service. The Message's replyTo field must be a Messenger of 
    * the client as previously given with MSG_REGISTER_CLIENT. 
    */ 
    public static final int MSG_UNREGISTER_CLIENT = 2; 

    /** 
    * Command to service to set a new value. This can be sent to the 
    * service to supply a new value, and will be sent by the service to 
    * any registered clients with the new value. 
    */ 
    public static final int TOKEN_REFRESHED = 3; 

    class IncomingHandler extends Handler { 
     @Override 
     public void handleMessage(Message msg) { 
      switch (msg.what) { 
       case MSG_REGISTER_CLIENT: 
        mClients.add(msg.replyTo); 
        break; 
       case MSG_UNREGISTER_CLIENT: 
        mClients.remove(msg.replyTo); 
        break; 
       case TOKEN_REFRESHED: 
        for (int i = mClients.size() - 1; i >= 0; i--) { 
         try { 
          mClients.get(i).send(Message.obtain(null, 
            TOKEN_REFRESHED, msg.arg1, 0)); 
         } catch (RemoteException e) { 
          // The client is dead. Remove it from the list; 
          // we are going through the list from back to front 
          // so this is safe to do inside the loop. 
          mClients.remove(i); 
         } 
        } 
        break; 
       default: 
        super.handleMessage(msg); 
      } 
     } 
    } 


    /** 
    * Called if InstanceID token is updated. This may occur if the security of 
    * the previous token had been compromised. Note that this is called when the InstanceID token 
    * is initially generated so this is where you would retrieve the token. 
    */ 
    // [START refresh_token] 
    @Override 
    public void onTokenRefresh() { 
     // Get updated InstanceID token. 
     String refreshedToken = FirebaseInstanceId.getInstance().getToken(); 
     Message msg = Message.obtain(null, 
       TOKEN_REFRESHED); 
     msg.obj = refreshedToken; 
     // TODO: Implement this method to send any registration to your app's servers. 
     sendRegistrationToServer(refreshedToken); 
    } 
    // [END refresh_token] 

    /** 
    * Persist token to third-party servers. 
    * <p/> 
    * Modify this method to associate the user's FCM InstanceID token with any server-side account 
    * maintained by your application. 
    * 
    * @param token The new token. 
    */ 
    private void sendRegistrationToServer(String token) { 
     // Add custom implementation, as needed. 
     Log.e("", "FCM Token: " + token); 
    } 
} 
+0

谢谢你......我会尝试:) – itsa04g9

+0

欢迎和审查我的答案,当你得到完成:) –

相关问题