show ads that require activity context in service - java

I want to show ads in a service. google admob works well because it needs context, but some other ad services like unity ads, adcolony, appodeal need activity context.
How can I provide activity context in a service. I think create an Activity will works but ads need some time to load the ad and then show so create a blank activity and show it.
For unity:
UnityAds.initialize(this, "xxxxxxx", new IUnityAdsListener() {
#Override
public void onUnityAdsReady(String s) {
Timber.e("onUnityAdsReady");
}
#Override
public void onUnityAdsStart(String s) {
Timber.e("onUnityAdsStart");
}
#Override
public void onUnityAdsFinish(String s, UnityAds.FinishState finishState) {
Timber.e("onUnityAdsFinish");
}
#Override
public void onUnityAdsError(UnityAds.UnityAdsError unityAdsError, String s) {
Timber.e("onUnityAdsError");
}
});
For adclony:
AdColony.configure(this, "xxxx", "xxx");
adColonyInterstitialListener = new AdColonyInterstitialListener() {
#Override
public void onRequestFilled(AdColonyInterstitial ad) {
adColonyInterstitial = ad;
/** Store and use this ad object to show your ad when appropriate */
}
};
AdColony.requestInterstitial("xxx", adColonyInterstitialListener);
I want to show these ads from service how can I do it while they need activity context.

Related

Class A function calls a function in Class B , Once it's completed how to get notification to Class A (Android Java)

Here is the thing that I need to do.
When the user click on a button on an activity , the app must call a function in different class and sent back a notification to the activity. Then the activity shows those information in the main screen.
(Let's say the function is to receive firebase data and add it to a sqlite database. Once the data retrieval is complete ,I want to populate those information in the activity )
Is there any way to do this without using Room database
Currently I am writing the method in the activity class and redirect from there to populate data. Here is a example how I currently use it
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("server/saving-data/fireblog/posts");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int counter = dataSnapshot.size();
for(int i =0; i<counter;i++){
Post post = dataSnapshot.getValue(Post.class);
// Add to sqlite data
if(i=counter) {
// Populate Data in activity
}
}
}
The Thing i want to do it ,I want to take this function code to a sepeate class and run from the activity and get a callback.
I am a newbie and don't have a idea how to do this. Thank you
I found a solution myself.
first you need to create interface , as an example let's take this >
public interface ActionListenerCallback {
public void onActionSuccess(String successMessage);
public void onActionFailure(Throwable throwableError);
}
After that you need to implement this in the activity where you called the function
public class Act_Reps extends AppCompatActivity implements ActionListenerCallback {
#Override
protected void onCreate(Bundle savedInstanceState) {
RealtimeDB RDB= new RealtimeDB(this,Id);
RDB.setCallback(this);
RDB.callingFunction();
}
#Override
public void onActionSuccess(String successMessage) {
Log.d("Log", "Message "+ successMessage);
}
#Override
public void onActionFailure(Throwable throwableError) {
}
}
Here is the class where the function is called
public class RealtimeDB {
ActionListenerCallback callback;
public void setCallback(ActionListenerCallback callback) {
this.callback = callback;
}
public void callingFunction(){
handler.postDelayed(new Runnable() {
#Override
public void run() {
callback.onActionSuccess("Done");
}
}, 5000);
}
}

Scan for iBeacon upon receiving remote notification

