How to check if unity video ads ready to show or loaded - unity3d

I'm using Unity Ads in my game. In older version i check if unity video ads are ready to show then call a method to show ads like this
public bool IsVideoReady()
{
if (Advertisement.IsReady())
return true;
else
return false;
}
But in new version i dont know how to check if unity video ads are ready or loaded to show.
My new script is
using UnityEngine;
using UnityEngine.Advertisements;
public class AdsInitializer : MonoBehaviour, IUnityAdsInitializationListener, IUnityAdsLoadListener, IUnityAdsShowListener
{
[SerializeField] string _androidGameId;
[SerializeField] string _iOSGameId;
string _gameId;
[SerializeField] bool _testMode = true;
private void Awake()
{
if (Advertisement.isInitialized)
{
Debug.Log("Advertisement is Initialized");
LoadRewardedAd();
}
else
{
InitializeAds();
}
}
public void InitializeAds()
{
_gameId = (Application.platform == RuntimePlatform.IPhonePlayer) ? _iOSGameId : _androidGameId;
Advertisement.Initialize(_gameId, _testMode, this);
}
public void OnInitializationComplete()
{
Debug.Log("Unity Ads initialization complete.");
LoadInerstitialAd();
LoadBannerAd();
}
public void OnInitializationFailed(UnityAdsInitializationError error, string message)
{
Debug.Log($"Unity Ads Initialization Failed: {error.ToString()} - {message}");
}
public void LoadInerstitialAd()
{
Advertisement.Load("Interstitial_Android", this);
}
public void LoadRewardedAd()
{
Advertisement.Load("Rewarded_Android", this);
}
public void OnUnityAdsAdLoaded(string placementId)
{
Debug.Log("OnUnityAdsAdLoaded");
Advertisement.Show(placementId,this);
}
public void OnUnityAdsFailedToLoad(string placementId, UnityAdsLoadError error, string message)
{
Debug.Log($"Error showing Ad Unit {placementId}: {error.ToString()} - {message}");
}
public void OnUnityAdsShowFailure(string placementId, UnityAdsShowError error, string message)
{
Debug.Log("OnUnityAdsShowFailure");
}
public void OnUnityAdsShowStart(string placementId)
{
Debug.Log("OnUnityAdsShowStart");
Time.timeScale = 0;
Advertisement.Banner.Hide();
}
public void OnUnityAdsShowClick(string placementId)
{
Debug.Log("OnUnityAdsShowClick");
}
public void OnUnityAdsShowComplete(string placementId, UnityAdsShowCompletionState showCompletionState)
{
Debug.Log("OnUnityAdsShowComplete "+showCompletionState);
if (placementId.Equals("Rewarded_Android") && UnityAdsShowCompletionState.COMPLETED.Equals(showCompletionState))
{
Debug.Log("rewared Player");
}
Time.timeScale = 1;
Advertisement.Banner.Show("Banner_Android");
}
public void LoadBannerAd()
{
Advertisement.Banner.SetPosition(BannerPosition.BOTTOM_CENTER);
Advertisement.Banner.Load("Banner_Android",
new BannerLoadOptions
{
loadCallback = OnBannerLoaded,
errorCallback = OnBannerError
}
);
}
void OnBannerLoaded()
{
Advertisement.Banner.Show("Banner_Android");
}
void OnBannerError(string message)
{
}
}
i just want to know how to check if unity interstital or rewarded ads are ready before showing them.
because in new versions Advertisment.isReady() is not working any more

Related

Ads are showing when I build a apk in unity but when app bundle is uploaded on playstore, it doesn't

