how to add ( admob ) Interstitial ads to libgdx game and what activity to use? - libgdx

I followed google guide:
updated build.gradle dependencies
updated AndroidManifest.xml
updated the AndroidLauncher and tried banner ads first
from libgdx wiki https://libgdx.com/wiki/third-party/admob-in-libgdx
#Override public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create the layout
RelativeLayout layout = new RelativeLayout(this);
// Do the stuff that initialize() would do for you
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
// Create the libGDX View
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
View gameView = initializeForView(new mygame(), config);
// Create and setup the AdMob view
AdView adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111"); // Put in your secret key here
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
// Add the libGDX view
layout.addView(gameView);
// Add the AdMob view
RelativeLayout.LayoutParams adParams =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
adParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
adParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
layout.addView(adView, adParams);
// Hook it all up
setContentView(layout);
}}
but I cant figure out how to do the same for Interstitial ads
i tried adding adscontroller interface
public interface AdsController {
public void loadInterstitialAd();
public void showInterstitialAd();
}
and updating AndroidLauncher
public class AndroidLauncher extends AndroidApplication implements AdsController {
InterstitialAd mInterstitialAd;
private static final String TAG = "Androidlauncher";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// // Create the layout
RelativeLayout layout = new RelativeLayout(this);
// Do the stuff that initialize() would do for you
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
// Create the libGDX View
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
View gameView = initializeForView(new mygame(this), config);
layout.addView(gameView);
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {}
});
AdRequest adRequest = null;
InterstitialAd.load(this,"ca-app-pub-3940256099942544/1033173712", adRequest,
new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
mInterstitialAd = interstitialAd;
Log.i(TAG, "onAdLoaded");
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
// Handle the error
Log.d(TAG, loadAdError.toString());
mInterstitialAd = null;
}
});
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback(){
#Override
public void onAdClicked() {
// Called when a click is recorded for an ad.
Log.d(TAG, "Ad was clicked.");
}
#Override
public void onAdDismissedFullScreenContent() {
// Called when ad is dismissed.
// Set the ad reference to null so you don't show the ad a second time.
Log.d(TAG, "Ad dismissed fullscreen content.");
mInterstitialAd = null;
}
#Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
// Called when ad fails to show.
Log.e(TAG, "Ad failed to show fullscreen content.");
mInterstitialAd = null;
}
#Override
public void onAdImpression() {
// Called when an impression is recorded for an ad.
Log.d(TAG, "Ad recorded an impression.");
}
#Override
public void onAdShowedFullScreenContent() {
// Called when ad is shown.
Log.d(TAG, "Ad showed fullscreen content.");
}
});
loadInterstitialAd();
}
#Override
public void loadInterstitialAd() {
AdRequest adRequest = new AdRequest.Builder().build();
}
#Override
public void showInterstitialAd() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if(mInterstitialAd!=null) {
mInterstitialAd.show();
}
else loadInterstitialAd();
}
});
}
}
InterstitialAd.show(MyActivity.this); require activity but libgdx doesn't work like that(I think?)
every code I found is no longer useful because google updated Admob