I currently have an app setup to receive remote notifications using Azure Notification Hub.
Now, I would like to scan for iBeacons, see if a specific one is close by and if so, the notification should not be shown to the user. However, if the beacon isn't in sight, the user should receive this notification.
Basically I want the beacon to supress the notifications for this app.
How would one go about doing this?
Based on the docs from Azure, when a remote notification comes in, you get a callback like this:
public class MyHandler extends NotificationsHandler {
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
Context ctx;
#Override
public void onReceive(Context context, Bundle bundle) {
ctx = context;
String nhMessage = bundle.getString("message");
sendNotification(nhMessage);
if (MainActivity.isVisible) {
MainActivity.mainActivity.ToastNotify(nhMessage);
}
}
private void sendNotification(String msg) {
// put your notification code here
...
}
}
If you want to filter the notifications based on what beacons are present, you can add that logic to the onReceive method like this:
public void onReceive(Context context, Bundle bundle) {
if (!(MyApplication)this.getApplication()).isBeaconVisible()) {
// Suppress notification by returning early from method
return;
}
...
}
The above isBeaconVisible() could be implemented in a custom Android Application class using the Android Beacon Library with something like below. You'll need to read more about how to set up that library to make this work. You'll also need to register the custom Application class in your AndroidManifest.xml.
public class MyApplication extends Application implements BeaconConsumer, RangeNotifier {
public Collection<Beacon> mVisibleBeacons;
public void onCreate() {
super.onCreate();
BeaconManager beaconManager = BeaconManager.getInstanceForApplication(this);
// TODO: look up the proper I_BEACON_LAYOUT in a google search
beaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout(I_BEACON_LAYOUT));
beaconManager.addRangeNotifier(this);
}
#Override
public void onBeaconServiceConnect() {
BeaconManager beaconManager = BeaconManager.getInstanceForApplication(this);
try {
beaconManager.startRangingBeaconsInRegion(new Region("all-beacons", null, null, null));
} catch (RemoteException e) {
e.printStackTrace();
}
}
#Override
public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
mVisibleBeacons = beacons;
}
public boolean isBeaconVisible() {
return mVisibleBeacons.size() > 0;
}
}
The above logic for isBeaconVisible() returns true if any beacon with any identifier has been seen in the last second. But you can alter this to make it more sophisticated per your requirements.
You can use some opensource library to work with beacons. I used Altbeacon library for example.
Here is the samples : https://altbeacon.github.io/android-beacon-library/samples.html
For your target you need to implement BeaconConsumer interface on Activity or Service. It has a method onBeaconServiceConnect(). Example of implementation:
#Override
public void onBeaconServiceConnect() {
beaconManager.addRangeNotifier(new RangeNotifier() {
#Override
public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
if (beacons.size() == 0) {
Log.i(TAG, "Show your notification here");
}
}
});
try {
beaconManager.startRangingBeaconsInRegion(new Region("someRangingUniqueId", null, null, null));
} catch (RemoteException e) { }
}

Native Android UI for using Within LibGdx

