LibGDX Admob LinearLayout code - java

I'm trying to put the admob in my LIBGDX application, but by following the tutorial GitHub and I can not run my application. Please someone tries to help me set up the code. Below is main_activity, main.xml.
Note: All modifications were made in AndroidManifest.xml as tutorial google admob.
Main.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="#+id/main_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
</LinearLayout>
MainAcitivity:
public class MainActivity extends AndroidApplication implements AdsController {
private static final String BANNER_AD_UNIT_ID = "ca-app-pub-3954521267929789/5402418153";
AdView bannerAd;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration();
cfg.useGL20 = false;
View gameView = initializeForView(new FXGame(this), cfg);
setupAds();
RelativeLayout layout = new RelativeLayout(this);
layout.addView(gameView, ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
layout.addView(bannerAd, params);
setContentView(layout);
}
public void setupAds() {
bannerAd = new AdView(this);
bannerAd.setVisibility(View.INVISIBLE);
bannerAd.setBackgroundColor(0xff000000); // black
bannerAd.setAdUnitId(BANNER_AD_UNIT_ID);
bannerAd.setAdSize(AdSize.SMART_BANNER);
}
#Override
public void showBannerAd() {
runOnUiThread(new Runnable() {
#Override
public void run() {
bannerAd.setVisibility(View.VISIBLE);
AdRequest.Builder builder = new AdRequest.Builder();
AdRequest ad = builder.build();
bannerAd.loadAd(ad);
}
});
}
#Override
public void hideBannerAd() {
runOnUiThread(new Runnable() {
#Override
public void run() {
bannerAd.setVisibility(View.INVISIBLE);
}
});
}
}
MY FXGame:
public class FXGame extends Game {
private AdsController adsController;
public ZBGame(AdsController adsController){
this.adsController = adsController;
}
#Override
public void create() {
AssetLoader.load();
setScreen(new SplashScreen(this));
adsController.showBannerAd();
}
#Override
public void dispose() {
super.dispose();
AssetLoader.dispose();
}
}
Interface AdsController:
public interface AdsController {
public void showBannerAd();
public void hideBannerAd();
}

You are setting visibility of bannerAd wrong in your showBannerAd and hideBannerAd methods. It should be opposite. Additionaly please ensure that you are calling show showBannerAd().

Related

How can I make clickable all the words in a text? [duplicate]

This question already has answers here:
Create clickable link in text view in android
(2 answers)
Closed 2 years ago.
I'm trying to develop an Android application with Java. I need to separate all words in a text (bookText in code) and make them clickable. How can I do this? I will be grateful if you could help me. Thanks in advance.
public class BookActivity extends AppCompatActivity {
public static final String BOOK_TEXT = "com.example.altaybook.BOOK_TEXT";
BookViewModel bookViewModel;
private TextView bookTextView;
private String bookName;
private String bookText;
ProgressBar bookTextProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book);
bookTextView = findViewById(R.id.book_text_id);
bookTextProgressBar = findViewById(R.id.bookTextProgressBar);
Intent intent = getIntent();
final int bookPosition = intent.getIntExtra(BOOK_TEXT, -1);
bookViewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication())).get(BookViewModel.class);
bookViewModel.getAllBooks().observe(this, new Observer<List<Book>>() {
#Override
public void onChanged(List<Book> books) {
bookName = books.get(bookPosition).getName();
setTitle(bookName);
bookText = books.get(bookPosition).getText();
SetTextAsyncTask setTextAsyncTask = new SetTextAsyncTask();
setTextAsyncTask.execute();
bookTextView.setMovementMethod(LinkMovementMethod.getInstance());
}
});
}
public class SetTextAsyncTask extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
bookTextProgressBar.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(String... strings) {
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
bookTextView.setText(bookText);
bookTextProgressBar.setVisibility(View.GONE);
}
}
}
You can use LinearLayout. Here is an example:
activity_book.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:orientation="horizontal"
android:gravity="center"
android:id="#+id/container"/>
</LinearLayout>
BookActivity.java
public class BookActivity extends Activity
{
public static final String BOOK_TEXT = "com.example.altaybook.BOOK_TEXT";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book);
LinearLayout ll = findViewById(R.id.container);
String[] splitText = BOOK_TEXT.split("\\.");
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
for(int i=0; i < splitText.length; i++) {
TextView content = new TextView(this);
if(i == 0) { content.setText(splitText[i]);
} else { content.setText("." + splitText[i]); }
content.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(BookActivity.this, "You clicked: " + ((TextView)view).getText(), Toast.LENGTH_SHORT).show();
}
});
ll.addView(content, params);
}
}
}