I recently launched a game in unity which I uploaded on playstore. I was able to display ads when I just built an apk from the app but when I upload the app bundle on playstore and playstore launched that update, the ads stop displaying. My admob account is approved and my individual app's approval status is also 'Ready'.
I am not able to understand why my game is not displaying any ads as it should be working. All the ad ids are correct and it works fine in the normal apk. I am seeing proper ads.
Can someone help me please.
My AdManager Script
using GoogleMobileAds.Api;
using GoogleMobileAds.Common;
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MediationManager : MonoBehaviour
{
#region Ad_IDs
public string app_Id;
public string banner_Id;
public string nativeBanner_Id;
public string interstitial_Id;
public string rewardedVideo_Id;
public static MediationManager Instance;
private BannerView bannerView;
private BannerView nativebannerView;
private InterstitialAd interstitial;
private RewardedAd rewardedAd;
#endregion
private void Awake()
{
if (Instance == null)
{
Instance = this;
DontDestroyOnLoad(this);
print("again");
}
else
{
print("not again");
Destroy(this.gameObject);
}
}
// Start is called before the first frame update
void Start()
{
MobileAds.SetiOSAppPauseOnBackground(true);
//RequestConfiguration requestConfiguration =
// new RequestConfiguration.Builder()
// .SetTagForChildDirectedTreatment(TagForChildDirectedTreatment.True)
// .build();
//MobileAds.SetRequestConfiguration(requestConfiguration);
// Initialize the Google Mobile Ads SDK.
MobileAds.Initialize(HandleInitCompleteAction);
}
private void HandleInitCompleteAction(InitializationStatus initstatus)
{
MobileAdsEventExecutor.ExecuteInUpdate(() =>
{
//RequestBanner();
RequestInterstitial();
RequestAdmobRewarded();
// RequestNativeBanner();
//ShowTopBanner();
});
}
#region Request Ads
public AdRequest CreateAdRequest()
{
return new AdRequest.Builder().Build();
}
private void RequestInterstitial()
{
if (PlayerPrefs.GetInt("adsRemoveCount") <= 2)
{
// Clean up interstitial ad before creating a new one.
if (this.interstitial != null)
{
this.interstitial.Destroy();
}
// Create an interstitial.
this.interstitial = new InterstitialAd(interstitial_Id);
// Register for ad events.
this.interstitial.OnAdLoaded += this.HandleOnAdLoaded;
this.interstitial.OnAdFailedToLoad += this.HandleOnAdFailedToLoad;
this.interstitial.OnAdOpening += this.HandleOnAdOpened;
this.interstitial.OnAdClosed += this.HandleOnAdClosed;
// this.interstitial. += this.HandleOnAdLeavingApplication;
// Load an interstitial ad.
this.interstitial.LoadAd(this.CreateAdRequest());
}
}
public void RequestBanner()
{
if (PlayerPrefs.GetInt("RemoveAds") == 0)
{
// Clean up banner ad before creating a new one.
if (this.bannerView != null)
{
this.bannerView.Destroy();
}
// Create a 320x50 banner at the top of the screen.
this.bannerView = new BannerView(banner_Id, AdSize.Banner, AdPosition.Top);
// Register for ad events.
this.bannerView.OnAdLoaded += this.HandleAdLoaded;
this.bannerView.OnAdFailedToLoad += this.HandleAdFailedToLoad;
this.bannerView.OnAdOpening += this.HandleAdOpened;
this.bannerView.OnAdClosed += this.HandleAdClosed;
//this.bannerView.OnAdLeavingApplication += this.HandleAdLeftApplication;
// Load a banner ad.
this.bannerView.LoadAd(this.CreateAdRequest());
this.bannerView.Hide();
print("Show Top Banner");
}
}
public void RequestNativeBanner()
{
if (PlayerPrefs.GetInt("RemoveAds") == 0)
{
if (this.nativebannerView != null)
{
this.nativebannerView.Destroy();
}
this.nativebannerView = new BannerView(banner_Id, AdSize.MediumRectangle, 0, 54);
this.nativebannerView.LoadAd(this.CreateAdRequest());
this.nativebannerView.Hide();
}
}
private void RequestAdmobRewarded()
{
if (PlayerPrefs.GetInt("adsRemoveCount") <= 2)
{
this.rewardedAd = new RewardedAd(rewardedVideo_Id);
// Called when an ad request has successfully loaded.
this.rewardedAd.OnAdLoaded += HandleRewardedAdLoaded;
// Called when an ad request failed to load.
// this.rewardedAd.OnAdFailedToLoad += HandleRewardedAdFailedToLoad;
// Called when an ad is shown.
this.rewardedAd.OnAdOpening += HandleRewardedAdOpening;
// Called when an ad request failed to show.
this.rewardedAd.OnAdFailedToShow += HandleRewardedAdFailedToShow;
// Called when the user should be rewarded for interacting with the ad.
this.rewardedAd.OnUserEarnedReward += HandleUserEarnedReward;
// Called when the ad is closed.
this.rewardedAd.OnAdClosed += HandleRewardedAdClosed;
// Load the rewarded ad with the request.
this.rewardedAd.LoadAd(this.CreateAdRequest());
}
}
#endregion
#region Banner callback handlers
public void HandleAdLoaded(object sender, EventArgs args)
{
MonoBehaviour.print("HandleAdLoaded event received");
}
public void HandleAdFailedToLoad(object sender, AdFailedToLoadEventArgs args)
{
MonoBehaviour.print("HandleFailedToReceiveAd event received with message: " + args.LoadAdError);
}
public void HandleAdOpened(object sender, EventArgs args)
{
MonoBehaviour.print("HandleAdOpened event received");
}
public void HandleAdClosed(object sender, EventArgs args)
{
MonoBehaviour.print("HandleAdClosed event received");
}
public void HandleAdLeftApplication(object sender, EventArgs args)
{
MonoBehaviour.print("HandleAdLeftApplication event received");
}
#endregion
#region Interstial callback handlers
public void HandleOnAdLoaded(object sender, System.EventArgs args)
{
MonoBehaviour.print("HandleAdLoaded event received");
}
public void HandleOnAdFailedToLoad(object sender, AdFailedToLoadEventArgs args)
{
MonoBehaviour.print("HandleFailedToReceiveAd event received with message: "
+ args.ToString());
RequestInterstitial();
}
public void HandleOnAdOpened(object sender, System.EventArgs args)
{
MonoBehaviour.print("HandleAdOpened event received");
}
public void HandleOnAdClosed(object sender, System.EventArgs args)
{
MonoBehaviour.print("HandleAdClosed event received");
RequestInterstitial();
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex - 1);
}
public void HandleOnAdLeavingApplication(object sender, System.EventArgs args)
{
MonoBehaviour.print("HandleAdLeavingApplication event received");
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex - 1);
}
#endregion
#region AdmobRewarded_Ad callback handlers
public void HandleRewardedAdLoaded(object sender, System.EventArgs args)
{
MonoBehaviour.print("HandleRewardedAdLoaded event received");
}
public void HandleRewardedAdFailedToLoad(object sender, AdErrorEventArgs args)
{
MonoBehaviour.print(
"HandleRewardedAdFailedToLoad event received with message: "
+ args.AdError.GetMessage());
// RequestAdmobRewarded();
}
public void HandleRewardedAdOpening(object sender, System.EventArgs args)
{
MonoBehaviour.print("HandleRewardedAdOpening event received");
// RequestAdmobRewarded();
}
public void HandleRewardedAdFailedToShow(object sender, AdErrorEventArgs args)
{
MonoBehaviour.print(
"HandleRewardedAdFailedToShow event received with message: "
+ args.AdError.GetMessage());
// RequestAdmobRewarded();
}
public void HandleRewardedAdClosed(object sender, System.EventArgs args)
{
MonoBehaviour.print("HandleRewardedAdClosed event received");
RequestAdmobRewarded();
}
public void HandleUserEarnedReward(object sender, Reward args)
{
string type = args.Type;
double amount = args.Amount;
if (PlayerPrefs.HasKey("adsRemoveCount"))
{
PlayerPrefs.SetInt("adsRemoveCount", PlayerPrefs.GetInt("adsRemoveCount") + 1);
}
else
{
PlayerPrefs.SetInt("adsRemoveCount", 1);
}
}
#endregion
#region Ads Call Function
public void ShowAdmobInterstial()
{
if (PlayerPrefs.GetInt("adsRemoveCount") <= 2)
{
if (interstitial.IsLoaded())
{
interstitial.Show();
}
else
{
RequestInterstitial();
}
}
}
public void ShowAdmobRewardedVideo()
{
if (PlayerPrefs.GetInt("adsRemoveCount") <= 2)
{
if (this.rewardedAd.IsLoaded())
{
this.rewardedAd.Show();
}
else
{
RequestAdmobRewarded();
}
}
}
#endregion
}

