I'm using admob interstitial on my app. I'm able to display the interstitial only one time, but I have no idea how to request a new intertstitial. lease help me !
my code is as follow ?
using UnityEngine;
using GoogleMobileAds.Api;
public class AdsMnager : MonoBehaviour {
public static AdsMnager Instance {
get ;
set;
}
public bool InterstitialLoaded = false;
public bool InterstitialClosed = false ;
const string InterstitialAdId ="ca-app-pub-3940256099942544/1033173712";
const string BannerAdId = "ca-app-pub-3940256099942544/6300978111";
InterstitialAd interstitialAd;
AdRequest request;
private BannerView bannerView;
private void Awake()
{
if (Instance == null)
Instance = this;
else
Destroy (gameObject);
DontDestroyOnLoad (gameObject);
interstitialAd = new InterstitialAd (InterstitialAdId);
Showbanner ();
request = new AdRequest.Builder ().Build ();
interstitialAd.LoadAd (request);
}
public void RequestBanner()
{
bannerView = new BannerView (BannerAdId, AdSize.Banner, AdPosition.Bottom);
AdRequest request = new AdRequest.Builder ().Build ();
bannerView.LoadAd (request);
bannerView.Show ();
}
public void Showbanner()
{
if (bannerView == null)
RequestBanner ();
}
public void ShowInterstitial()
{
request = new AdRequest.Builder ().Build ();
interstitialAd.LoadAd (request);
if (interstitialAd.IsLoaded ()) {
InterstitialLoaded = true;
interstitialAd.Show ();
} else {
}
interstitialAd.OnAdClosed += InterstitialAd_onAdClosed;
}
private void InterstitialAd_onAdClosed (object sender , System.EventArgs e)
{
InterstitialLoaded = false;
InterstitialClosed = true;
}
}
Thanks in advance.
You can request for a new ad in the #onAdClosed() callback method. Just modify your #InterstitialAd_onAdClosed() method like so:
private void InterstitialAd_onAdClosed (object sender , System.EventArgs e)
{
InterstitialLoaded = false;
InterstitialClosed = true;
interstitialAd.LoadAd(new AdRequest.Builder().Build())
}
Related
I am using admob for ads. Ads working very well on the Editor but on the phone it doesn't. I have a button in the game that show rewarded ads then load next level. And I am showing interstitial ads at end of the level then load next level. But after loading next level game crashes. I am trying to fix it for days but it keeps happening. I am adding my ad manager script. (unit ids not empty of course)
using System.Collections;
using UnityEngine;
using GoogleMobileAds.Api;
using System;
public class AdManager : MonoBehaviour
{
public static AdManager instance;
private BannerView bannerView;
private RewardedAd rewardedAd;
private InterstitialAd interstitialAd;
#if UNITY_ANDROID
string bannerAdUnitId = " ";
string rewardedAdUnitId = " ";
string interstitialAdUnitId = " ";
#else
string bannerAdUnitId = "unexpected_platform";
string rewardedAdUnitId = "unexpected_platform";
string interstitialAdUnitId = "unexpected_platform";
#endif
void Awake()
{
if(instance != null && instance != this){
Destroy(this.gameObject);
}
else{
instance = this;
DontDestroyOnLoad(this.gameObject);
}
}
private void Start() {
MobileAds.Initialize(initStatus => { });
RequestInterstitialAd();
RequestBannerAd();
RequestRewardedAd();
}
//BANNER
public void RequestBannerAd(){
if (bannerView != null)
bannerView.Destroy();
else{
bannerView = new BannerView(bannerAdUnitId, AdSize.Banner, AdPosition.Bottom);
AdRequest request = new AdRequest.Builder().Build();
bannerView.LoadAd(request);
}
}
//REWARDED
public void RequestRewardedAd(){
if(rewardedAd != null)
rewardedAd.Destroy();
rewardedAd = new RewardedAd(rewardedAdUnitId);
// Called when an ad request failed to show.
rewardedAd.OnAdFailedToShow += HandleRewardedAdFailedToShow;
// Called when the ad is closed.
rewardedAd.OnAdClosed += HandleRewardedAdClosed;
AdRequest request = new AdRequest.Builder().Build();
rewardedAd.LoadAd(request);
}
public void ShowRewardedAd(){
if (rewardedAd.IsLoaded()) {
rewardedAd.Show();
}
else{
StartCoroutine(RewardedNotLoadedFunctionCall());
}
}
IEnumerator RewardedNotLoadedFunctionCall(){
FindObjectOfType<GameManagement>().RewardedAdNotLoaded();
yield return null;
}
public void HandleRewardedAdClosed(object sender, EventArgs args)
{
RequestRewardedAd();
StartCoroutine(AdClosedFunctionCall());
}
IEnumerator AdClosedFunctionCall(){
FindObjectOfType<GameManagement>().AdClosed();
yield return null;
}
public void HandleRewardedAdFailedToShow(object sender, AdErrorEventArgs args)
{
StartCoroutine(RewardedNotLoadedFunctionCall());
}
//interstitial
private void RequestInterstitialAd(){
if(interstitialAd != null)
interstitialAd.Destroy();
interstitialAd = new InterstitialAd(interstitialAdUnitId);
interstitialAd.OnAdClosed += HandleOnAdClosed;
AdRequest request = new AdRequest.Builder().Build();
interstitialAd.LoadAd(request);
}
public void ShowInterstitialAd(){
if (interstitialAd.IsLoaded()) {
interstitialAd.Show();
}
else{
StartCoroutine(AdClosedFunctionCall());
}
}
public void HandleOnAdClosed(object sender, EventArgs args)
{
RequestInterstitialAd();
StartCoroutine(AdClosedFunctionCall());
}
}
logcat
Admob Ad does not run on the same thread as Unity's main thread.
rewardedAd.OnAdClosed += HandleRewardedAdClosed;
Calling Unity's function from Admob's thread will lead to unexpected error.
First, add UnityMainThreadDispatcher to your project. All functions called by Admob's callback need be queued by UnityMainThreadDispatcher to main thread:
public void HandleRewardedAdClosed(object sender, EventArgs args)
{
UnityMainThreadDispatcher.Instance().Enqueue(()=>{
RequestRewardedAd();
StartCoroutine(AdClosedFunctionCall());
});
}
Secondly, you should not use FindObjectOfType(). This is an expensive operation and you might run into NullReferenceException if it fails to find the GameManagement object. And since this exception did not happen on Unity's main thread, the logcat message was cryptic.
You should use Singleton or Observer pattern instead.
Thirdly, you're giving reward to user even if they skip the reward ad. Use rewardedAd.OnUserEarnedReward to make sure user have earned the reward ad.
I implemented AppOpen to my project, it works fine.
Here's the code:
public class AppOpenManager implements LifecycleObserver, Application.ActivityLifecycleCallbacks {
private static final String LOG_TAG = "AppOpenManager";
private static String AD_UNIT_ID;
private AppOpenAd appOpenAd = null;
private static boolean isShowingAd = false;
public static boolean shouldOpenAd = true;
private AppOpenAd.AppOpenAdLoadCallback loadCallback;
private Activity currentActivity;
private long loadTime = 0;
private final UILApplication myApplication;
public AppOpenManager(UILApplication myApplication, boolean isPurchased) {
AD_UNIT_ID = AdsConstants.getAppOpenId(myApplication.getApplicationContext());
this.myApplication = myApplication;
this.myApplication.registerActivityLifecycleCallbacks(this);
ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
shouldOpenAd = !isPurchased;
}
/**
* LifecycleObserver methods
*/
#OnLifecycleEvent(ON_START)
public void onStart() {
if (shouldOpenAd)
showAdIfAvailable();
Log.d(LOG_TAG, "onStart");
}
/**
* Request an ad
*/
public void fetchAd() {
// Have unused ad, no need to fetch another.
if (isAdAvailable()) {
return;
}
loadCallback = new AppOpenAd.AppOpenAdLoadCallback() {
/**
* Called when an app open ad has loaded.
* #param ad the loaded app open ad.
*/
#Override
public void onAdLoaded(#NonNull AppOpenAd ad) {
AppOpenManager.this.appOpenAd = ad;
AppOpenManager.this.loadTime = (new Date()).getTime();
Log.d("OnAdLoaded", "Banner adapter class name: " + ad.getResponseInfo().getMediationAdapterClassName());
}
/**
* Called when an app open ad has failed to load.
* #param loadAdError the error.
*/
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
// Handle the error.
}
};
AdRequest request = getAdRequest();
AppOpenAd.load(
myApplication, AD_UNIT_ID, request,
AppOpenAd.APP_OPEN_AD_ORIENTATION_PORTRAIT, loadCallback);
}
/**
* Shows the ad if one isn't already showing.
*/
public void showAdIfAvailable() {
// Only show ad if there is not already an app open ad currently showing
// and an ad is available.
if (!isShowingAd && isAdAvailable()) {
Log.d(LOG_TAG, "Will show ad.");
FullScreenContentCallback fullScreenContentCallback =
new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
// Set the reference to null so isAdAvailable() returns false.
AppOpenManager.this.appOpenAd = null;
isShowingAd = false;
fetchAd();
}
#Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
}
#Override
public void onAdShowedFullScreenContent() {
isShowingAd = true;
}
};
appOpenAd.setFullScreenContentCallback(fullScreenContentCallback);
appOpenAd.show(currentActivity);
} else {
Log.d(LOG_TAG, "Can not show ad.");
fetchAd();
}
}
/**
* Creates and returns ad request.
*/
private AdRequest getAdRequest() {
return new AdRequest.Builder().build();
}
/**
* Utility method that checks if ad exists and can be shown.
*/
public boolean isAdAvailable() {
return appOpenAd != null && wasLoadTimeLessThanNHoursAgo(4);
}
/**
* Utility method to check if ad was loaded more than n hours ago.
*/
private boolean wasLoadTimeLessThanNHoursAgo(long numHours) {
long dateDifference = (new Date()).getTime() - this.loadTime;
long numMilliSecondsPerHour = 3600000;
return (dateDifference < (numMilliSecondsPerHour * numHours));
}
//some listeners here
}
The only problem is that I have Activity Result:
someActivityResultLauncher = fragment.registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
if (result.getResultCode() == Activity.RESULT_OK) {
Intent data = result.getData();
if (data != null) {
ArrayList<Uri> uriList = new ArrayList<>();
if (data.getClipData() != null) {
int count = data.getClipData().getItemCount();
for (int i = 0; i < count; i++) {
Uri uri = data.getClipData().getItemAt(i).getUri();
uriList.add(uri);
}
} else if (data.getData() != null) {
Uri uri = data.getData();
uriList.add(uri);
}
intentServiceSendingFileUtils.createIntentForSendingFile(fragment.requireActivity(),
uriList, info);
}
}
});
Every time I want to select pictures/documents/etc. AppOpen Ad appears.
How to prevent my app from doing this?
I want to show App Open Ad only when my app opens or user goes back.
I can set some boolean value to true/false to show or not the ad but maybe there is any better solution for this.
okay, fixed, maybe anyone needs this:
#OnLifecycleEvent(ON_START)
public void onStart() {
Log.e(LOG_TAG, "onStart isSelectingFile --> " + isSelectingFile);
if (shouldOpenAd && !isSelectingFile) {
showAdIfAvailable();
} else if (isSelectingFile)
isSelectingFile = false;
}
and
private void getContent(String type) {
AppOpenManager.isSelectingFile = true;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setType(type);
someActivityResultLauncher.launch(intent);
}
Just set the boolean before you open Gallery or File Manager and change it when you already got result what you wanted.
Im using Mlkit object detection API in my android application to detect objects in realtime. Here is my code
private AtomicBoolean flag = new AtomicBoolean(false);
private void startDetection(){
final FirebaseVisionObjectDetectorOptions options = new FirebaseVisionObjectDetectorOptions.Builder()
.setDetectorMode(FirebaseVisionObjectDetectorOptions.STREAM_MODE)
.enableClassification()
.build();
final FirebaseVisionObjectDetector objectDetector =
FirebaseVision.getInstance().getOnDeviceObjectDetector(options);
timer = new Timer();
timer.schedule(new TimerTask() {
#SuppressLint("SetTextI18n")
#Override
public void run() {
try {
if(flag.compareAndSet(false, true)) {
status.setText("Processing");
result.setText("Starting");
FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(textureView.getBitmap());
objectDetector.processImage(image)
.addOnSuccessListener(
new OnSuccessListener<List<FirebaseVisionObject>>() {
#Override
public void onSuccess(List<FirebaseVisionObject> detectedObjects) {
/*StringBuilder wew = new StringBuilder();
for (FirebaseVisionObject obj : detectedObjects) {
Integer id = obj.getTrackingId();
Rect bounds = obj.getBoundingBox();
// If classification was enabled:
int category = obj.getClassificationCategory();
Float confidence = obj.getClassificationConfidence();
wew.append(category);
}
result.setText(wew.toString());*/
result.setText(Integer.toString(detectedObjects.size()));
flag.set(false);
}
})
.addOnFailureListener(
new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
result.setText(e.getMessage());
}
});
}
} catch (NullPointerException e) {
e.printStackTrace();
result.setText(e.getMessage());
}
}
},0,2000);
}
The list of objects detection is 0 and i got this from the logcat
ObjectDetectorTask: Object detector pipeline is reset
Why is that happening?
I am making one adforest classified alike app in my android studio and
below is the splash screen activity which executes first when i click on app icon but after that next activity does not open...progress bar on splash screen keeps on rotating but it is not openning next activity !!
SplashScreen.java
public class SplashScreen extends AppCompatActivity {
Activity activity;
SettingsMain setting;
JSONObject jsonObjectSetting;
boolean isRTL = false;
public static JSONObject jsonObjectAppRating, jsonObjectAppShare;
public static boolean gmap_has_countries = false, app_show_languages = false;
public static JSONArray app_languages;
public static String languagePopupTitle, languagePopupClose, gmap_countries;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
Configuration configuration = getResources().getConfiguration();
configuration.fontScale = (float) 1; //0.85 small size, 1 normal size, 1,15 big etc
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
metrics.scaledDensity = configuration.fontScale * metrics.density;
getBaseContext().getResources().updateConfiguration(configuration, metrics);
activity = this;
setting = new SettingsMain(this);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (!prefs.getBoolean("firstTime", false)) {
setting.setUserLogin("0");
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstTime", true);
editor.apply();
}
if (getSupportActionBar() != null) {
getSupportActionBar().hide();
}
try {
PackageInfo info = getPackageManager().getPackageInfo(
"com.call4site.nearhaat",
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA1");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch (PackageManager.NameNotFoundException e)
{
e.printStackTrace();
}
if (SettingsMain.isConnectingToInternet(this)) {
adforest_getSettings(this);
} else {
AlertDialog.Builder alert = new AlertDialog.Builder(SplashScreen.this);
alert.setTitle(setting.getAlertDialogTitle("error"));
alert.setCancelable(false);
alert.setMessage(setting.getAlertDialogMessage("internetMessage"));
alert.setPositiveButton(setting.getAlertOkText(), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
SplashScreen.this.recreate();
}
});
alert.show();
}
}
public void adforest_getSettings(final Context context) {
RestService restService =
UrlController.createService(RestService.class);
Call<ResponseBody> myCall = restService.getSettings(UrlController.AddHeaders(this));
myCall.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> responseObj) {
try {
if (responseObj.isSuccessful()) {
Log.d("info settings Responce", "" + responseObj.toString());
JSONObject response = new JSONObject(responseObj.body().string());
Log.d("info settings object", "" + response.getJSONObject("data"));
if (response.getBoolean("success")) {
jsonObjectSetting = response.getJSONObject("data");
setting.setMainColor(jsonObjectSetting.getString("main_color"));
isRTL = jsonObjectSetting.getBoolean("is_rtl");
setting.setRTL(isRTL);
setting.setAlertDialogTitle("error", jsonObjectSetting.getJSONObject("internet_dialog").getString("title"));
setting.setAlertDialogMessage("internetMessage", jsonObjectSetting.getJSONObject("internet_dialog").getString("text"));
setting.setAlertOkText(jsonObjectSetting.getJSONObject("internet_dialog").getString("ok_btn"));
setting.setAlertCancelText(jsonObjectSetting.getJSONObject("internet_dialog").getString("cancel_btn"));
setting.setAlertDialogTitle("info", jsonObjectSetting.getJSONObject("alert_dialog").getString("title"));
setting.setAlertDialogMessage("confirmMessage", jsonObjectSetting.getJSONObject("alert_dialog").getString("message"));
setting.setAlertDialogMessage("waitMessage", jsonObjectSetting.getString("message"));
setting.setAlertDialogMessage("search", jsonObjectSetting.getJSONObject("search").getString("text"));
setting.setAlertDialogMessage("catId", jsonObjectSetting.getString("cat_input"));
setting.setAlertDialogMessage("location_type", jsonObjectSetting.getString("location_type"));
setting.setAlertDialogMessage("gmap_lang", jsonObjectSetting.getString("gmap_lang"));
setting.setGoogleButn(jsonObjectSetting.getJSONObject("registerBtn_show").getBoolean("google"));
setting.setfbButn(jsonObjectSetting.getJSONObject("registerBtn_show").getBoolean("facebook"));
JSONObject alertDialog = jsonObjectSetting.getJSONObject("dialog").getJSONObject("confirmation");
setting.setGenericAlertTitle(alertDialog.getString("title"));
setting.setGenericAlertMessage(alertDialog.getString("text"));
setting.setGenericAlertOkText(alertDialog.getString("btn_ok"));
setting.setGenericAlertCancelText(alertDialog.getString("btn_no"));
setting.isAppOpen(jsonObjectSetting.getBoolean("is_app_open"));
setting.checkOpen(jsonObjectSetting.getBoolean("is_app_open"));
setting.setGuestImage(jsonObjectSetting.getString("guest_image"));
JSONObject jsonObjectLocationPopup = jsonObjectSetting.getJSONObject("location_popup");
Log.d("info location_popup obj", "" + jsonObjectLocationPopup);
setting.setLocationSliderNumber(jsonObjectLocationPopup.getInt("slider_number"));
setting.setLocationSliderStep(jsonObjectLocationPopup.getInt("slider_step"));
setting.setLocationText(jsonObjectLocationPopup.getString("text"));
setting.setLocationBtnSubmit(jsonObjectLocationPopup.getString("btn_submit"));
setting.setLocationBtnClear(jsonObjectLocationPopup.getString("btn_clear"));
JSONObject jsonObjectLocationSettings = jsonObjectSetting.getJSONObject("gps_popup");
setting.setShowNearby(jsonObjectSetting.getBoolean("show_nearby"));
Log.d("info gps_popup obj", "" + jsonObjectLocationSettings);
setting.setGpsTitle(jsonObjectLocationSettings.getString("title"));
setting.setGpsText(jsonObjectLocationSettings.getString("text"));
setting.setGpsConfirm(jsonObjectLocationSettings.getString("btn_confirm"));
setting.setGpsCancel(jsonObjectLocationSettings.getString("btn_cancel"));
setting.setAdsPositionSorter(jsonObjectSetting.getBoolean("ads_position_sorter"));
setting.setBannerShow(false);
setting.setAdsPosition("");
setting.setBannerAdsId("");
setting.setInterstitalShow(false);
setting.setAdsInitialTime("");
setting.setAdsDisplayTime("");
setting.setInterstitialAdsId("");
setting.setNotificationTitle("");
setting.setNotificationMessage("");
setting.setNotificationTitle("");
if (setting.getAppOpen()) {
setting.setNoLoginMessage(jsonObjectSetting.getString("notLogin_msg"));
}
setting.setFeaturedScrollEnable(jsonObjectSetting.getBoolean("featured_scroll_enabled"));
if (setting.isFeaturedScrollEnable()) {
Log.d("info setting AutoScroll", jsonObjectSetting.getJSONObject("featured_scroll").toString());
setting.setFeaturedScroolDuration(jsonObjectSetting.getJSONObject("featured_scroll").getInt("duration"));
setting.setFeaturedScroolLoop(jsonObjectSetting.getJSONObject("featured_scroll").getInt("loop"));
}
jsonObjectAppRating = jsonObjectSetting.getJSONObject("app_rating");
jsonObjectAppShare = jsonObjectSetting.getJSONObject("app_share");
gmap_has_countries = jsonObjectSetting.getBoolean("gmap_has_countries");
if (gmap_has_countries) {
gmap_countries = jsonObjectSetting.getString("gmap_countries");
}
app_show_languages = jsonObjectSetting.getBoolean("app_show_languages");
if (app_show_languages) {
languagePopupTitle = jsonObjectSetting.getString("app_text_title");
languagePopupClose = jsonObjectSetting.getString("app_text_close");
app_languages = jsonObjectSetting.getJSONArray("app_languages");
}
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after 100ms
if (setting.getUserLogin().equals("0")) {
SplashScreen.this.finish();
if (setting.isLanguageChanged()) {
if (isRTL)
updateViews("ur");
else {
updateViews("en");
}
}
Intent intent = new Intent(SplashScreen.this, MainActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.right_enter, R.anim.left_out);
} else {
SplashScreen.this.finish();
if (setting.isLanguageChanged()) {
if (isRTL)
updateViews("ur");
else {
updateViews("en");
}
}
setting.isAppOpen(false);
Intent intent = new Intent(SplashScreen.this, HomeActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.right_enter, R.anim.left_out);
}
if (app_show_languages && !setting.isLanguageChanged()) {
if (setting.getLanguageRtl()) {
updateViews("ur");
} else {
updateViews("en");
}
}
}
}, 2000);
} else {
Toast.makeText(activity, response.get("message").toString(), Toast.LENGTH_SHORT).show();
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.d("info settings error", String.valueOf(t));
Log.d("info settings error", String.valueOf(t.getMessage() + t.getCause() + t.fillInStackTrace()));
}
});
}
#Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(LocaleHelper.onAttach(base));
}
private void updateViews(String languageCode) {
LocaleHelper.setLocale(this, languageCode);
}
}
This is UrlController java class which uses to call retrofit api:
UrlController.java
public class UrlController {
static OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(5, TimeUnit.MINUTES)
.writeTimeout(5, TimeUnit.MINUTES)
.readTimeout(5, TimeUnit.MINUTES)
.build();
private static String Purchase_code = "************************";
private static String Custom_Security = "***********************";
private static String url = "null";
private static String Base_URL = "https://yourdomain.co.in/demo/";
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
private static Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(Base_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create());
private static Retrofit retrofit = builder.build();
public static <S> S createService(Class<S> serviceClass)
{
url = retrofit.baseUrl().toString();
return retrofit.create(serviceClass);
}
public static <S> S createService(
Class<S> serviceClass, String username, String password, Context context)
{
if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(password)) {
String authToken = Credentials.basic(username, password);
return createService(serviceClass, authToken, context);
}
return createService(serviceClass, null, null, context);
}
public static <S> S createService(
Class<S> serviceClass, final String authToken, Context context)
{
if (!TextUtils.isEmpty(authToken)) {
AuthenticationInterceptor interceptor = new AuthenticationInterceptor(authToken, context);
if (!httpClient.interceptors().contains(interceptor))
{
httpClient.addInterceptor(interceptor);
builder.client(httpClient.build());
retrofit = builder.build();
}
}
return retrofit.create(serviceClass);
}
public static Map<String, String> AddHeaders(Context context) {
Map<String, String> map = new HashMap<>();
if (SettingsMain.isSocial(context)) {
map.put("AdForest-Login-Type", "social");
}
map.put("Purchase-Code", Purchase_code);
map.put("custom-security", Custom_Security);
map.put("Adforest-Request-From", "android");
map.put("Adforest-Lang-Locale", SettingsMain.getLanguageCode());
map.put("Content-Type", "application/json");
map.put("Cache-Control", "max-age=640000");
return map;
}
public static Map<String, String> UploadImageAddHeaders(Context context) {
Map<String, String> map = new HashMap<>();
if (SettingsMain.isSocial(context)) {
map.put("AdForest-Login-Type", "social");
}
map.put("Purchase-Code", Purchase_code);
map.put("custom-security", Custom_Security);
map.put("Adforest-Lang-Locale", SettingsMain.getLanguageCode());
map.put("Adforest-Request-From", "android");
map.put("Cache-Control", "max-age=640000");
return map;
}
}
when it executes:
myCall.enqueue(new Callback()
{
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> responseObj)
{
//some code here
} );
#Override
public void onFailure(Call<ResponseBody> call, Throwable t)
{
//some code here
}
It does not executes either the on response method or on Failure method. No error or exception in catch block. In android studio logcat debug mode it shows :
D/WindowClient: Remove from mViews:android.widget.LinearLayout{a73a5de V.E...... ......I. 0,0-580,115}, this = android.view.WindowManagerGlobal#eeef6d7
i don't understand the problem behind it...is this debug message is the cause due to which next activity not opening or it is happening due to something else??
I am badly stuck here...not finding any way to move ahead !!
I'm using quickblox sdk group chat.
This is my code. But I still wrong. Can anybody guide me, please?
UserListForGroupActivity.java
public class UserListForGroupActivity extends Activity implements QBCallback {
private ListView usersList;
private ProgressDialog progressDialog;
private Button btnChat;
private SimpleAdapter usersAdapter;
private ArrayList<Friend_Users> friends= new ArrayList<Friend_Users>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_list_for_group);
usersList = (ListView) findViewById(R.id.usersList);
btnChat=(Button)findViewById(R.id.btnstartGroupChat);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading fiends list");
progressDialog.show();
// ================= QuickBlox ===== Step 4 =================
// Get all users of QB application.
QBUsers.getUsers(this);
}
#Override
public void onComplete(Result result) {
if (result.isSuccess()) {
if (progressDialog != null) {
progressDialog.dismiss();
}
// Cast 'result' to specific result class QBUserPagedResult.
QBUserPagedResult pagedResult = (QBUserPagedResult) result;
final ArrayList<QBUser> users = pagedResult.getUsers();
System.out.println(users.toString());
// Prepare users list for simple adapter.
ArrayList<Map<String, String>> usersListForAdapter = new ArrayList<Map<String, String>>();
for (QBUser u : users) {
Map<String, String> umap = new HashMap<String, String>();
umap.put("userLogin", u.getLogin());
umap.put("chatLogin", QBChat.getChatLoginFull(u));
usersListForAdapter.add(umap);
}
// Put users list into adapter.
usersAdapter = new SimpleAdapter(this, usersListForAdapter,
android.R.layout.simple_list_item_multiple_choice,
new String[]{"userLogin", "chatLogin"},
new int[]{android.R.id.text1, android.R.id.text2});
usersList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
usersList.setAdapter(usersAdapter);
btnChat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
SparseBooleanArray checked= usersList.getCheckedItemPositions();
for (int i = 0; i < checked.size(); i++) {
// Item position in adapter
int position = checked.keyAt(i);
// Add sport if it is checked i.e.) == TRUE!
if (checked.valueAt(i))
{
QBUser friendUser = users.get(position);
String login, password;
int id;
id=friendUser.getId();
login=friendUser.getLogin();
password=friendUser.getPassword();
friends.add(new Friend_Users(id,login, password));
}
}
Friend_Users_Wrapper wrapper= new Friend_Users_Wrapper(friends);
Log.e("UserListForGroupAcitvity friend list pass intent=>", friends.size()+ friends.get(0).getLogin());
Bundle extras = getIntent().getExtras();
Intent intent=new Intent(UserListForGroupActivity.this, GroupChatActivity.class);
intent.putExtra("friends", wrapper);
intent.putExtras(extras);
startActivity(intent);
}
});
} else {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setMessage("Error(s) occurred. Look into DDMS log for details, " +
"please. Errors: " + result.getErrors()).create().show();
}
}
#Override
public void onComplete(Result result, Object context) { }
}
GroupChatActivity.java
public class GroupChatActivity extends Activity {
private EditText messageText;
private TextView meLabel;
private TextView friendLabel;
private ViewGroup messagesContainer;
private ScrollView scrollContainer;
private QBUser me;
private GroupChatController groupChatController;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat);
// Load QBUser objects from bundle (passed from previous activity).
Bundle extras = getIntent().getExtras();
Friend_Users_Wrapper wrapper= (Friend_Users_Wrapper) getIntent().getSerializableExtra("friends");
ArrayList<Friend_Users> friendArray= wrapper.getFriend_Users();
me = new QBUser();
me.setId(extras.getInt("myId"));
me.setLogin(extras.getString("myLogin"));
me.setPassword(extras.getString("myPassword"));
System.out.println("user login =>"+extras.getString("myLogin"));
QBUser friends= new QBUser();
for (Friend_Users friend_Users : friendArray) {
friends.setId(friend_Users.getId());
friends.setLogin(friend_Users.getLogin());
friends.setPassword(friend_Users.getPassword());
}
// UI stuff
messagesContainer = (ViewGroup) findViewById(R.id.messagesContainer);
scrollContainer = (ScrollView) findViewById(R.id.scrollContainer);
Button sendMessageButton = (Button) findViewById(R.id.sendButton);
sendMessageButton.setOnClickListener(onSendMessageClickListener);
messageText = (EditText) findViewById(R.id.messageEdit);
// ================= QuickBlox ===== Step 5 =================
// Get chat login based on QuickBlox user account.
// Note, that to start chat you should use only short login,
// that looks like '17744-1028' (<qb_user_id>-<qb_app_id>).
String chatLogin = QBChat.getChatLoginShort(me);
// Our current (me) user's password.
String password = me.getPassword();
if (me != null && friends != null) {
// ================= QuickBlox ===== Step 6 =================
// All chat logic can be implemented by yourself using
// ASMACK library (https://github.com/Flowdalic/asmack/downloads)
// -- Android wrapper for Java XMPP library (http://www.igniterealtime.org/projects/smack/).
groupChatController = new GroupChatController(chatLogin, password);
groupChatController.setOnMessageReceivedListener(onMessageReceivedListener);
// ================= QuickBlox ===== Step 7 =================
// Get friend's login based on QuickBlox user account.
// Note, that for your companion you should use full chat login,
// that looks like '17792-1028#chat.quickblox.com' (<qb_user_id>-<qb_app_id>#chat.quickblox.com).
// Don't use short login, it
String friendLogin = QBChat.getChatLoginFull(friends);
groupChatController.startChat(friendLogin);
}
}
private void sendMessage() {
if (messageText != null) {
String messageString = messageText.getText().toString();
groupChatController.sendMessage(messageString);
messageText.setText("");
showMessage(me.getLogin() + " (me) : "+messageString, true);
}
}
private GroupChatController.OnMessageReceivedListener onMessageReceivedListener = new GroupChatController.OnMessageReceivedListener() {
#Override
public void onMessageReceived(final Message message) {
String messageString = message.getBody();
showMessage(messageString, false);
}
};
private void showMessage(String message, boolean leftSide) {
final TextView textView = new TextView(GroupChatActivity.this);
textView.setTextColor(Color.BLACK);
textView.setText(message);
int bgRes = R.drawable.left_message_bg;
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
if (!leftSide) {
bgRes = R.drawable.right_message_bg;
params.gravity = Gravity.RIGHT;
}
textView.setLayoutParams(params);
textView.setBackgroundResource(bgRes);
runOnUiThread(new Runnable() {
#Override
public void run() {
messagesContainer.addView(textView);
// Scroll to bottom
if (scrollContainer.getChildAt(0) != null) {
scrollContainer.scrollTo(scrollContainer.getScrollX(), scrollContainer.getChildAt(0).getHeight());
}
scrollContainer.fullScroll(View.FOCUS_DOWN);
}
});
}
private View.OnClickListener onSendMessageClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
sendMessage();
}
};
}
GroupChatController.java
public class GroupChatController {
// Get QuickBlox chat server domain.
// There will be created connection with chat server below.
public static final String CHAT_SERVER = QBChat.getChatServerDomain();
private XMPPConnection connection;
private ConnectionConfiguration config;
private Chat chat;
// Multi-User Chat
private MultiUserChat muc2;
private String chatLogin;
private String password;
private String friendLogin;
private ChatManager chatManager;
public GroupChatController(String chatLogin, String password) {
this.chatLogin = chatLogin;
this.password = password;
}
public void startChat(String buddyLogin) {
this.friendLogin = buddyLogin;
new Thread(new Runnable() {
#Override
public void run() {
// Chat action 1 -- create connection.
Connection.DEBUG_ENABLED = true;
config = new ConnectionConfiguration(CHAT_SERVER);
connection = new XMPPConnection(config);
try {
connection.connect();
connection.login(chatLogin, password);
// Chat action 2 -- create chat manager.
chatManager = connection.getChatManager();
// Chat action 3 -- create chat.
chat = chatManager.createChat(friendLogin, messageListener);
// Set listener for outcoming messages.
chatManager.addChatListener(chatManagerListener);
// Muc 2
if(connection != null){
muc2 = new MultiUserChat(connection, "2389_chat1#muc.chat.quickblox.com");
// Discover whether user3#host.org supports MUC or not
// The room service will decide the amount of history to send
muc2.join(chatLogin);
muc2.invite(friendLogin, "Welcome!");
Log.d("friendLogin ->",friendLogin);
// Set listener for outcoming messages.
//chatManager.addChatListener(chatManagerListener);
muc2.addMessageListener(packetListener);
addListenerToMuc(muc2);
//chat1#muc.chat.quickblox.com
}
Message message = new Message(friendLogin + "#muc.chat.quickblox.com");
message.setBody("Join me for a group chat!");
message.addExtension(new GroupChatInvitation("2389_chat1#muc.chat.quickblox.com"));
connection.sendPacket(message);
} catch (XMPPException e) {
e.printStackTrace();
}
}
}).start();
}
/*** muc */
private void addListenerToMuc(MultiUserChat muc){
if(null != muc){
muc.addMessageListener(new PacketListener() {
#Override
public void processPacket(Packet packet) {
Log.i("processPacket", "receiving message");
}
});
}
}
PacketListener packetListener = new PacketListener() {
#Override
public void processPacket(Packet packet) {
Message message = (Message)packet;
try {
muc2.sendMessage(message);
} catch (XMPPException e) {
e.printStackTrace();
}
//System.out.println("got message " + message.toXML());
}
};
private PacketInterceptor packetInterceptor = new PacketInterceptor() {
#Override
public void interceptPacket(Packet packet) {
System.out.println("Sending message: " + packet.toString());
Message message = muc2.createMessage();
message.setBody("Hello from producer, message " +
" ");
try {
muc2.sendMessage(message);
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
/***/
private ChatManagerListener chatManagerListener = new ChatManagerListener() {
#Override
public void chatCreated(Chat chat, boolean createdLocally) {
// Set listener for incoming messages.
chat.addMessageListener(messageListener);
muc2.addMessageListener(packetListener);
}
};
public void sendMessage(String message) {
try {
if (chat != null) {
chat.sendMessage(message);
}
if (muc2 != null) {
muc2.sendMessage(message);
}
} catch (XMPPException e) {
e.printStackTrace();
}
}
private MessageListener messageListener = new MessageListener() {
#Override
public void processMessage(Chat chat, Message message) {
// 'from' and 'to' fields contains senders ids, e.g.
// 17792-1028#chat.quickblox.com/mac-167
// 17744-1028#chat.quickblox.com/Smack
String from = message.getFrom().split("#")[0];
String to = message.getTo().split("#")[0];
System.out.println(String.format(">>> Message received (from=%s, to=%s): %s",
from, to, message.getBody()));
if (onMessageReceivedListener != null) {
onMessageReceivedListener.onMessageReceived(message);
}
}
};
public static interface OnMessageReceivedListener {
void onMessageReceived(Message message);
}
// Callback that performs when device retrieves incoming message.
private OnMessageReceivedListener onMessageReceivedListener;
public OnMessageReceivedListener getOnMessageReceivedListener() {
return onMessageReceivedListener;
}
public void setOnMessageReceivedListener(OnMessageReceivedListener onMessageReceivedListener) {
this.onMessageReceivedListener = onMessageReceivedListener;
}
}
public void startChat(String buddyLogin) {
...
List<String> usersLogins= new ArrayList<String>();
for(String userLogin: usersLogins){
muc2.invite(userLogin, "Welcome!");
}
...
}