Facebook Unity SDK on Android crashes when fb.init is called - android

I'm working facebook unity SDK, everything is fine on unity editor, but doesn't work on android device. "App stopped" when fb.init called.
I use unity 5.5.1 version and facebook sdk version is 7.9.4
here is code :
public void teststr()
{
if (!FB.IsInitialized) {
// Initialize the Facebook SDK
FB.Init(InitCallback, OnHideUnity);
} else {
// Already initialized, signal an app activation App Event
}
}
private void InitCallback ()
{
if (FB.IsInitialized) {
// ...
} else {
}
}
private void OnHideUnity (bool isGameShown)
{
if (!isGameShown) {
// Pause the game - we will need to hide
Time.timeScale = 0;
} else {
// Resume the game - we're getting focus again
Time.timeScale = 1;
}
}
teststr function fires when I clicked button

I've solved!
I use FB.Init(this.InitCallback, this.OnHideUnity);
instead of FB.Init(InitCallback, OnHideUnity);

Related

Firebase realtime DB events not triggered in APK, but are in editor

I have built a Unity game which needs to listen for updates to a database object. When I run the game in the Unity editor - realtime DB changed events are triggered and the game reacts accordingly. When I publish to my Android device, however, these events dont seem to get registered.
When I check the Unity logs, the error I see is:
InitializationException: Firebase modules failed to initialize: invites (missing dependency), messaging (missing dependency), remote_config (missing dependency)
Though I clearly have those packages imported.
Any thoughts?
firebaseReference.GetValueAsync().ContinueWith(task => {
if (task.IsFaulted) {
// Handle the error...
print ("failed watchers");
}
else if (task.IsCompleted) {
DataSnapshot snapshot = task.Result;
// Do something with snapshot...
print ("set watchers");
}
});
firebaseReference.ChildChanged += HandleChildChanged;
This error is related to Google Services; you have two solutions (I'll post only the related to the messaging, that's the only one I used):
1) Check the dependencies, using the Firebase plugin, and show a message to the user (the plugin does it for you).
2) Try to register the Firebase messaging service, catch any errors and fail silently (if that's the case);
Here is the code for solution 1:
PushNotificationManager.cs
using UnityEngine;
using Firebase;
public class PushNotificationManager : MonoBehaviour {
DependencyStatus dependencyStatus = DependencyStatus.UnavailableOther;
public void Start()
{
dependencyStatus = FirebaseApp.CheckDependencies();
if (dependencyStatus != DependencyStatus.Available)
{
FirebaseApp.FixDependenciesAsync().ContinueWith(task =>
{
dependencyStatus = FirebaseApp.CheckDependencies();
if (dependencyStatus == DependencyStatus.Available)
{
InitializeFirebase();
}
else
{
Debug.LogError("Could not resolve all Firebase dependencies: " + dependencyStatus);
}
});
}
else
{
InitializeFirebase();
}
}
protected void InitializeFirebase()
{
Firebase.Messaging.FirebaseMessaging.TokenReceived += OnTokenReceived;
Firebase.Messaging.FirebaseMessaging.MessageReceived += OnMessageReceived;
}
public void OnTokenReceived(object sender, Firebase.Messaging.TokenReceivedEventArgs token)
{
Debug.Log(token.Token);
}
public void OnMessageReceived(object sender, Firebase.Messaging.MessageReceivedEventArgs e)
{
//Debug.Log("Received a new message from: " + e.Message.From + " / " + e.Message.Data.ToString());
}
}
And here is the code for solution 2: PushNotificationManager.cs
using UnityEngine;
using System;
public class PushNotificationManager : MonoBehaviour {
public void Start()
{
InitializeFirebase();
}
protected void InitializeFirebase()
{
try
{
Firebase.Messaging.FirebaseMessaging.TokenReceived += OnTokenReceived;
Firebase.Messaging.FirebaseMessaging.MessageReceived += OnMessageReceived;
}
catch(Exception e)
{
Debug.LogError("Erro no Firebase: "+e);
}
}
// (...)
}
NOTE:
As far as I know, there's no solution till now, so this is only to prevent crashes to your app.
More info here: Bugs reported [Firebase-Unity]

How to change Vuforia AR camera focus mode?

I am using Vuforia 6.2 AR SDK for in Unity. But while I test the application in Android phone the camera seems like blurry. I searched in Vuforia's developer website and found some camera focus mode but I can't implement because that guideline was for older Vuforia SDK, I can't find the script they mentioned in their website. Here is their code sample but it's not working. I created different script and run this line on Start() function, but still not working.
CameraDevice.Instance.SetFocusMode(
CameraDevice.FocusMode.FOCUS_MODE_CONTINUOUSAUTO);
try this
void Start ()
{
VuforiaARController.Instance.RegisterVuforiaStartedCallback(OnVuforiaStarted);
VuforiaARController.Instance.RegisterOnPauseCallback(OnPaused);
}
private void OnVuforiaStarted()
{
CameraDevice.Instance.SetFocusMode(
CameraDevice.FocusMode.FOCUS_MODE_CONTINUOUSAUTO);
}
private void OnPaused(bool paused)
{
if (!paused) // resumed
{
// Set again autofocus mode when app is resumed
CameraDevice.Instance.SetFocusMode(
CameraDevice.FocusMode.FOCUS_MODE_CONTINUOUSAUTO);
}
}
This code is the right code.
bool cameramode = false;
public void OnCameraChangeMode()
{
Vuforia.CameraDevice.CameraDirection currentDir = Vuforia.CameraDevice.Instance.GetCameraDirection();
if (!cameramode) {
RestartCamera(Vuforia.CameraDevice.CameraDirection.CAMERA_FRONT);
camBtnTxt.text = "Back Camera";
} else {
RestartCamera(Vuforia.CameraDevice.CameraDirection.CAMERA_BACK);
camBtnTxt.text = "Front Camera";
}
}
private void RestartCamera(Vuforia.CameraDevice.CameraDirection newDir)
{
Vuforia.CameraDevice.Instance.Stop();
Vuforia.CameraDevice.Instance.Deinit();
Vuforia.CameraDevice.Instance.Init(newDir);
Vuforia.CameraDevice.Instance.Start();
}

Interestial Ads Not Showing on Live Android Device for Game Build in Unity 4.6

I am using Unity Version ==> 4.6.0
Admob Version ==> Google Mobile Ads Unity Plugin v3.1.3
I am using below code to show interstitial ads.
public const string adsIdAndroid = "ca-app-pub-3940256099942544/1033173712";
public void RequestInterstitial()
{
try
{
if (!AdsFlag)
{
Debug.Log("Requested Interstitial");
// Initialize an InterstitialAd.
interstitial = new InterstitialAd(adsIdAndroid);
// Create an empty ad request.
AdRequest request = new AdRequest.Builder().Build();
// Load the interstitial with the request.
interstitial.LoadAd(request);
}
}
catch (Exception ex) { }
}
public void ShowInterstitial()
{
try
{
//Debug.Log("Try Show InterstitialAd");
if (!AdsFlag)
{
if (interstitial.IsLoaded())
{
Debug.Log("Show InterstitialAd");
interstitial.Show();
AdsFlag = true;
}
else
{
Debug.Log("InterstitialAd Not Loaded");
RequestInterstitial();
}
}
}
catch (Exception ex) { }
}
I am calling above function as below :
void Start()
{
AdsFlag = false;
RequestInterstitial();
}
void Update()
{
ShowInterstitial();
}
Unity Log As Below :
Requested Interstitial
UnityEngine.Debug:Log(Object)
Dummy CreateInterstitialAd
UnityEngine.Debug:Log(Object)
Dummy LoadAd
UnityEngine.Debug:Log(Object)
Dummy IsLoaded
UnityEngine.Debug:Log(Object)
Show InterstitialAd
UnityEngine.Debug:Log(Object)
Dummy ShowInterstitial
UnityEngine.Debug:Log(Object)
But on Real Android Device , ads not showing up..
How to solve this problem ?
Many of us facing similar problem with unity and admob
I just solved this problem by following below steps:
1) I have deleted google-play-services_lib folder at Assets\Plugins\Android
2) Then Select Menu Assets -> Play Service Resolver -> Android Resolver -> Resolve Client Jars.
I just followed this 2 steps and now my google ads working fine.
Maybe this answer help you to figure out problem.