Hi there StackOverflow!
I had been loocking on a way to Use the native Android Dialogs and Confimation Boxes in Libgdx...
All that i did by now was a Title and an Image under it:
Dialog yourmsgbox = new Dialog("Title", jsons);
yourmsgbox.setBounds(0f,0f,100f,200f);
yourmsgbox.add(choiceImg);
mainClass.addActor(yourmsgbox);
I suck a little at this but all the codes that i find in Google to do that are Or for Desktop or very especific for that Type of game + Even after some tries to copy the code and adapt it to my .java Files im still getting errors....
So if you guys could guide through a step by step ((Or a list Number of online items that i could follow to get this done I WOULD BE VERYY GRATEFULL !!!))
[[My Json file is EXTREMELY BUGGY, so if I could not have to mess with that Stubborn uiskin.json, I would Thank you :]]
Sorry my bad english
Please i'd apreciate a little help!?
UPDATE:: Sorry i have
two MainClasses for this project and i pick the wrong Logcat :)
I just use showMessage(); in the beggining of the create(), it
crashes when i get into the app. Here is what i did:
I Created an Inferface in core Project:
public interface NativeDialogInterface {
void showMessage(final String title, final String message, final String okButtonText);
}
Created AndroidNativeDialog in -android Project folder:
public class AndroidNativeDialog implements NativeDialogInterface {
private Activity activity;
public void initialize(Activity activity) {
this.activity = activity;
}
#Override
public void showMessage(final String title, final String message, final String okButtonText) {
this.activity.runOnUiThread(new Runnable() {
#Override
public void run() {
final AlertDialog alertDialog = new AlertDialog.Builder(activity).create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setButton(okButtonText, new DialogInterface.OnClickListener() {
#Override
public void onClick(final DialogInterface arg0, final int arg1) {
alertDialog.cancel();
}
});
alertDialog.show();
}
});
}
}
*Strange that it says as warning "Method setButton(...) is deprecated"
Then i added new (dialogInterface) in the AndroidLaucher.java:
public class AndroidLauncher extends AndroidApplication {
private AndroidNativeDialog dialogInteface;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
dialogInterface = new AndroidNativeDialog();
initialize(new IndexMain(dialogInteface), config);
}
}
Then in the MainClass what i did was:
btnWindow.addListener(new ClickListener(){
#Override
public void clicked(InputEvent event, float x, float y) {
mainScreen.addActor(andWindow);
dialogInteface.showMessage("TITLE", "ThE MeSsaGe", "Okayy");
Timer.schedule(new Timer.Task() {
#Override
public void run() {
andWindow.setBounds(Gdx.graphics.getWidth(), 0f, 1f, 1f);
}
}, 17);
}
});
I head to that link that "Fuat Coçkun" provided and i learn a lot about these type of structures but it seems i still have something wrongg
Its WORKS perfectly until i click that /\ Button, the button is ok if i delete the showMessage(...);
new LogCat: http://pastebin.com/NbgnyrAJ
Sorry for my bad english.
I can give you example usage of native android AlertDialog with libgdx. Firstly you need an interface in your core Project as follows :
public interface NativeDialogInterface {
void showMessage(final String title, final String message, final String okButtonText);
}
You need different implementations for each of platform you support in your project. Android project implementation will use Dialog, AlertDialog or whatever you want to use as native android component. This example shows AlertDialog implementation:
public class AndroidNativeDialog implements NativeDialogInterface {
private Activity activity;
public void initialize(Activity activity) {
this.activity = activity;
}
#Override
public void showMessage(final String title, final String message, final String okButtonText) {
this.activity.runOnUiThread(new Runnable() {
#Override
public void run() {
final AlertDialog alertDialog = new AlertDialog.Builder(activity).create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setButton(okButtonText, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
alertDialog.cancel();
}
});
alertDialog.show();
}
});
}
}
You need to call "initialize" method of your instance in your activity(onCreate is proper.) for setting activity field.
You can use any dummy implementation for the Desktop module of your libgdx project. Following implementation only logs the data you passed.
public class DesktopNativeDialog implements NativeDialogInterface {
#Override
public void showMessage(final String title, final String message, final String okButtonText) {
System.out.println("Title : " + title);
System.out.println("Message : " + message);
System.out.println("OkButtonText : " + okButtonText);
}
}
That's all. You should have a field typed NativeDialogInterface in your Core module and call "showMessage" method with your parameter. You will see a console log if you run your application on desktop. You will see native Android alert dialog on your glSurfaceView when you run your application on device/emulator.
I did this and created an expansion for libGDX. You can use it or check the source: https://github.com/TomGrill/gdx-dialogs

Ad Colony ads run just one time