How to Integrate Huawei Account kit

Currently I'm using Huawei Plugin From EvilMindDev.
Below is AccountManager script.
using HuaweiMobileServices.Id;
using HuaweiMobileServices.Utils;
using System;
using UnityEngine;
namespace HmsPlugin
{
public class AccountManager : MonoBehaviour
{
public static AccountManager GetInstance(string name = "AccountManager") => GameObject.Find(name).GetComponent<AccountManager>();
private static HuaweiIdAuthService DefaultAuthService
{
get
{
Debug.Log("[HMS]: GET AUTH");
var authParams = new HuaweiIdAuthParamsHelper(HuaweiIdAuthParams.DEFAULT_AUTH_REQUEST_PARAM).SetIdToken().CreateParams();
Debug.Log("[HMS]: AUTHPARAMS AUTHSERVICE" + authParams);
var result = HuaweiIdAuthManager.GetService(authParams);
Debug.Log("[HMS]: RESULT AUTHSERVICE"+ result);
return result;
}
}
public AuthHuaweiId HuaweiId { get; private set; }
public Action<AuthHuaweiId> OnSignInSuccess { get; set; }
public Action<HMSException> OnSignInFailed { get; set; }
private HuaweiIdAuthService authService;
// Start is called before the first frame update
void Awake()
{
Debug.Log("[HMS]: AWAKE AUTHSERVICE");
authService = DefaultAuthService;
Debug.Log("DefaultAuthService : "+DefaultAuthService);
Debug.Log("authService : "+authService);
}
public void SignIn()
{
Debug.Log("[HMS]: Sign in " + authService);
authService.StartSignIn((authId) =>
{
HuaweiId = authId;
Debug.Log("HuaweiId : "+HuaweiId);
OnSignInSuccess?.Invoke(authId);
}, (error) =>
{
HuaweiId = null;
OnSignInFailed?.Invoke(error);
});
}
public void SignOut()
{
Debug.Log("authService.SignOut");
authService.SignOut();
HuaweiId = null;
}
}
}
Below is AccountSignIn script.
using HuaweiMobileServices.Id;
using HuaweiMobileServices.Utils;
using UnityEngine;
using UnityEngine.UI;
using HmsPlugin;
public class AccountSignIn : MonoBehaviour
{
private const string NOT_LOGGED_IN = "No user logged in";
private const string LOGGED_IN = "{0} is logged in";
private const string LOGIN_ERROR = "Error or cancelled login";
private Text loggedInUser;
private AccountManager accountManager;
// Start is called before the first frame update
void Start()
{
loggedInUser = GameObject.Find("LoggedUserText").GetComponent<Text>();
loggedInUser.text = NOT_LOGGED_IN;
//accountManager = AccountManager.GetInstance();
accountManager = GetComponent<AccountManager>();
accountManager.OnSignInSuccess = OnLoginSuccess;
accountManager.OnSignInFailed = OnLoginFailure;
LogIn();
}
public void LogIn()
{
accountManager.SignIn();
}
public void LogOut()
{
accountManager.SignOut();
loggedInUser.text = NOT_LOGGED_IN;
}
public void OnLoginSuccess(AuthHuaweiId authHuaweiId)
{
loggedInUser.text = string.Format(LOGGED_IN, authHuaweiId.DisplayName);
}
public void OnLoginFailure(HMSException error)
{
loggedInUser.text = LOGIN_ERROR;
}
}
Everytime I try to SignIn it will give me this error.
This is HuaweiIdAuthService.
Even if I try the demo provided will give me the same error.
If I try debug using Android Studio it will still give me the same error.
public void SignIn()
{
Debug.Log("[HMS]: Sign in " + authService);
authService.StartSignIn((authId) =>
{
HuaweiId = authId;
Debug.Log("HuaweiId : "+HuaweiId);
OnSignInSuccess?.Invoke(authId);
}, (error) =>
{
HuaweiId = null;
OnSignInFailed?.Invoke(error);
});
}
the authService doesn't return anything. Where can I get that from ?
It is a null pointer. Please check for unassigned objects. If you cannot find anything, please delete project and install again cause sometimes these kind of things happening.
This plugin have 2 branch for Unity 2019 and Unity 2018.
You should activate Account Kit API in Huawei Appgallery
Check configuration AndroidManifest file
Check Agconnect-service.json file

