2016-11-12 109 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

歡迎和審查我的答案,當你得到完成:) –

相關問題