Call text to speech from class separate to activity class

I am trying to create a class which can be called from any activity to speak the text from an EditText box. When I run the code I currently have, it plays the alert sound but then fails to play the Text to Speech content. What do I need to change to get the text to play too? I know the activity layout XML code is correct because the Text To Speech code works when it is directly in the activity class. I have looked around for a solution but nowhere else outlines how to do this from a thread context.
I have included my code below:
on AircraftMain.java
View.OnClickListener speakBtnOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String toSpeak = textToSpeak.getText().toString();
TextToSpeak speak = new TextToSpeak(AircraftMain.this, toSpeak);
speak.run();
}
};
TextToSpeak.java
import android.app.Activity;
import android.media.MediaPlayer;
import android.speech.tts.TextToSpeech;
import java.util.Locale;
public class TextToSpeak implements Runnable {
private Activity activity;
private static String text;
private static TextToSpeech talk;
public TextToSpeak(Activity activity, String toSpeak) {
this.activity = activity;
text = toSpeak;
}
public void run() {
talk = new TextToSpeech(activity, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR) {
talk.setLanguage(Locale.UK);
}
}
});
talk.addEarcon("Attention", "com.kieronmc.aircraftgps", R.raw.warning_beep);
talk.playEarcon("Attention", QUEUE_ADD,null);
talk.setLanguage(Locale.UK);
talk.speak(text, TextToSpeech.QUEUE_ADD, null);
}
}
Try this code, It should work:
1) Create a text to speech Initializer as follows:
public class TextToSpeechInitializer{
private Context context;
private static TextToSpeech talk;
private TextToSpeechIniListener callback;
private Locale locale;
public TextToSpeechInitializer(Context context , Locale locale , TextToSpeechIniListener l) {
this.context = context;
if(l != null) {
callback = l;
}
this.locale = locale;
initialize();
}
private void initialize() {
talk = new TextToSpeech(context, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
talk.setLanguage(locale); //TODO: Check if locale is available before setting.
callback.onSucces(talk);
}else{
callback.onFailure(talk);
Log.e("TTS","TextToSpeechInitializeError");
}
}
});
}
}
2) The above initializer class calls this interface class to notify the activity below (TTS Success or Failure) :
public interface TextToSpeechIniListener {
public void onSucces(TextToSpeech tts);
public void onFailure(TextToSpeech tts);
}
3) Activity
public class Demo7 extends AppCompatActivity implements TextToSpeechIniListener {
private Button b;
private TextToSpeechInitializer i;
private TextToSpeech talk;
private boolean flag = false;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo7);
i = new TextToSpeechInitializer(this, Locale.UK, this);
b = (Button) findViewById(R.id.b);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(flag) {
talk.addEarcon("Attention", getPackageName(), R.raw.androidcalm);
talk.playEarcon("Attention", QUEUE_ADD, null);
//talk.setLanguage(Locale.UK);
talk.speak("Hello, Testing", QUEUE_ADD, null);
}
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
if(talk != null){
talk.stop();
talk.shutdown();
}
}
#Override
public void onSucces(TextToSpeech tts) {
this.talk = tts;
flag = true;
}
#Override
public void onFailure(TextToSpeech tts) {
flag = false;
finish();
}
}
layout demo7.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/b"
android:text="speak"/>
</LinearLayout>

SurfaceView doesn't display camera