AndroidApplication extends Activity, so for interstitials you can just pass in a reference to the application, eg InterstitialAd.show(this);
I did something very similar to get interstitials working in my project. I use Ironsource but the process should be very similar. First, I defined an AdManager interface:
public interface AdManager {
/**
* Show a rewarded video ad
*/
void showRewardedVideo();
/**
* Called on app pause
*/
void onPause();
/**
* Called on app resume
*/
void onResume();
/**
* Attempts to show an interstitial ad
*
* #param onSuccess
* #param onFailed
*/
void showInterstitial(Listener onSuccess, Listener onFailed);
/**
* Called every frame, for any extra work that might need to be done
*
* #param deltaTime
*/
void update(float deltaTime);
}
Following that, you can implement your platform's ad provider:
public class AndroidAdManager implements AdManager, RewardedVideoListener, InterstitialListener, OfferwallListener {
private OnlineRPG game;
private boolean videoAvailable;
private Listener onInterstitialSuccess;
private Listener onInterstitialFailed;
private float timeSinceAd;
public AndroidAdManager(Activity activity, Gamegame) {
this.game = game;
this.activity = activity;
IronSource.setRewardedVideoListener(this);
IronSource.setInterstitialListener(this);
IronSource.setOfferwallListener(this);
IronSource.init(activity, "whatever");
IronSource.shouldTrackNetworkState(activity, true);
IronSource.loadInterstitial();
IntegrationHelper.validateIntegration(activity);
}
#Override
public void showRewardedVideo() {
if (IronSource.isRewardedVideoPlacementCapped(REWARDED_VIDEO_PLACEMENT_NAME)) {
Log.i(TAG, "Rewarded video placement is capped");
return;
}
IronSource.showRewardedVideo(REWARDED_VIDEO_PLACEMENT_NAME);
}
#Override
public void onPause() {
IronSource.onPause(activity);
}
#Override
public void onResume() {
IronSource.onResume(activity);
}
#Override
public void showInterstitial(Listener onSuccess, Listener onFailed) {
if (timeSinceAd < INTERSTITIAL_MIN_PERIOD || true) {
onFailed.invoke();
return;
}
this.onInterstitialSuccess = onSuccess;
this.onInterstitialFailed = onFailed;
IronSource.showInterstitial(INTERSTITIAL_PLACEMENT_NAME);
}
#Override
public void update(float deltaTime) {
timeSinceAd += deltaTime;
}
#Override
public void onRewardedVideoAdOpened() {
}
#Override
public void onRewardedVideoAdClosed() {
}
#Override
public void onRewardedVideoAvailabilityChanged(boolean b) {
Log.i(TAG, "onRewardedVideoAvailabilityChanged: " + b);
videoAvailable = b;
}
#Override
public void onRewardedVideoAdStarted() {
}
#Override
public void onRewardedVideoAdEnded() {
}
#Override
public void onRewardedVideoAdRewarded(Placement placement) {
}
#Override
public void onRewardedVideoAdShowFailed(IronSourceError ironSourceError) {
}
#Override
public void onRewardedVideoAdClicked(Placement placement) {
}
#Override
public void onInterstitialAdReady() {
}
#Override
public void onInterstitialAdLoadFailed(IronSourceError ironSourceError) {
if (onInterstitialFailed != null) {
Gdx.app.postRunnable(new Runnable() {
#Override
public void run() {
onInterstitialFailed.invoke();
onInterstitialFailed = null;
}
});
}
}
#Override
public void onInterstitialAdOpened() {
Log.i(TAG, "Interstitial Ad Opened");
}
#Override
public void onInterstitialAdClosed() {
Log.i(TAG, "Interstitial Ad Closed");
if (onInterstitialSuccess != null) {
Gdx.app.postRunnable(new Runnable() {
#Override
public void run() {
timeSinceAd = 0;
onInterstitialSuccess.invoke();
onInterstitialSuccess = null;
}
});
}
IronSource.loadInterstitial();
}
#Override
public void onInterstitialAdShowSucceeded() {
}
#Override
public void onInterstitialAdShowFailed(IronSourceError ironSourceError) {
Log.e(TAG, ironSourceError.getErrorMessage());
if (onInterstitialFailed != null) {
Gdx.app.postRunnable(new Runnable() {
#Override
public void run() {
onInterstitialFailed.invoke();
onInterstitialFailed = null;
}
});
}
}
#Override
public void onInterstitialAdClicked() {
}
#Override
public void onOfferwallAvailable(boolean b) {
}
#Override
public void onOfferwallOpened() {
}
#Override
public void onOfferwallShowFailed(IronSourceError ironSourceError) {
}
#Override
public boolean onOfferwallAdCredited(int i, int i1, boolean b) {
return false;
}
#Override
public void onGetOfferwallCreditsFailed(IronSourceError ironSourceError) {
}
#Override
public void onOfferwallClosed() {
}
}
Lastly, in your AndroidLauncher you can create your AndroidAdManager, giving it a reference to your game/activity.
public class AndroidLauncher extends AndroidApplication {
private Game game;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
game = new Game();
game.setAdManager(new AndroidAdManager(this, game));
game.setPermissionManager(new AndroidPermissionManager(this, game));
initialize(game, config);
}
#Override
protected void onPause() {
super.onPause();
game.getAds().onPause();
}
#Override
protected void onResume() {
super.onResume();
game.getAds().onResume();
}
}
I hope this helps in your project!

Related

Getting data in recyclerView

