Android 在FirebaseInstanceIdService上创建自定义侦听器以在活动中实现
是否有可能在Android 在FirebaseInstanceIdService上创建自定义侦听器以在活动中实现,android,firebase,firebase-cloud-messaging,Android,Firebase,Firebase Cloud Messaging,是否有可能在FirebaseInstancedService类中创建接口和侦听器,并在活动中实现它 因为我试着这么做,结果我出错了 这是我的密码: public class _FirebaseInstanceIDService extends FirebaseInstanceIdService { private static final String TAG = "MyFirebaseIIDService"; private static Context mContext =
FirebaseInstancedService
类中创建接口和侦听器,并在活动中实现它
因为我试着这么做,结果我出错了
这是我的密码:
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)
我想知道这是否可行。确实需要建议。FirebaseInstancedService.onTokenRefresh是由一个服务实现的。它不能在活动中实现
无法在活动中监视令牌刷新,因为应用程序未处于活动状态时也可能发生令牌刷新。由于应用程序被终止时不会运行活动,因此您必须在服务中实现
FirebaseInstancedService.onTokenRefresh
,以处理令牌刷新。FirebaseInstancedService.onTokenRefresh由服务实现。它不能在活动中实现
无法在活动中监视令牌刷新,因为应用程序未处于活动状态时也可能发生令牌刷新。由于应用程序被终止时活动不会运行,您必须在服务中实现
FirebaseInstancedService.onTokenRefresh
,以处理令牌刷新。您面临这个问题,因为您的服务不是使用onListener实现的,因为您正在使用“this”初始化它。这意味着您将实现引用到同一个类,但我得到了您想要的:
您需要服务和其他类之间的动态绑定
实现listner,但我将建议一种冗长的方法来实现它
因为
FireBaseInstancedService
是一项服务,不建议使用服务接口。如果您的应用未运行,您可以通过发送广播从服务获取更新,如果您的应用正在运行,则使用IPC进行更新,并从messenger发送令牌
在您的活动或片段中,请使用下面的代码
步骤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:在调用get令牌之前调用绑定
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:最后在FireBaseInstancedService类中
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);
}
}
公共类MyFireBaseInstanceId服务扩展FireBaseInstanceId服务{
私有静态最终字符串TAG=“MyFirebaseIIDService”;
/**
*跟踪所有当前注册的客户端。
*/
ArrayList mClients=新的ArrayList();
/**
*保存客户端设置的最后一个值。
*/
/**
*命令服务注册客户端,接收回调
*来自服务。邮件的replyTo字段必须是的Messenger
*应在其中发送回调的客户端。
*/
公共静态final int MSG_REGISTER_CLIENT=1;
/**
*命令服务取消注册客户端,或停止接收回调
*来自服务。邮件的replyTo字段必须是的Messenger
*客户机,如前所述,与MSG_REGISTER_client一起提供。
*/
公共静态final int MSG_UNREGISTER_CLIENT=2;
/**
*命令以设置新值。此命令可发送到
*服务提供新值,并将由服务发送到
*具有新值的任何已注册客户端。
*/
公共静态最终整型令牌\u刷新=3;
类IncomingHandler扩展了Handler{
@凌驾
公共无效handleMessage(消息消息消息){
开关(msg.what){
case MSG\u REGISTER\u客户端:
mClients.add(msg.replyTo);
打破
案例消息\u取消注册\u客户端:
mClients.remove(msg.replyTo);
打破
案例标记\u已刷新:
对于(int i=mClients.size()-1;i>=0;i--){
试一试{
mClients.get(i).send(Message.get)(null,
令牌_刷新,msg.arg1,0);
}捕获(远程异常){
//客户端已死亡。请将其从列表中删除;
//我们正在从头到尾浏览这份名单
//因此,在循环内这样做是安全的。
M客户。删除(i);
}
}
打破
违约:
超级handleMessage(msg);
}
}
}
/**
*如果InstanceID令牌更新,则调用。如果
*以前的令牌已被破坏。请注意,当InstanceID令牌
*是最初生成的,因此您将在此处检索令牌。
*/
//[启动刷新\u令牌]
@凌驾
公共刷新(){
//获取更新的InstanceID令牌。
字符串refreshedToken=FirebaseInstanceId.getInstance().getToken();
Message msg=Message.get(空,
令牌(U);
msg.obj=已刷新;
//TODO:实现此方法以将任何注册发送到应用程序的服务器。
sendRegistrationToServer(refreshedToken);
}
//[结束刷新\u令牌]
/**
*将令牌持久化到第三方服务器。
*
*修改此方法以将用户的FCM InstanceID令牌与任何服务器端帐户关联
*由您的应用程序维护。
*
*@param-token新令牌。
*/
私有void sendRegistrationToServer(字符串令牌){
//根据需要添加自定义实现。
Log.e(“,”FCM令牌:“+令牌);
}
}
您正面临这个问题,因为您的服务不是使用onListener实现的,因为您使用“this”初始化它,这意味着您将实现引用到同一个类,但我得到了您想要的:
您需要服务和其他类之间的动态绑定
实现listner,但我将建议一种冗长的方法来实现它
因为