海外统计与推送-----Firebase

最近一直在做海外项目。涉及到推送功能。于是使用到了firebase.

firebase是Google推出的一个云端服务,并且它完全免费。

官方:https://firebase.google.com/features/ 。当然,由于是涉及海外的,所以,你懂的,要搬梯子。

firebase的功能有很多种,包含,推送通知,云存储,活动监视,远程部署等等。请注意:

手机中的Google Play Service的版本信息需要>=FireBase SDK的版本,否则FireBase将无效。

在firebase上可以看到用户weizhi位置:如下图(公司app)

同时你也可以使用FireBase进行LogEvent追踪,可以看到用户的偏好操作行为

具体代码:

public class Firebase {

    private static Firebase instance;
    private Context context;
    private FirebaseAnalytics mFireInstance;

    public Firebase(Context context) {
        this.context = context;
    }

    public static Firebase getInstance(Context context) {
        if (instance == null) {
            instance = new Firebase(context);
        }
        return instance;
    }

    private FirebaseAnalytics getFirebaseAnalytics() {
        if (mFireInstance == null) {
            try {
                mFireInstance = FirebaseAnalytics.getInstance(context);
            } catch (Exception e) {

            }
        }
        return mFireInstance;
    }

    public void logEvent(String category, String action) {
        FirebaseAnalytics firebaseAnalytics = instance.getFirebaseAnalytics();
        Bundle bundle = new Bundle();
        bundle.putString("action", cutStringIfNecessary(action));
        firebaseAnalytics.logEvent(validateKey(category), bundle);
    }

    public void logEvent(String category, String action, String label) {
        FirebaseAnalytics firebaseAnalytics = instance.getFirebaseAnalytics();
        Bundle bundle = new Bundle();
        bundle.putString(validateKey(action), cutStringIfNecessary(label));
        firebaseAnalytics.logEvent(validateKey(category), bundle);
    }

    public void logEvent(String category, String action, long value) {
        FirebaseAnalytics firebaseAnalytics = instance.getFirebaseAnalytics();
        Bundle bundle = new Bundle();
        bundle.putLong(validateKey(action), value);
        firebaseAnalytics.logEvent(validateKey(category), bundle);
    }

    public void logEvent(String category, String action, double value) {
        FirebaseAnalytics firebaseAnalytics = instance.getFirebaseAnalytics();
        Bundle bundle = new Bundle();
        bundle.putDouble(validateKey(action), value);
        firebaseAnalytics.logEvent(validateKey(category), bundle);
    }

    public void logEvent(String category, long value) {
        FirebaseAnalytics firebaseAnalytics = instance.getFirebaseAnalytics();
        Bundle bundle = new Bundle();
        bundle.putLong("value", value);
        firebaseAnalytics.logEvent(validateKey(category), bundle);
    }

    public void logEvent(String category, double value) {
        FirebaseAnalytics firebaseAnalytics = instance.getFirebaseAnalytics();
        Bundle bundle = new Bundle();
        bundle.putDouble("value", value);
        firebaseAnalytics.logEvent(validateKey(category), bundle);
    }

    public void logEvent(String category, Bundle values) {
        FirebaseAnalytics firebaseAnalytics = instance.getFirebaseAnalytics();
        firebaseAnalytics.logEvent(validateKey(category), values);
    }

    private String cutStringIfNecessary(String v) {
        if (!TextUtils.isEmpty(v) && v.length() > 100) {
            return v.substring(0, 100);
        }
        return v;
    }

    private String validateKey(String key) {
        if (!TextUtils.isEmpty(key)) {
            if (!Character.isLetter(key.charAt(0))) {
                key = "K" + key;
            }
            if (key.length() > 40) {
                key = key.substring(0, 40);
            }
            for (int i = 0; i < key.length(); i++) {
                if (!Character.isLetterOrDigit(key.charAt(i)) && key.charAt(i) != '_') {
                    key = key.replace(key.charAt(i), '_');
                }
            }
        }
        return key;
    }

    //设置是否开启数据收集功能
    public void setAnalyticsCollectionEnabled(boolean enabled) {
        instance.getFirebaseAnalytics().setAnalyticsCollectionEnabled(enabled);
    }

    public void setMinimumSessionDuration(long milliseconds) {
        instance.getFirebaseAnalytics().setMinimumSessionDuration(milliseconds);
    }

    public void setUserId(String userId) {
        instance.getFirebaseAnalytics().setUserId(userId);
    }

    public void setSessionTimeoutDuration(long milliseconds) {
        instance.getFirebaseAnalytics().setSessionTimeoutDuration(milliseconds);
    }

    public void setUserProperty(String name, String value) {
        instance.getFirebaseAnalytics().setUserProperty(name, value);
    }



    /*获取Appinsranceid 参数*/
    public void getAppInstanceId(final getAppInstanceIdListener appInstanceIdListener) {
        instance.getFirebaseAnalytics().getAppInstanceId().addOnCompleteListener(new OnCompleteListener<String>() {
            @Override
            public void onComplete(@NonNull Task<String> task) {
                if (appInstanceIdListener != null) {
                    try {
                        appInstanceIdListener.setAppInstanceId(task.getResult());
                    } catch (RuntimeExecutionException e) {
                        appInstanceIdListener.setAppInstanceId("");
                    }

                }

            }
        });
    }

    public interface getAppInstanceIdListener {
        void setAppInstanceId(String appInstanceId);
    }

 在需要的时候,直接调用:Firebase.getInstance(getApplicationContext()).logEvent("xxx", "xxx");

使用Firebase进行推送。

首先需要再Firebase后台添加一个应用,然后下载Google-service.json文件,添加到应用中。如图

最后一步,运行项目,就可以看到firebase的统计了。

FireBase云推送是完全免费的,它的配置信息如下图所示:

其中打?是可选项。 值得注意的是下图:

自定义的数据是key-value   。 这两个值配置好后,会在应用用获取,具体实现:

       1.需要使用两个service分别继承  :FirebaseMessagingService和FirebaseInstanceIdService

    FirebaseMessagingService

dataMap就是我们在Firebase云推送上配置的key-value的值。得到值后就可以进行相应的处理了

FirebaseInstanceIdService:

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

    private static final String TAG = "MyFirebaseIIDService";

    @Override
    public void onCreate() {
        super.onCreate();
        FirebaseMessaging.getInstance().subscribeToTopic("xxx");
    }

    /**
     * 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();
        Log.d(TAG, "Refreshed token: " + refreshedToken);

        // If you want to send messages to this application instance or
        // manage this apps subscriptions on the server side, send the
        // Instance ID token to your app server.

        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) {
        // TODO: Implement this method to send token to your app server.
        Log.e("id", token);
        Log.e("id===========", token);
    }
}

FirebaseMessaging.getInstance().subscribeToTopic("xxx")  xxx这个值可以自定义,通过这个值可以在后台配置curl命令,然后在自己后台实现实时推送。

好了,关于推送就说到这了。下篇会讲到remoteConfig.谢谢!!

猜你喜欢

转载自blog.csdn.net/github_37271067/article/details/81114323