i am getting messages from the database into a recycler view but i want to refresh the recycler view every second for to adding different for to getting new messages in recycler view
But i haver an error of getting data please see it https://www.filemail.com/d/izhittgyibvcjxx
my code is
boolean refresh;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message_user);
refresh = true;
content();
}
public void content()
{
getdata();
if (refresh)
{
refresh(100);
}
}
private void refresh(int milliseconds)
{
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
#Override
public void run() {
content();
}
};
handler.postDelayed(runnable,milliseconds);
}
private void getdata()
{
String Choice = "Get Messages";
Call<List<responsemodel>> call = SplashScreen.apiInterface.getfullprofiledata(Choice,Message_To,Message_From);
call.enqueue(new Callback<List<responsemodel>>() {
#Override
public void onResponse(Call<List<responsemodel>> call, Response<List<responsemodel>> response) {
List<responsemodel> data = response.body();
Message_user_Adapter adapter = new Message_user_Adapter(data,Message_To);
messages_Message_user_RecyclerView.setAdapter(adapter);
messages_Message_user_RecyclerView.smoothScrollToPosition(messages_Message_user_RecyclerView.getAdapter().getItemCount());
}
#Override
public void onFailure(Call<List<responsemodel>> call, Throwable t) {
}
});
}

reopen Google map stops my Application

i have tow fragment. by click in first fragment button second fragment that is Google map will open.
first time all thing is correct but if i back and click again program will stop.
map fragment code is as blow:
public class map extends Fragment implements OnMapReadyCallback {
private GoogleMap mMap;
private double lat;
private double att;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.map,container,false);
// GoogleMap map = ((MapFragment) getFragmentManager(.findFragmentById(R.id.map)).getMap();
return view;
}
#Override
public void onStart() {
super.onStart();
if (getArguments() != null) {
lat= getArguments().getDouble("LAT");
att=getArguments().getDouble("ATT");
Toast.makeText(getActivity(),String.valueOf(att),Toast.LENGTH_LONG).show();
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onMapReady(GoogleMap googleMap) {
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(lat, att);
CameraPosition googlePlex = CameraPosition.builder()
.target(new LatLng(lat,att))
.zoom(16).build();
googleMap.addMarker(new MarkerOptions().position(sydney));
googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(googlePlex));
}
}
and main activity is:
public class MainActivity extends AppCompatActivity implements onclicklistener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(findViewById(R.id.firstpage)!=null)
{
if(savedInstanceState!=null)
return;
firstpage startpage=new firstpage();
FragmentManager fm=getFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
ft.add(R.id.firstpage,startpage);
ft.commit();
}
}
#Override
public void onclickbutton(String index) {
try{ map newmap=new map();
Bundle args = new Bundle();
args.putDouble("LAT",32.657892);
args.putDouble("ATT",51.668643);
FragmentManager fm=getFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
newmap.setArguments(args);
ft.addToBackStack(null);
ft.replace(R.id.firstpage,newmap);
ft.commit();}
catch (Exception e){Toast toast = Toast.makeText(this, "error", Toast.LENGTH_SHORT);}
}
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0 ){
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
}
first Run is completely OK but if i click again program will stop. please guide me.
it solved.
i added this code:
#Override
public void onDetach() {
Fragment fragment = (getFragmentManager().findFragmentById(R.id.map));
FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
ft.remove(fragment);
ft.commit();
super.onDetach();
}

notifyDataSetChanged on RecyclerView