Using admob rewarded ad in unity singleton pattern

I am using admob ads in my app and they are working fine. But when i try to do something after a ad close or reward earned call back my code breaks. Following is my adMob script
public class AdMobScript : MonoBehaviour
{
...
public event Action OnReviveRewardEarned;
public event Action OnReviveAdLoaded;
public event Action OnReviveAdClosed;
private void LoadReviveRewardedAd()
{
reviveRewardedAd = new RewardedAd(adReviveRewardedId);
reviveRewardedAd.OnAdLoaded += ReviveAdLoaded;
reviveRewardedAd.OnUserEarnedReward += ReviveEarnedReward;
reviveRewardedAd.OnAdClosed += ReviveAdClosed;
AdRequest request = new AdRequest.Builder().Build();
reviveRewardedAd.LoadAd(request);
}
private void ReviveAdClosed(object sender, EventArgs e)
{
LoadReviveRewardedAd();
if (isRewardErned)
{
isRewardErned = false;
OnReviveRewardEarned.Invoke();
}
else
OnReviveAdClosed.Invoke();
}
private void ReviveEarnedReward(object sender, Reward e)
{
isRewardErned = true;
}
private void ReviveAdLoaded(object sender, EventArgs e)
{
//reviveButton.interactable = true;
OnReviveAdLoaded.Invoke();
}
public void ShowAdToRevive()
{
if (reviveRewardedAd.IsLoaded())
{
reviveRewardedAd.Show();
}
}
...
}
In the callbacks i am calling my adManager script which is in term using adMob script. Here is the code for it.
public class AdManager : MonoBehaviour
{
...
private void Start() {
AdMobScript.instance.OnReviveAdClosed += ReviveAdClosed;
AdMobScript.instance.OnReviveAdLoaded += ReviveAdLoaded;
AdMobScript.instance.OnReviveRewardEarned += ReviveReward;
}
#region ReviveAds
private void ReviveReward() {
//game crash here
backButton.gameObject.SetActive(true);
reviveButton.gameObject.SetActive(false);
noThanksButton.gameObject.SetActive(false);
manager.Revive();
}
private void ReviveAdLoaded() {
reviveButton.interactable = true;
}
private void ReviveAdClosed() {
//game crash here
reviveButton.interactable = false;
}
public void ShowAdToRevive() {
AdMobScript.instance.ShowAdToRevive();
}
...
}
After either ad close or reward earned my game crashes (error log says
get_gameObject can only be called from the main thread
). There must be something i am doing wrong. Can anyone please point me to the right direction?
The reason for the problem - you trying to manipulate with MonoBehaviors, not in main thread.
Just write simple scheduler which calls the events in the Unity thread, like this:
Scheduler:
using System;
using UnityEngine;
public class Scheduler : MonoBehaviour
{
public static Scheduler instance;
public event Action secondTick = delegate { };
private float seconds = 0;
private void Awake()
{
instance = this;
}
private void Update()
{
seconds += Time.unscaledDeltaTime;
if (seconds >= 1.0f)
{
seconds -= 1.0f;
secondTick.Invoke();
}
}
}
Updated AdMobScript:
public class AdMobScript : MonoBehaviour
{
...
private bool onRewardEarnedCall = false;
private bool onRewardAdLoaded = false;
private bool onRewardAdClosed = false;
public event Action OnReviveRewardEarned;
public event Action OnReviveAdLoaded;
public event Action OnReviveAdClosed;
private void LoadReviveRewardedAd()
{
reviveRewardedAd = new RewardedAd(adReviveRewardedId);
reviveRewardedAd.OnAdLoaded += ReviveAdLoaded;
reviveRewardedAd.OnUserEarnedReward += ReviveEarnedReward;
reviveRewardedAd.OnAdClosed += ReviveAdClosed;
AdRequest request = new AdRequest.Builder().Build();
reviveRewardedAd.LoadAd(request);
Scheduler.instance.secondTick += OnSecondTick;
}
private void OnSecondTick()
{
if(onRewardAdClosed)
{
onRewardAdClosed = false;
OnReviveAdClosed.Invoke();
}
if(onRewardEarnedCall)
{
OnReviveRewardEarned.Invoke();
onRewardEarnedCall = false;
}
if(onRewardAdLoaded)
{
OnReviveAdLoaded.Invoke();
onRewardAdLoaded = false;
}
}
private void ReviveAdClosed(object sender, EventArgs e)
{
LoadReviveRewardedAd();
if (isRewardErned)
{
isRewardErned = false;
onRewardEarnedCall = true;
}
else
onRewardAdClosed = true;
}
private void ReviveEarnedReward(object sender, Reward e)
{
isRewardErned = true;
}
private void ReviveAdLoaded(object sender, EventArgs e)
{
//reviveButton.interactable = true;
onRewardAdLoaded = true;
}
public void ShowAdToRevive()
{
if (reviveRewardedAd.IsLoaded())
{
reviveRewardedAd.Show();
}
}
...
}
This is a very simple and not optimize solution but this will solve your problem.

