Hello I am a new developer and I have created my first app on Android Studios.
I used test ads made by Admob to test if my ads worked and they did. When I finally published my app with MY ad unit code for some reason it didn't work. I then checked online and found that it may take some time before they activate, so I waited and waited, until 3 days past and still it didn't work.
Here are the steps I took:
Follow the tutorial made by Admob to implement code for rewarded ads
Add network permissions
Linked my published app to Admob
Made an ad unit on Admob by clicking "ADD AD UNIT"
I was wondering whether or not I missed a step but if I did why would the test ads work but not the real ones.
I would have liked to contact Admob directly but they don't seem to have any customer service email. YOU ARE MY LAST HOPE PLEASE HELP. thank you
Code: MainActivity Class
public class MainActivity extends Activity implements RewardedVideoAdListener {
public static RewardedVideoAd mAd;
public static RewardedVideoAd mAd2;
public static MediaPlayer click;
public static MediaPlayer unlock;
public static MediaPlayer thud;
public static InterstitialAd mInterstitialAd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
this.requestWindowFeature(getWindow().FEATURE_NO_TITLE);
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
Constants.SCREEN_WIDTH = dm.widthPixels;
Constants.SCREEN_HEIGHT = dm.heightPixels;
setContentView(new GamePanel(this));
mAd = MobileAds.getRewardedVideoAdInstance(this);
mAd.setRewardedVideoAdListener(this);
mAd2 = MobileAds.getRewardedVideoAdInstance(this);
mAd2.setRewardedVideoAdListener(this);
loadAd();
click = MediaPlayer.create(getApplicationContext(), R.raw.click_sound);
unlock = MediaPlayer.create(getApplicationContext(), R.raw.unlock_sound);
thud = MediaPlayer.create(getApplicationContext(), R.raw.thud_sound);
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
mInterstitialAd.loadAd(new AdRequest.Builder().build());
}
private void click() {
click.start();
}
private void unlock() {
unlock.start();
}
private void thud() {
thud.start();
}
private void loadAd() {
if (!mAd.isLoaded()) {
mAd.loadAd("ca-app-pub-3940256099942544/5224354917", new AdRequest.Builder().build());
}
if (!mAd2.isLoaded()) {
mAd2.loadAd("ca-app-pub-3940256099942544/5224354917", new AdRequest.Builder().build());
}
}
// Required to reward the user.
#Override
public void onRewarded(RewardItem reward) {
if (GamePanel.Ad1 == 1) {
Toast.makeText(this, "Congrats 30 Survival Points Added!", Toast.LENGTH_SHORT).show();
}
if (GamePanel.Ad2 == 1) {
Toast.makeText(this, "Congrats 100 Survival Points Added!", Toast.LENGTH_SHORT).show();
}
}
// The following listener methods are optional.
#Override
public void onRewardedVideoAdLeftApplication() {
}
#Override
public void onRewardedVideoAdClosed() {
if (GamePanel.Ad1 == 1) {
GamePanel.HighCoin = GamePanel.HighCoin + 30;
GamePanel.Ad1 = 0;
Toast.makeText(this, "Congrats 30 Survival Points Added!", Toast.LENGTH_SHORT).show();
}
if (GamePanel.Ad2 == 1) {
GamePanel.HighCoin = GamePanel.HighCoin + 100;
Toast.makeText(this, "Congrats 100 Survival Points Added!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onRewardedVideoAdFailedToLoad(int errorCode) {
}
#Override
public void onRewardedVideoAdLoaded() {
}
#Override
public void onRewardedVideoAdOpened() {
}
#Override
public void onRewardedVideoStarted() {
}
}
And to load the code i used:
MainActivity.mInterstitialAd.show();
if (MainActivity.mAd.isLoaded())
MainActivity.mAd.show();
The ad unit code shown above is the test ad code given by Admob, which does work but I'm having trouble with the codes I make on Admob myself.
Thanks for the help, But i figured it out.
i forgot to put in my billing info on admob.
Related
I am trying to make a feature as part of my android app, where a user interacts with a geofence based on their location on a map and it will fire up a dialog telling the user they are near the starting point of the route using a BroadcastReceiver in its own class.
So far I can trigger it and provide Toast messages, but I can't seem to use it to trigger a UI change in my other activity.
Here is my BroadcastReceiver class -
public class GeofenceBroadcastReceiver extends BroadcastReceiver {
private static final Object TAG = "Error";
#Override
public void onReceive(Context context, Intent intent) {
GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
if (geofencingEvent.hasError()) {
Log.d("TOASTY", "onReceive: Geofence even has error..");
}
List<Geofence> triggeredGeofenceList = geofencingEvent.getTriggeringGeofences();
for (Geofence geofence : triggeredGeofenceList) {
Log.d("GEOF", "onReceive: "+geofence.getRequestId());
}
Location triggerLocation = geofencingEvent.getTriggeringLocation();
double lat = triggerLocation.getLatitude();
double lon = triggerLocation.getLongitude();
Toast.makeText(context, "GEOFENCE TRIGGERED AT : LAT IS :" + lat + " LON IS : " +lon, Toast.LENGTH_SHORT).show();
int transitionType = geofencingEvent.getGeofenceTransition();
switch (transitionType) {
case Geofence.GEOFENCE_TRANSITION_ENTER:
Toast.makeText(context, "Entered Geofence", Toast.LENGTH_SHORT).show();
Log.d("GEOF", "onReceive: "+geofencingEvent.getGeofenceTransition());
break;
case Geofence.GEOFENCE_TRANSITION_DWELL:
Toast.makeText(context, "Dwelling inside of Geofence", Toast.LENGTH_SHORT).show();
break;
case Geofence.GEOFENCE_TRANSITION_EXIT:
Toast.makeText(context, "Exited Geofence area", Toast.LENGTH_SHORT).show();
break;
}
Bundle b = intent.getExtras();
Intent i = new Intent(context, routeActivity.class);
i.putExtra("lat", lat);
i.putExtra("lon", lon);
i.putExtras(b);
Log.d("LOLCALLY", "onReceive: "+i);
context.sendBroadcast(i);
}
}
My thinking was to use intent, I have tried to pull the triggered location (which I can see is correct in the log output) into my other activity but no joy.
Many thanks!
You need to register your receiver on your activity and process its callback:
public class MyActivity extends AppCompatActivity {
private BroadcastReceiver geofenceReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Pull triggered location and use it to update the activity
}
};
#Override
protected void onResume() {
super.onResume();
registerReceiver(geofenceReceiver, new IntentFilter("YOUR_GEOFENCE_ACTION"));
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(geofenceReceiver);
}
}
I'm developing an app which counts number of times the app goes to the background. It also retains the values when the orientation is changed. Though I have it working of all use cases, I have one use case which does not work.
Case : When I press the home button, change the phone's orientation and reopen the app, It does open in landscape mode but, the background count does not increase.
I have tried setting values in all the life cycle methods. It doesn't work. Hope somebody can help me with this.
`
public class MainActivity extends AppCompatActivity {
private int clickCount =0, backgroundCount = 0;
TextView tvClickCountValue, tvBackgroundCountValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if( savedInstanceState != null){
clickCount = savedInstanceState.getInt("COUNT");
backgroundCount = savedInstanceState.getInt("BGCOUNT");
}
setContentView(R.layout.activity_main);
tvClickCountValue = (TextView) this.findViewById(R.id.tvClickCountValue);
tvBackgroundCountValue = (TextView) this.findViewById(R.id.tvBackgroundCountValue);
setView(MainActivity.this);
}
public void onClick(View v){
clickCount += 1;
tvClickCountValue.setText(Integer.toString(clickCount));
}
public void setView(Context ctx){
tvClickCountValue.setText(Integer.toString(clickCount));
tvBackgroundCountValue.setText(Integer.toString(backgroundCount));
}
#Override
protected void onStop() {
super.onStop();
backgroundCount += 1;
}
#Override
protected void onResume() {
super.onResume();
tvClickCountValue.setText(Integer.toString(clickCount));
tvBackgroundCountValue.setText(Integer.toString(backgroundCount));
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("COUNT", clickCount);
outState.putInt("BGCOUNT", backgroundCount);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
clickCount = savedInstanceState.getInt("COUNT");
backgroundCount = savedInstanceState.getInt("BGCOUNT");
}
}
This article contains useful information: https://developer.android.com/guide/topics/resources/runtime-changes.html especially in the section about Handling The Change.
Try handling it on onConfigurationChanged() of you have disabled Activity restarts on orientation changes. Otherwise, probably through this article you will find which case applies to your scenario.
By reading the problem description, I am assuming that if you don't rotate the device the application works as intended.
you need to persist the count in the SharedPreferences. each time you reopen the app read the last value from the SharedPreferences. And increment and save to SharedPreferences each time the app is hidden.
Then you can count the with #kiran code:
public class BaseActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
public static boolean isAppInFg = false;
public static boolean isScrInFg = false;
public static boolean isChangeScrFg = false;
#Override
protected void onStart() {
if (!isAppInFg) {
isAppInFg = true;
isChangeScrFg = false;
onAppStart();
}
else {
isChangeScrFg = true;
}
isScrInFg = true;
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
if (!isScrInFg || !isChangeScrFg) {
isAppInFg = false;
onAppPause();
}
isScrInFg = false;
}
public void onAppStart() {
// app in the foreground
// show the count here.
}
public void onAppPause() {
// app in the background
// start counting here.
}
}
I have a game on LibGDX. According to this
http://www.norakomi.com/tutorial_admob_part2_banner_ads1.php
instruction I created necessery methods in AndroidLauncher.java file. And in the core file, generated by AndroidLauncher.java, I have created the controller and also interface java file
( http://www.norakomi.com/tutorial_admob_part2_banner_ads2.php ).
The problem is that my game has several classes which extend one another and the corresponding condition, which I want to use for displaying adMob, is not that one to which method "initialize" gives "this" from AndroidLauncher.java file. But to download and to give request for adMob is possible only from AndroidLauncher.java, because another classes are in its own game view.
How to solve this?
This is the basic code from AndroidLauncher.java
public class AndroidLauncher extends AndroidApplication implements AdsController {
private static final String BANNER_AD_UNIT_ID = "ca-app-pub-3940256099942544/6300978111";
private static final String INTERSTITIAL_AD_UNIT_ID = "ca-app-pub-3940256099942544/1033173712";
AdView bannerAd;
InterstitialAd interstitialAd;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
// Create a gameView and a bannerAd AdView
View gameView = initializeForView(new Stork2016(this), config);
setupBanner();
setupInterstitial();
// Define the layout
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);
config.useCompass = false;
config.useAccelerometer = false;
public void setupBanner() {
bannerAd = new AdView(this);
//bannerAd.setVisibility(View.VISIBLE);
//bannerAd.setBackgroundColor(0xff000000); // black
bannerAd.setAdUnitId(BANNER_AD_UNIT_ID);
bannerAd.setAdSize(AdSize.SMART_BANNER);
}
public void setupInterstitial() {
interstitialAd = new InterstitialAd(this);
interstitialAd.setAdUnitId(INTERSTITIAL_AD_UNIT_ID);
AdRequest.Builder builder = new AdRequest.Builder();
AdRequest ad = builder.build();
interstitialAd.loadAd(ad);
#Override
public void showInterstitialAd(final Runnable then) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (then != null) {
interstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
Gdx.app.postRunnable(then);
AdRequest.Builder builder = new AdRequest.Builder();
AdRequest ad = builder.build();
interstitialAd.loadAd(ad);
}
});
}
interstitialAd.show();
}
});
}
#Override
public boolean isWifiConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
return (ni != null && ni.isConnected());
}
#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);
}
});
}
}
And then we have file Stork2016.java in which we create AdsController to be able to use methods for adds in AndroidLauncher.java.
private AdsController adsController;
public Stork2016(AdsController adsController){
this.adsController = adsController;
}
#Override
public void create () {
adsController.showBannerAd();
batch = new SpriteBatch();
gsm = new GameStateManager();
music = Gdx.audio.newMusic(Gdx.files.internal("music.mp3"));
music.setLooping(true);
music.setVolume(0.5f);
music.play();
Gdx.gl.glClearColor(1, 0, 0, 1);
gsm.push(new MenuState(gsm));
}
And also we have interface java file AdsController.java
public interface AdsController {
public void showBannerAd();
public void hideBannerAd();
public void showInterstitialAd (Runnable then);
public boolean isWifiConnected();
}
So, as we can see in Stork2016 we have "gsm.push(new MenuState(gsm));" and in MenuState.java I have "gsm.set(new PlayState(gsm));". In PlayState.java there is the part of code:
#Override
public void update(float dt) {
handleInput();
updateGround();
....
if (tube.collides(bird.getBounds()))
gsm.set(new GameOver(gsm));
...
}
}
camera.update();
}
The condition "if" frome the above code I want to use to show interstitial adMob. But it is impossibe, because the contoller which takes methods from AndroidLauncher.java can be created only in Stork2016.java. And also in AndroidLauncher.java there is
View gameView = initializeForView(new Stork2016(this), config);
wich transfers "this" to Stork2016, where is the controller.
In my AndroidLauncher activity I start the game and initialize the Insterstitial ad. Then I initialize my interface which I call from inside the game, to trigger show/hide of the interstitial ad.
For example I have method showInterstitialAd() in my interface listener, then my implementation on Android would be:
#Override
public void showCoverAd() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (interstitialAd.isLoaded()) {
interstitialAd.show();
}
}
});
}
And on iOS-MOE:
#Override
public void showCoverAd() {
if (gadInterstitial.isReady()) {
gadInterstitial.presentFromRootViewController(uiViewController);
}
}
So you need the make sure that the interface listener knows about the interstitial ad, for example AndroidLauncher implements MyGameEventListener
In my case interface AdsController.java is implemented in AndroidLauncher.java:
public class AndroidLauncher extends AndroidApplication implements AdsController { ...
And then by this part of code:
View gameView = initializeForView(new Stork2016(this), config);
we send "this" to new class Strork2016.java.
And in the class Stork2016.java I create constructor:
private AdsController adsController;
public Stork2016(AdsController adsController){
this.adsController = adsController;
}
which lets us use methods from interface AdsController.java.
But only in this class Stork2016. If I want to use it in another class:
gsm.push(new MenuState(gsm));
this is impossible and this is the problem.
OK guys, I have solved the problem.
I had to create two consturctors in both classes: the main core class which is initialyzed from AndroidLauncher and in the class GameStateManager. Because the class, where I want admob intersitital to be called, is created by method gsm.push which is described in class GameStateManager. Actually, in GameStateManager there have already been constuructor, so I hade only to add necessary code to this constructor.
I'm new to Android Studio and currently working on my first app. Thanks to numerous examples on here i have managed to catch up on the basics very quickly. I now have a problem with my autocompletetextview, i want to get the text selected then use it in a if statement to determine what is shown on the "results" textview. The if statement works fine but only for the "else" part and i can't figure out where i went wrong.
I have commented out the onItemClickListener because the "testfoodph" method does the same.
Here is the activity code:
public class phTester extends AppCompatActivity {
Intent intent = getIntent();
AutoCompleteTextView text;
MultiAutoCompleteTextView text1;
TextView results;
String foodies;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ph_tester);
String[] foods = getResources().getStringArray(R.array.foodlist);
text=(AutoCompleteTextView)findViewById(R.id.autoCompleteTextView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,foods);
text.setAdapter(adapter);
text.setThreshold(1);
results=(TextView)findViewById(R.id.phResults);
foodies = text.getText().toString();
text.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//if (foodies.equalsIgnoreCase("Mango")) {
//results.setText(getString(R.string.phAlk));
}
//else {
//results.setText(getString(R.string.Error));
//}
//}
});
}
public void TestFoodPH(View view) {
if (foodies.equalsIgnoreCase("Mango")) {
results.setText(getString(R.string.phAlk));
}
else {
results.setText(getString(R.string.Error));
}
}
following are my codes in main activity
public class MainActivity extends ActionBarActivity{
private MediaRouteButton mMediaRouteButton;
private MediaRouteSelector mMediaRouteSelector;
private MediaRouter mMediaRouter;
private CastDevice mSelectedDevice;
private MyMediaRouterCallback mMediaRouterCallback;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(this.checkGooglePlaySevices(this))
Log.v("cc5zhenhua","googleplayservice okay");
else
{
Log.v("cc5zhenhua","googleplayservice not ok");
//GooglePlayServicesUtil.getErrorDialog(0, this, 0).show();
}
//initialize media cast objects
mMediaRouter=MediaRouter.getInstance(getApplicationContext());
mMediaRouteSelector=new MediaRouteSelector.Builder()
.addControlCategory(CastMediaControlIntent.CATEGORY_CAST).build();
mMediaRouterCallback= new MyMediaRouterCallback();
mMediaRouter.addCallback(mMediaRouteSelector, mMediaRouterCallback);
}
public void onStart() {
super.onStart();
mMediaRouter.addCallback(mMediaRouteSelector, mMediaRouterCallback
);
MediaRouter.RouteInfo route = mMediaRouter.updateSelectedRoute(mMediaRouteSelector);
// do something with the route...
}
#Override
protected void onResume()
{
super.onResume();
mMediaRouter.addCallback(mMediaRouteSelector, mMediaRouterCallback);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
super.onCreateOptionsMenu(menu);
//mMediaRouteButton.setRouteSelector(mMediaRouteSelector);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.main, menu);
MenuItem mediaRouteItem = menu.findItem( R.id.action_mediaroute01 );
MediaRouteActionProvider mediaRouteActionProvider =
(MediaRouteActionProvider)MenuItemCompat.getActionProvider(
mediaRouteItem);
mediaRouteActionProvider.setRouteSelector(mMediaRouteSelector);
mMediaRouteButton = (MediaRouteButton) mediaRouteItem.getActionView();
return true;}
public boolean checkGooglePlaySevices(final Activity activity) {
final int googlePlayServicesCheck = GooglePlayServicesUtil.isGooglePlayServicesAvailable(
activity);
switch (googlePlayServicesCheck) {
case ConnectionResult.SUCCESS:
return true;
default:
Log.v("cc5zhenhua","test"); }
return false;
}
private class MyMediaRouterCallback extends MediaRouter.Callback
{
#Override
public void onRouteSelected(MediaRouter router, RouteInfo info) {
mSelectedDevice = CastDevice.getFromBundle(info.getExtras());
String routeId = info.getId();
Log.v("cc5zhenhua", "MainActivity.onRouteSelected");
}
#Override
public void onRouteUnselected(MediaRouter router, RouteInfo info) {
//teardown();
mSelectedDevice = null;
}
}
}
There's no build error. However when I run the main activity, the media route button can not be clicked at all. Please advise any where I missed? Thank you!
My chromecast is whitelisted registed with an APPID before the new SDK published.
I can't use that appID for the control category either, it throws not valida appID exception.
My cast device is also available for chromecast extension in my computer.
You need to start the scan by adding callbacks:
mMediaRouter.addCallback(mMediaRouteSelector, mMediaRouterCallback,
MediaRouter.CALLBACK_FLAG_PERFORM_ACTIVE_SCAN);
If you are already doing that and forgot to mention that in your post, then you need to register your app and device on the Developer Console. Your issue is, then, most likely due to the whitelisting of your device; try connecting to your device from a chrome browser at http://<chromecast-ip>:9222, if you can't, then your device is not whitelisted; follow the steps in this post to trouble shoot that
Finally get the issue point. Just because that my last app with old googlecast sdk works on the AVD, so I focused on my codes and new SDK setting.However, when I deploy the app on real phone ,the media route can be found. Thanks to Ali for his kindness and helping.