I have a recyclerView and customAdaprer. I pass an list of an object (earthquakeList)to recycleradapter and then i do setAdapter:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
earthquakeList = new ArrayList<>();
adapter = new RecyclerViewAdapter(earthquakeList);
recyclerView.setAdapter(adapter);
}
I create AsyncTask on onResume method:
#Override
protected void onResume() {
super.onResume();
// Kick off an {#link AsyncTask} to perform the network request
new EarthQuakeAsyncTask().execute();
}
in AsyncTask my class i get a new List from my object that i get from internet and when I replaced this new list with older list and call notifyDataSetChanged, recyclerView still nothing show??
I debug my app and I get object from net.
I do in this way on list view but recylerview seems efferent.
I replace old list with the new list one like blow:
private class EarthQuakeAsyncTask extends AsyncTask<Void, Void, List<Earthquake>> {
#Override
protected List<Earthquake> doInBackground(Void... urls) {
// Create URL object
URL url = HttpRequest.createUrl(USGS_REQUEST_URL);
// perform HTTP request to the URL and receive a JSON response back
String jsonResponse = "";
try {
jsonResponse = HttpRequest.makeHttpRequest(url);
} catch (IOException e) {
e.printStackTrace();
}
List<Earthquake> earthquakes = HttpRequest.extractFeaturesFromJson(jsonResponse);
return earthquakes;
}
#Override
protected void onPostExecute(List<Earthquake> earthquakeList) {
super.onPostExecute(earthquakeList);
MainActivity.this.earthquakeList.clear();
MainActivity.this.earthquakeList.addAll(earthquakeList);
adapter.notifyDataSetChanged();
}
what is exactly my wrong?
************************ EDIT ********************
this is Adapter :
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyHolder> {
List<Earthquake> earthquakes;
public RecyclerViewAdapter(List<Earthquake> earthquakes) {
this.earthquakes = earthquakes;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(
R.layout.earthquak_list_item, parent, false);
MyHolder myHolder = new MyHolder(view);
return myHolder;
}
#Override
public void onBindViewHolder(MyHolder holder, int position) {
Earthquake earthquake = earthquakes.get(position);
holder.magnitude.setText(earthquake.getmMagnitude());
holder.location.setText(earthquake.getmLocation());
holder.time.setText(earthquake.getmDate());
}
#Override
public int getItemCount() {
return (null != earthquakes ? earthquakes.size() : 0);
}
public void setItems(List<Earthquake> earthquakeList) {
this.earthquakes = earthquakeList;
}
public class MyHolder extends RecyclerView.ViewHolder {
#BindView(R.id.magnitude)
TextView magnitude;
#BindView(R.id.location)
TextView location;
#BindView(R.id.date)
TextView time;
public MyHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
Ops ,I forgot put LayoutManager for recyclerView .
this is right code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
earthquakeList = new ArrayList<>();
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
adapter = new RecyclerViewAdapter(earthquakeList);
recyclerView.setAdapter(adapter);
}

hide admob banner ads

I would like to show banner admob exactly at the moment the user enter into the main game screen. I hide the banner in onCreate with setAlpha(0f) method, and show it in the first render loop with setAlpha(1f). The timing is a bit off. How do I make it more precise? I also wonder if setting alpha is acceptable method to hide admob adds?
//RENDER LOOP
if(showAd==false){
actionResolver.showBanner();
showAd=true;
}
//android launcher
protected AdView adView;
protected View gameView;
private InterstitialAd interstitialAd;
private Activity context;
#Override
public void showBanner() {
try {
runOnUiThread(new Runnable() {
public void run() {
adView.setAlpha(1f);
}
});
} catch (Exception e) {
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context=this;
AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration();
// Do the stuff that initialize() would do for you
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
RelativeLayout layout = new RelativeLayout(this);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
layout.setLayoutParams(params);
AdView admobView = createAdView();
layout.addView(admobView);
View gameView = createGameView(cfg);
layout.addView(gameView);
setContentView(layout);
startAdvertising(admobView);
interstitialAd = new InterstitialAd(this);
interstitialAd.setAdUnitId(AD_UNIT_ID_INTERSTITIAL);
interstitialAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
}
#Override
public void onAdClosed() {
super.onAdClosed();
loadInterstitial();
}
});
}
private AdView createAdView() { ////// HERE I SET ALPHA
adView = new AdView(this);
adView.setAdSize(AdSize.SMART_BANNER);
adView.setAdUnitId(AD_UNIT_ID_BANNER);
adView.setId(123456); // this is an arbitrary id, allows for relative positioning in createGameView()
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
params.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
adView.setLayoutParams(params);
adView.setBackgroundColor(Color.BLACK);
adView.setAlpha(0f);
return adView;
}
private View createGameView(AndroidApplicationConfiguration cfg) {
gameView = initializeForView(new Cube(this,this), cfg);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
params.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
params.addRule(RelativeLayout.BELOW, adView.getId());
gameView.setLayoutParams(params);
return gameView;
}
private void startAdvertising(AdView adView) {
// AdRequest adRequest = new AdRequest.Builder().build();
// adView.loadAd(adRequest);
AdRequest.Builder builder = new AdRequest.Builder();
// builder.addTestDevice("3F39DA9CF3F587314F9C4C0D88639C28");
adView.loadAd(builder.build());
}
#Override
public void showInterstitial() {
try {
runOnUiThread(new Runnable() {
public void run() {
if (interstitialAd.isLoaded()) {
interstitialAd.show();
}
}
});
} catch (Exception e) {
}
}
#Override
public void loadInterstitial() {
try {
runOnUiThread(new Runnable() {
public void run() {
if(interstitialAd.isLoaded()){
}else{
AdRequest interstitialRequest = new AdRequest.Builder().build();
interstitialAd.loadAd(interstitialRequest);
}
}
});
} catch (Exception e) {
}
}
#Override
public void onResume() {
super.onResume();
if (adView != null) adView.resume();
}
#Override
public void onPause() {
if (adView != null) adView.pause();
super.onPause();
}
#Override
public void onDestroy() {
if (adView != null) adView.destroy();
super.onDestroy();
}
#TargetApi(19)
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}
}