Xamarin WebView Not loading stream which comes from webrtc

class MyWebViewRenderer : WebViewRenderer
{
Activity mContext;
public MyWebViewRenderer(Context context) : base(context)
{
this.mContext = context as Activity;
}
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
{
base.OnElementChanged(e);
Control.Settings.JavaScriptEnabled = true;
Control.ClearCache(true);
Control.Settings.DomStorageEnabled = true;
Control.Settings.PluginsEnabled = true;
Control.Settings.SetAppCacheEnabled(true);
Control.Settings.CacheMode = CacheModes.NoCache;
Control.Settings.SetRenderPriority(WebSettings.RenderPriority.High);
Control.Settings.LightTouchEnabled = true;
Control.SetWebChromeClient(new MyWebClient(mContext));
Control.SetWebViewClient(new SSLTolerentWebViewClient());
Control.LoadUrl(Control.Url);
}
public class MyWebClient : WebChromeClient
{
Activity mContext;
public MyWebClient(Activity context)
{
this.mContext = context;
}
[TargetApi(Value = 21)]
public override void OnPermissionRequest(PermissionRequest request)
{
mContext.RunOnUiThread(() =>
{
request.Grant(request.GetResources());
});
}
}
private class SSLTolerentWebViewClient : WebViewClient
{
public override void OnReceivedSslError(Android.Webkit.WebView view, SslErrorHandler handler, SslError error)
{
handler.Proceed(); // Ignore SSL certificate errors
}
public override void OnLoadResource(Android.Webkit.WebView view,string url)
{
}
}
}
Unfortunately, Android doesn't support WebRTC on its native webview yet, as you can see in the official documentation: https://developer.chrome.com/multidevice/webview/overview
It's not your code. You would have to find a way around it.