I am trying to display a camera on in my android app, but all I am getting is a black box where the SurfaceView is located.
I am using this simple XML layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.lazylayer.photoshoot.MainActivity">
<SurfaceView
android:id="#+id/surface_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
With this Activity:
public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback {
SurfaceView surfaceView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
surfaceView = (SurfaceView)findViewById(R.id.surface_view);
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
try{
CameraManager cameraManager = (CameraManager)getSystemService(Context.CAMERA_SERVICE);
String[] cameras = cameraManager.getCameraIdList();
cameraManager.openCamera(cameras[0], deviceCallback, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {}
CameraDevice.StateCallback deviceCallback = new CameraDevice.StateCallback() {
#Override
public void onOpened(CameraDevice camera) {
try {
List<Surface> surfaceList = Collections.singletonList(surfaceView.getHolder().getSurface());
camera.createCaptureSession(surfaceList, sessionCallback, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
#Override
public void onDisconnected(CameraDevice camera) {}
#Override
public void onError(CameraDevice camera, int error) {}
};
CameraCaptureSession.StateCallback sessionCallback = new CameraCaptureSession.StateCallback() {
#Override
public void onConfigured(CameraCaptureSession session) {
}
#Override
public void onConfigureFailed(CameraCaptureSession session) {}
};
}
Here is what gets displayed when the app is ran on my phone:
I was able to fix the issue by using a FrameLayout instead of a SurfaceView
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/camera_view">
</FrameLayout>

Ads is not visible. Not refreshing add. Scheduling ad refresh 60000 miliseconds from now

Hi i integrated an admob banner in my game via xml but it not showing in the bottom of my screen the layout of banner already appear in graphical layout ..
Also when i check my logCat i saw this message "Ad is not visible. Not refreshing ad."
I used this code on my name combiner website.
this is my code java
public class FlyingPanda extends Activity{
/** Called when the activity is first created. */
public static FlyingPanda app;
public static CCGLSurfaceView mGLSurfaceView;
private boolean isCreated = false;
private static final String AD_INTERSTITIAL_UNIT_ID = "df2cce209f194168";
/** The interstitial ad. */
private InterstitialAd interstitialAd;
private AdView adView = null;
#Override
public void onCreate(Bundle savedInstanceState) {
if( !isCreated ){
isCreated = true;
} else {
return;
}
app = this;
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
//my code
setContentView(R.layout.adview);
//my code
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
//my code
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
//my code
RelativeLayout layout = new RelativeLayout(this);
layout.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
mGLSurfaceView = new CCGLSurfaceView(this);
layout.addView(mGLSurfaceView);
setContentView(layout);
// Create an ad request. Check logcat output for the hashed device ID to
// get test ads on a physical device.
//AdRequest adRequest = new AdRequest.Builder().build();
//adView.loadAd(adRequest);
//-----------------------------------------------------Interstitial Add
// Create an Interstitial ad.
interstitialAd = new InterstitialAd(this);
interstitialAd.setAdUnitId(AD_INTERSTITIAL_UNIT_ID);
// Load the interstitial ad.
AdRequest interstitialAdRequest = new AdRequest.Builder().build();
interstitialAd.loadAd(interstitialAdRequest);
/////////////////////////////////////////////////////////////////////////////
Common.game_initialize();
getScaledCoordinate();
CCDirector.sharedDirector().attachInView(mGLSurfaceView);
// attach the OpenGL view to a window
Common.sound_engine = SoundEngine.sharedEngine();
loadSound();
CCScene scene = CCScene.node();
scene.addChild(new HelloWorldLayer(), 1);
CCDirector.sharedDirector().runWithScene(scene);
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onPause() {
if (adView != null) {
adView.pause();
}
super.onPause();
MediaGlobal._shared().pauseMusic();
if(GameLayer.sharedGameLayer() != null){
GameLayer.sharedGameLayer().onPause(null);
}
CCDirector.sharedDirector().pause();
}
#Override
public void onResume() {
super.onResume();
if (adView != null) {
adView.resume();
}
MediaGlobal._shared().resumeMusic();
}
#Override
public void onDestroy() {
if (adView != null) {
adView.destroy();
}
isCreated = false;
MediaGlobal._shared().stopMusic();
Common.sound_engine.realesAllEffects();
super.onDestroy();
CCDirector.sharedDirector().end();
CCTextureCache.sharedTextureCache().removeAllTextures();
CCTextureCache.sharedTextureCache().removeAllTextures();
CCSpriteFrameCache.sharedSpriteFrameCache().removeAllSpriteFrames();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK){
exitGameDialog();
return false;
}
return super.onKeyDown(keyCode, event);
}
public void exitGameDialog() {
Builder builder = new AlertDialog.Builder(FlyingPanda.this)
.setIcon(R.drawable.icon)
.setTitle("Quitter le jeu?")
.setMessage("Est-vous sûr?")
.setNegativeButton("Non", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int whichButton) {
}
})
.setPositiveButton("Oui",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int whichButton) {
CCActionManager.sharedManager()
.removeAllActions();
CCDirector.sharedDirector().end();
finish();
}
});
builder.create().show();
}
private void loadSound() {
SoundEngine.purgeSharedEngine();
Common.sound_engine.preloadEffect(CCDirector.sharedDirector().getActivity().getApplication(), R.raw.bomb);
Common.sound_engine.preloadEffect(CCDirector.sharedDirector().getActivity().getApplication(), R.raw.bounce);
Common.sound_engine.preloadEffect(CCDirector.sharedDirector().getActivity().getApplication(), R.raw.death);
Common.sound_engine.preloadEffect(CCDirector.sharedDirector().getActivity().getApplication(), R.raw.fly);
Common.sound_engine.preloadEffect(CCDirector.sharedDirector().getActivity().getApplication(), R.raw.gamebg);
Common.sound_engine.preloadEffect(CCDirector.sharedDirector().getActivity().getApplication(), R.raw.gameover);
Common.sound_engine.preloadEffect(CCDirector.sharedDirector().getActivity().getApplication(), R.raw.jumppad);
}
private void getScaledCoordinate() {
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
Common.SCREEN_WIDTH = displayMetrics.widthPixels;
Common.SCREEN_HEIGHT = displayMetrics.heightPixels;
Common.kXForIPhone = Common.SCREEN_WIDTH / 480.0f;
Common.kYForIPhone = Common.SCREEN_HEIGHT / 320.0f;
}
// Admob Setting
////////////////////////////////////////////////////////////////////////////////
public void setHideAdView(final boolean bHide) {
runOnUiThread(new Runnable() {
public void run() {
if(bHide) {
adView.setVisibility(View.INVISIBLE);
}
else {
adView.setVisibility(View.VISIBLE);
}
}
});
}
public void showInterstitialAds()
{
runOnUiThread(new Runnable() {
public void run() {
// Load the interstitial ad.
AdRequest interstitialAdRequest = new AdRequest.Builder().build();
interstitialAd.loadAd(interstitialAdRequest);
interstitialAd.show();
}
});
}
}
and this is my xml code
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_height="match_parent"
android:paddingLeft="0dp"
android:paddingRight="0dp"
android:paddingTop="0dp"
android:paddingBottom="0dp"
tools:context="com.ideanetstudio.IncroyableAventuresAlaadin.FlayingPanda">
<com.google.android.gms.ads.AdView
android:id="#+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
ads:adSize="BANNER"
ads:adUnitId="ca-app-pub-848493934849303/736373839303">
</com.google.android.gms.ads.AdView>
add adView.pause(); in onPause() and adView.resume(); in onResume() method:
#Override
protected void onPause() {
adView.pause();
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
adView.resume();
}

Admob view is not visible until onResume

AdMob view is not visible, but clickable. If call onResume() view become visible. When I use
AdMob library all work fine, but if use google play services for AdMob I got this issue.
My code is bellow.
protected void initAdMob(){
if (mAdView == null) {
mAdView = new AdView(MainActivity.this);
mAdView.setAdUnitId(getString(R.string.admob_id));
mAdView.setAdSize(AdSize.SMART_BANNER);
mAdView.loadAd(new AdRequest.Builder().build());
mAdView.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
super.onAdClosed();
}
#Override
public void onAdFailedToLoad(int errorCode) {
super.onAdFailedToLoad(errorCode);
}
#Override
public void onAdLeftApplication() {
super.onAdLeftApplication();
}
#Override
public void onAdOpened() {
super.onAdOpened();
}
#Override
public void onAdLoaded() {
super.onAdLoaded();
}
});
}
}
private void showAdMob() {
initAdMob();
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER_HORIZONTAL;
mAdView.setLayoutParams(params);
FrameLayout fl = (FrameLayout) mainView.findViewById(R.id.adView);
if (fl != null) {
fl.removeAllViews();
fl.addView(mAdView, params);
}
}
#Override
public void onResume() {
if(mAdView != null){
mAdView.resume();
}
super.onResume();
}
view xml:
<FrameLayout
android:id="#+id/gameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<FrameLayout
android:id="#+id/adView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"/>
</RelativeLayout>
Need to use Mediation ID instead Publisher ID in AdMob

Categories