libGDX Toast message

I have tried to use this tutorial:
http://www.badlogicgames.com/forum/viewtopic.php?f=11&t=484#p2959
Firstly have declared private Toast render_toast = new Toast(7, 6);
After that putted render_toast.toaster(); to render.
I would like to use it in show, so I have put this to show():
render_toast.makeText("Game start", "font", Toast.COLOR_PREF.BLUE, Toast.STYLE.ROUND, Toast.TEXT_POS.middle_right, Toast.TEXT_POS.middle_down, Toast.MED);
It isn't working, gives no error message, only stop my application.
I have implemented Android-like toast for my project and decided to share it with you! Enjoy: Toast LibGDX (GitHub)
Create an interface for required methods in your game. Implement this method in your AndroidLauncher class, using libgdx handler. You can call these methods anywhere in your game for Android related UI.
You can follow this video for details,
https://www.youtube.com/watch?v=XxiT3pkIiDQ
This is how, I used it in my game.
//Defining interface for customized methods
public interface AndroidInterfaces {
public void toast(final String t);
}
//implementing the interface in android launcer
public class AndroidLauncher extends AndroidApplication implements AndroidInterfaces{
final AndroidLauncher context=this;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration();
//if (Gdx.input.isPeripheralAvailable(Peripheral.Compass))
cfg.useCompass = true;
//cfg.useAccelerometer=true;
initialize(new MyGame(this), cfg);
}
#Override
public void toast(final String t) {
handler.post(new Runnable()
{
#Override
public void run() {
//System.out.println("toatsing in launcher run");
Toast.makeText(context, t, Toast.LENGTH_SHORT).show();
}
});
}
}
public class MyGame extends Game{
//16012016
//16012016 for toast
AndroidInterfaces aoi;
public MyGame(AndroidInterfaces maoi)
{
aoi=maoi;
}
public MyGame()
{
}
public boolean backpressed=false; //Universal flag to check back button press status , across screens.
.....
.....
}
public class MainMenuScreen implements Screen{
MyGame game;
float x,y,w,h,pw,gap;
float x1,y1; //coordinates for animation
//16012016
boolean toast=false;
float toasttimer=0;
public MainMenuScreen(MyGame gg) {
game = gg;
}
#Override
public void render(float delta) {
//16012016
if(toast)
{
toasttimer=toasttimer+delta;
}
.....
...//omitted
//16012016:Toast
if(toast)
{
if(toasttimer> 2.5)
Gdx.app.exit();
else if (Gdx.input.isKeyJustPressed(Keys.BACK)) //For double back press exit effect.
Gdx.app.exit();
}
else if (Gdx.input.justTouched()) {
game.setScreen(game.STS); //Setting another screen
}
//16012016
else if (Gdx.input.isKeyJustPressed(Keys.BACK))
if(!game.backpressed)
{
if(!toast)
{
toast=true; //if bsck button is just pressed in current screen then toasting..
game.aoi.toast("EXITING.THANKS FOR PLAYING!"); //Not relevant to desktop project, calling implemented method in androind launcher
}
}
}
else if(game.backpressed)
{
game.backpressed=false;
}
}
#Override
public void resize(int width, int height) {
}
#Override
public void show() {
//16012016
toasttimer=0;
toast=false;
Gdx.graphics.setContinuousRendering(true);
}
#Override
public void hide() {
Gdx.input.setInputProcessor(null);
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void dispose() {
}
}