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.
Related
I am trying to create a dialog inside a fragment.when I am trying to press on the button and enter the dialog the app collaspe.
I guess the code is not right can you please help me with that?
Here is my code:
private void openDialog(){
Dialog dialog=new Dialog(getContext());
//AlertDialog.Builder builder=new AlertDialog.Builder(getContext());
LayoutInflater layoutInflater=this.getLayoutInflater();
View custom_dialog=getActivity().getLayoutInflater().inflate(R.layout.geo_dialog,null);
dialog.setContentView(custom_dialog);
// add_geofence_radius= custom_dialog.findViewById(R.id.radius_size);
save_btn=custom_dialog.findViewById(R.id.save_btn);
cancel_btn=custom_dialog.findViewById(R.id.cancel_btn);
/* save_btn.setOnClickListener(new View.OnClickListener() {
#Override
}
});
*/
/*cancel_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.cancel();
}
});
*/
// dialog.setTitle("hello");
dialog.show();
}
The best way to show dialog in android is to use "DialogFragments" since they are aware of the lifecycle of the view it is attached on (ie. fragments/activities).
Here is an examples provided in Android docs:
public class PurchaseConfirmationDialogFragment extends DialogFragment {
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
return new AlertDialog.Builder(requireContext())
.setMessage(getString(R.string.order_confirmation))
.setPositiveButton(getString(R.string.ok), (dialog, which) -> {} )
.create();
}
public static String TAG = "PurchaseConfirmationDialog";
}
To show the dialog use:
new PurchaseConfirmationDialogFragment().show(
getChildFragmentManager(), PurchaseConfirmationDialog.TAG);
For more reference on dialogFragments, checkout : Create a DialogFragment
I'm trying to implement ViewModel in a app which get some data from Firestore using the FirestorepagingAdapter, and displays it in a recyclerview. I'm already getting all data and displayig it, but still not using ViewModel, it's all on the MainActivity
I'm trying to move the code that creates Firestorepagingoptions to the the view model, and in my MainActivity, just create the adapter and set to the recyclerview. But the FirestorePagingOptions.Builder needs to set a LifecycleOwner and I don't know how to get it in my ViewModel, or maybe i should't be doing it on the ViewModel at all, I'm pretty lost yet with these ViewModel, so if anyone has any suggestion I appreciate. Thanks a lot.
Here's my original code on the MainActivity (not changed yet to get the data from the Viewmodel)
public class ListaEmpresasActivity extends AppCompatActivity {
private FirebaseFirestore firebaseDB;
private RecyclerView recyclerViewListaEmpresas;
private FirestorePagingAdapter adapter;
private boolean viewChanged;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista_empresas);
recyclerViewListaEmpresas = findViewById(R.id.activity_main_lista_empresas);
firebaseDB = FirebaseFirestore.getInstance();
FirestorePagingOptions<EmpresaLista> options = configuraPaginacaoInicial();
adapter = new ListaEmpresasAdapter(options);
configuraRecyclerView(adapter);
}
private FirestorePagingOptions<EmpresaLista> configuraPaginacaoInicial() {
Query query = firebaseDB.collection("Lista_Empresas").orderBy("id");
return configuraOpcoesPaginacao(query);
}
private FirestorePagingOptions<EmpresaLista> configuraOpcoesPaginacao(Query query) {
PagedList.Config config = new PagedList.Config.Builder()
.setEnablePlaceholders(false)
.setPrefetchDistance(10)
.setPageSize(20)
.build();
return new FirestorePagingOptions.Builder<EmpresaLista>()
.setLifecycleOwner(this)
.setQuery(query, config, EmpresaLista.class)
.build();
}
private void configuraRecyclerView(FirestorePagingAdapter adapter) {
recyclerViewListaEmpresas.setHasFixedSize(true);
recyclerViewListaEmpresas.setLayoutManager(new LinearLayoutManager(this));
recyclerViewListaEmpresas.setAdapter(this.adapter);
}
And the code on my ViewModel
public class ListaEmpresasViewModel extends ViewModel {
private MutableLiveData<FirestorePagingOptions<EmpresaLista>> options;
private FirebaseFirestore firebaseDB;
public LiveData<FirestorePagingOptions<EmpresaLista>> getOptions() {
firebaseDB = FirebaseFirestore.getInstance();
options = configuraPaginacaoInicial();
return options;
}
private MutableLiveData<FirestorePagingOptions<EmpresaLista>> configuraPaginacaoInicial() {
Query query = firebaseDB.collection("Lista_Empresas").orderBy("id");
return configuraOpcoesPaginacao(query);
}
private MutableLiveData<FirestorePagingOptions<EmpresaLista>> configuraOpcoesPaginacao(Query query) {
PagedList.Config config = new PagedList.Config.Builder()
.setEnablePlaceholders(false)
.setPrefetchDistance(10)
.setPageSize(20)
.build();
return new FirestorePagingOptions.Builder<EmpresaLista>()
.setLifecycleOwner()
.setQuery(query, config, EmpresaLista.class)
.build();
}
}
Instead of setting the lifecycle owner in the options start and stop listening manually.
Start/stop listening
The FirestorePagingAdapter listens for scrolling events and loads additional pages from the database only when needed.
To begin populating data, call the startListening() method. You may want to call this in your onStart() method. Make sure you have finished any authentication necessary to read the data before calling startListening() or your query will fail.
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
Similarly, the stopListening() call freezes the data in the RecyclerView and prevents any future loading of data pages.
Call this method when the containing Activity or Fragment stops:
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
I have a daily alarm and a settings page that allow users to change the timing that the daily alarm fires. I have a OnSharedPreferenceChangeListener in my SettingsFragment that extends PreferenceFragmentCompat and it is working here. However, when I do the same thing in my MainActivity, it does not seem to be working.
This is my code in Main Activity:
'''
public class MainActivity extends AppCompatActivity {
//some other variables
private SharedPreferences.OnSharedPreferenceChangeListener preferenceChangeListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//some other code
preferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals("daily alarm time")){
int alarmTime = sharedPreferences.getInt("daily alarm time", 36000000);
setdailyalarm(alarmTime, true, false);
System.out.println("onsharedpreferencechange activited");
}
if (key.equals("daily alarm toggle")){
Boolean dailyAlarmToggle = sharedPreferences.getBoolean(key, true);
System.out.println("111111111111111111111111");
if (dailyAlarmToggle){
int alarmTime = sharedPreferences.getInt(key, 36000000);
setdailyalarm(alarmTime, true, false);
}
else{
int alarmTime = sharedPreferences.getInt(key, 36000000);
setdailyalarm(alarmTime, true, true);
}
}
}
};
}
'''
This is my onpause and onresume:
'''
#Override
protected void onPause() {
super.onPause();
PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(preferenceChangeListener);
}
#Override
protected void onResume() {
super.onResume();
PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(preferenceChangeListener);
}
'''
When I start my app and check my System.out, '''System.out.println("onsharedpreferencechange activited");''' does not seem to be firing which means my OnSharedPreferenceChangeListener is not working. I have seem the other discussions SharedPreferences.onSharedPreferenceChangeListener not being called consistently but it does not seem to be the solution to my problem.
When I start my app and check my System.out, '''System.out.println("onsharedpreferencechange activited");''' does not seem to be firing which means my OnSharedPreferenceChangeListener is not working.
It's because you're always unregistering the listener in your onPause(). So, whenever you leave the activity, the listener is removed and you can't listen for the SharedPreferences changes.
You could register the listener inside your onCreate() method.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// setup the listener
preferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
...
// then register it
PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(preferenceChangeListener);
}
Then unregister the listener when you close the activity by overriding the onDestroy() method:
#Override
public void onDestroy() {
PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(preferenceChangeListener);
super.onDestroy();
}
Or unregister the listener whenever you call finish() method. Either call the unregister part before finish() or overriding the finish() method.
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.
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.