Problem : Whenever I run application on a new mobile, my ad loads and runs perfectly where I want it to run. But after that on same mobile ad video doesn't play, even after I un-install my application and install again.
I don't want to show ads on my main activity, but I want to load ads in that activity. That's why I have added this in my main activity class
implements AdColonyAdListener, AdColonyAdAvailabilityListener
and override its methods like this.
#Override
public void onAdColonyAdAvailabilityChange(boolean isAvailable, String arg1) {
AdColonyHelper.isAdvAvailable = isAvailable;
}
#Override
public void onAdColonyAdAttemptFinished(AdColonyAd arg0) {
}
#Override
public void onAdColonyAdStarted(AdColonyAd arg0) {
}
To track the availability of ad I have a static boolean variable in my AdColonyHelper class. AdColony Helper class:
package Helpers;
import android.app.Activity;
import com.jirbo.adcolony.AdColonyAdListener;
import com.jirbo.adcolony.AdColonyVideoAd;
public class AdColonyHelper {
public static boolean isAdvAvailable = false;
public static String APP_ID;
public static String ZONE_ID;
static Activity act = new Activity();
public static void setting(String appid, String zoneId, Activity myAct)
{
APP_ID = appid;
ZONE_ID = zoneId;
act = myAct;
}
public static void showAdv(boolean isAvailable)
{
isAdvAvailable = isAvailable;
if(isAdvAvailable)
{
AdColonyVideoAd ad = new AdColonyVideoAd(ZONE_ID);//.withListener( (AdColonyAdListener) act );
ad.show();
}
}
public static void showAdv()
{
if(isAdvAvailable)
{
AdColonyVideoAd ad = new AdColonyVideoAd(ZONE_ID).withListener( (AdColonyAdListener) act );
ad.show();
}
}
}
in on create of my main activity I initialize it like this
AdColony.configure( this, "version:1.0,store:google", APP_ID, ZONE_ID );
AdColony.addAdAvailabilityListener(this);
if ( !AdColony.isTablet() )
{
setRequestedOrientation( ActivityInfo.SCREEN_ORIENTATION_PORTRAIT );
}
// below line is to set static variables in class
AdColonyHelper.setting(APP_ID, ZONE_ID, this);
This is all what I have done for ads in my main activity. Now right after going to my second Activity. I have this in on create method of that activity.
AdColonyHelper.showAdv();
This checks the availability of ad and plays it. But it plays ad just only one time.
But I continuously see this in my logcat
01-08 14:12:15.579: I/AdColony(23623): Finished downloading:
01-08 14:12:15.609: I/AdColony(23623): https://androidads21.adcolony.com/configure?......

Global Facebook login session accessible for all activities

Hello everyone!
Im currently developing an Android Application for mobiles using the official Facebook SDK. The first screen on my application is the LoginActivity. That activity is bringing up an Facebook login dialog, were the user can enter his facebook username and password and then press the login button. I think you know which dialog im talking about, i bet you have seen it somewhere.
When the user are logging to Facebook using that dialog, theres a Facebook session which are set to true, exactly as it should be. BUT, I found out that this session is only true if you are in the LoginActivity. If the user makes an successfull login to Facebook the user are moved to another Activity by this code:
private class LoginDialogListener implements DialogListener {
#Override
public void onComplete(Bundle values) {
Intent intent = new Intent().setClass(LoginActivity.this, LocationActivity.class);
startActivity(intent);
}
And when the user are moved to the new activity in this case LocationActivity,
the session is still true but only for the LoginActivity. I want the session to be global and be true for the whole application and all activities as soon as the user are logging in.
Here is some code from LoginActivity, i hope this will make your guys to understand it all better, i bet if i post the whole activity no one would read it.
public class LoginActivity extends Activity {
public static final String APP_ID = "123123123123123";
public static final String TAG = "FACEBOOK CONNECT";
private Facebook mFacebook;
private AsyncFacebookRunner mAsyncRunner;
private static final String[] PERMS = new String[] { "user_events" };
private Handler mHandler = new Handler();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mFacebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(mFacebook);
}
...
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
switch (itemId) {
case FacebookCon.LOGIN:
if (mFacebook.isSessionValid()) {
AsyncFacebookRunner asyncRunner = new AsyncFacebookRunner(
mFacebook);
asyncRunner.logout(this, new LogoutRequestListener());
} else {
mFacebook.authorize(this, PERMS, new LoginDialogListener());
}
break;
...
private class LogoutRequestListener implements RequestListener {
#Override
public void onComplete(String response, Object state) {
// Dispatch on its own thread
mHandler.post(new Runnable() {
public void run() {
}
});
}
A friend told me that i should make a "ApplicationController", i did not really understand what that were but he said that class should extend the whole application and all the variabels in the ApplicationController would be global for the whole application, and that's what i would like to do with the loginsession so it won't get lose when changing activities. But i don't know how to make this changes in my Application so i would like to have some help with this.

Categories