Sharing to Facebook shows error "We are Sorry, this post is no longer available. It may have been removed"

I'm trying to implement Facebook sharing in my game using Unity 3D + Facebook Unity SDK. But when I tried testing to post to my wall, this error shows up: "We are Sorry, this post is no longer available. It may have been removed." Can anybody help me? Thanks in advance.
BTW, here's my code:
using UnityEngine;
using System.Collections;
public class FacebookController : MonoBehaviour {
public bool isUsingFacebook = true; //Are we using Facebook SDK? This variable is only
//Feed parameters.
private string link = "market://details?id=com.LaserCookie.Queue"; //The link that will show the user the game's google play store address
private string linkName = "Queue"; //The link name
private string linkCaption = "Wow this game is great! 10/10 must play!"; // The caption of the link
private string linkDescription = "I achieved the score of " + PlayerController.instance.score.ToString() + "! Try to beat me if you can!"; //The description of the link
private string picture = "http://www.drycreekequestriancenter.com/testImage.jpeg"; //This is the image / game icon for the link. For now, it's shamelessly got from a random source. Thank you, random citizen...
void Awake()
{
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
//Init FB
private void Init()
{
if (!FB.IsInitialized)
{
FB.Init(OnInitComplete, OnHideUnity);
}
}
//Callback that will be called when the initialization is completed
private void OnInitComplete()
{
Debug.Log("FB.Init completed: Is user logged in? " + FB.IsLoggedIn);
//Check if we are logged in.
//If not, we will log in.
//If we are, post status.
if (!FB.IsLoggedIn)
{
LoginWithPublish();
}
else
{
PostImpl();
}
}
//Callback that will be called when the game is shown / not
private void OnHideUnity(bool isGameShown)
{
Debug.Log("Is game showing? " + isGameShown);
}
//Post to Facebook. This is the only exposed method because we only use this to post to Facebook.
//The initialization and login will be called when needed.
//It will first detect whether or not we have been initialized. And will init if we haven't.
//Then it will check whether or not we have been logged in with publish. And will log in if not.
public void PostToFacebook()
{
//Are we using facebook SDK?
if (isUsingFacebook)
{
if (!FB.IsInitialized) //Check for initialization
{
Init();
}
else if (!FB.IsLoggedIn) //Check for login
{
LoginWithPublish();
}
else //Post if we are already initia;ized and logged in
{
PostImpl();
}
}
}
//The true implementation of the posting
private void PostImpl()
{
FB.Feed("",link, linkName,linkCaption,linkDescription,picture);
}
//Login to Facebook with publish
private void LoginWithPublish()
{
// It is generally good behavior to split asking for read and publish
// permissions rather than ask for them all at once.
//
// In your own game, consider postponing this call until the moment
// you actually need it.
FB.Login("publish_actions", LoginCallback);
}
//Login callback
void LoginCallback(FBResult result)
{
if (result.Error != null)
{
Debug.Log( "Error Response:\n" + result.Error );
//TODO: Retry login if we have error? Or do we display a pop up?
}
else if (!FB.IsLoggedIn)
{
Debug.Log( "Login cancelled by Player" );
//TODO: Do we display a pop up?
}
else
{
Debug.Log( "Login was successful!" );
PostImpl();
}
}
}
You need to add Key Hash for FB application.
Go to My Apps, select you application, open Setting tab, add platform for android, and add you key hash.
check this link out
Setting a Release Key Hash
I've fixed the issue. It turns out it's because I used my still in development google store address as the link. I thought it would be automatically recognized regardless of my app is live or not. Thank you anyway. :)

HelloFacebookSample onBackpressed gives status success message even not post status

I have integrated sdk in my application but when i am going to sharedialog and press back button sdk gives "success" even not post click.
For more details SDK v 3.5 and it's code which given success while i am trying to test using real Facebook account and pressing cancel.but while using test account and when i check with this "getNativeDialogCompletionGesture" method it's working but not in real account.
My requirement is while pressing cancel it should not show success on backpressed.
public static boolean handleActivityResult(Context context, PendingCall appCall, int requestCode, Intent data,
Callback callback) {
if (requestCode != appCall.getRequestCode()) {
return false;
}
if (attachmentStore != null) {
attachmentStore.cleanupAttachmentsForCall(context, appCall.getCallId());
}
if (callback != null) {
if (NativeProtocol.isErrorResult(data)) {
Exception error = NativeProtocol.getErrorFromResult(data);
callback.onError(appCall, error, data.getExtras());
} else {
callback.onComplete(appCall, data.getExtras());
}
}
return true;
}

Categories

Resources