Passing ExoPlayer instance from activity to binded service?

I'm trying to make a Video Player using ExoPlayer that can also work in the background and you can control it through the notification. I already created the ExoPlayer and the ForeGround Service for the notification and i binded them. At the moment it works as intended, the only problem is that i don't want the activity player to stop working when i close the notification. This happens because at the moment i'm creating the ExoPlayer instance in the service and then i pass the instance to the Activity, so when i close the notification the instance gets lost. Is there a way to initialize the player instance in the Activity and then pass that instance to the service so i can still control the video from the notification without risking to lose the instance once the notification is closed?
I'm pretty new to android and this is the first time that i'm binding a service to an activity so i don't really know how to do it. I tried searching on Google but that didn't help either.
This is the Activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playerView=findViewById(R.id.player_view);
intent=new Intent(this,AudioPlayerService.class);
//here i will add the url that needs to be loaded
//but at the moment this is just a draft
Util.startForegroundService(this,intent);
playerView.setUseController(true);
//playerView.showController();
playerView.setControllerAutoShow(true);
playerView.setControllerHideOnTouch(true);
}
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
AudioPlayerService.LocalBinder binder = (AudioPlayerService.LocalBinder) iBinder;
mService = binder.getService();
mBound = true;
initializePlayer();
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
mBound = false;
}
};
#Override
public void onStart() {
super.onStart();
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
initializePlayer();
}
#Override
protected void onStop() {
unbindService(mConnection);
mBound = false;
super.onStop();
}
private void releasePlayer() {
if (player != null) {
player.release();
player = null;
}
}
private void initializePlayer() {
if (mBound) {
SimpleExoPlayer player = mService.getplayerInstance();
playerView.setPlayer(player);
}
}
}
This is the Service
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public SimpleExoPlayer getplayerInstance() {
if (player == null) {
startPlayer();
}
return player;
}
public class LocalBinder extends Binder {
public AudioPlayerService getService() {
return AudioPlayerService.this;
}
}
#Override
public void onCreate() {
super.onCreate();
final Context context=this;
}
private void startPlayer() {
final Context context = this;
player = ExoPlayerFactory.newSimpleInstance(context, new DefaultTrackSelector());
ProgressiveMediaSource mediaSource = new ProgressiveMediaSource.Factory(new DefaultHttpDataSourceFactory("NotificationSync", 10000, 10000, true))
.createMediaSource(Uri.parse("https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"));
player.prepare(mediaSource);
player.setPlayWhenReady(true);
playerNotificationManager = PlayerNotificationManager.createWithNotificationChannel(context, "1",
R.string.app_name,
2,
new PlayerNotificationManager.MediaDescriptionAdapter() {
#Override
public String getCurrentContentTitle(Player player) {
return "title";
}
#Nullable
#Override
public PendingIntent createCurrentContentIntent(Player player) {
Intent intent = new Intent(context, MainActivity.class);
return PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
#Nullable
#Override
public String getCurrentContentText(Player player) {
return "text";
}
#Nullable
#Override
public Bitmap getCurrentLargeIcon(Player player, PlayerNotificationManager.BitmapCallback callback) {
return null;
}
}, new PlayerNotificationManager.NotificationListener() {
#Override
public void onNotificationCancelled(int notificationId, boolean dismissedByUser) {
stopSelf();
}
#Override
public void onNotificationPosted(int notificationId, Notification notification, boolean ongoing) {
mNotification = notification;
mNotificationId = notificationId;
if (ongoing) {
startForeground(notificationId, notification);
}
}
}
);
playerNotificationManager.setPlayer(player);
playerNotificationManager.setUseStopAction(true);
}
#Override
public void onDestroy() {
releasePlayer();
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (player == null) {
//here i will get all the data from the intent that came from the
//activity (title,text,url...)
startPlayer();
}
return START_STICKY;
}
private void releasePlayer() {
if (player != null) {
player.release();
player = null;
}
}
}
In the end all i want to achieve is a video player that you start in the activity and also works/can be controlled through a notification without interruption when i go from activity->background and background->activity. If there are other ways to achieve this i'm open to try.