I'm using RoboVM bindings for my iOS application to display AdMob interstitials. When I close the interstitial ad, I lose all touch controls. Is there a way to detect the ad being closed so I can put the touch back to the game? Or is there a better way to implement interstitials? Here's my code below:
public class IOSLauncher extends IOSApplication.Delegate implements IActivityRequestHandler{
private static final Logger log = new Logger(IOSLauncher.class.getName(), Application.LOG_DEBUG);
private IOSApplication iosApplication;
//interstitial
private static final String INTERSTITIAL_AD = "MY_AD_ID";
private GADInterstitial interstitial;
private UIWindow window;
private UIViewController rootViewController;
#Override
protected IOSApplication createApplication() {
IOSApplicationConfiguration config = new IOSApplicationConfiguration();
config.orientationLandscape = true;
config.orientationPortrait = false;
iosApplication = new IOSApplication(new PaperPig(this), config);
return iosApplication;
}
public static void main(String[] argv) {
NSAutoreleasePool pool = new NSAutoreleasePool();
UIApplication.main(argv, null, IOSLauncher.class);
pool.close();
}
#Override
public void initializeAds() {
intializeInterstitial();
}
public void intializeInterstitial () {
rootViewController = new UIViewController();
interstitial = new GADInterstitial();
interstitial.setAdUnitID(INTERSTITIAL_AD);
interstitial.setDelegate(new GADInterstitialDelegateAdapter() {
#Override
public void didReceiveAd (GADInterstitial ad) {
System.out.println("Did receive ad.");
}
#Override
public void didFailToReceiveAd (GADInterstitial ad, GADRequestError error) {
System.out.println(error.description());
System.out.println(error.getErrorCode());
}
});
window = new UIWindow(UIScreen.getMainScreen().getBounds());
window.setRootViewController(rootViewController);
window.addSubview(rootViewController.getView());
interstitial.loadRequest(GADRequest.create());
}
#Override
public void showOrLoadInterstital() {
if (interstitial.isReady()) {
if (rootViewController == null) {
rootViewController = new UIViewController();
}
if (window == null) {
window = new UIWindow(UIScreen.getMainScreen().getBounds());
window.setRootViewController(rootViewController);
}
window.makeKeyAndVisible();
interstitial.present(rootViewController);
}
//Return touch back to Game
//UIApplication.getSharedApplication().getKeyWindow().setRootViewController(rootViewController);
}
}
You need to call:
window.setHidden(true);
Change your creation of GADInterstitialDelegateAdapter() to the following
interstitial.setDelegate(new GADInterstitialDelegateAdapter() {
#Override
public void didReceiveAd (GADInterstitial ad) {
System.out.println("Did receive ad.");
}
#Override
public void didDismissScreen(GADInterstitial ad) {
window.setHidden(true);
}
#Override
public void didFailToReceiveAd (GADInterstitial ad, GADRequestError error) {
System.out.println(error.description());
System.out.println(error.getErrorCode());
}
});
Related
I have an updateTask method which opens an alert dialog. I am trying to call this method through a listener in the onBindViewHolder function in my custom adapter.
However my alert dialog does not pop up and while debugging I found out that my update task method is not called.
Please help me understand why.
Thanks
Here is my customAdapter:
public class TasksAdapter extends RecyclerView.Adapter<TasksAdapter.TaskViewHolder> {
private ArrayList<Model> tasks;
private TaskUpdateListener listener;
TasksAdapter(ArrayList<Model> tasks,TaskUpdateListener listener) {
this.tasks = tasks;
this.listener = listener;
}
#Override
public TaskViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.retrieved_layout, parent, false);
return new TaskViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull TaskViewHolder holder, int position) {
Model task = tasks.get(position);
holder.setDate(task.getDate());
holder.setTask(task.getTask());
holder.setDesc(task.getDescription());
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String taskString = task.getTask();
String descString = task.getDescription();
listener.onTaskUpdate(task, position);
}
});
}
#Override
public int getItemCount() {
return tasks.size();
}
public static class TaskViewHolder extends RecyclerView.ViewHolder {
View mView;
public TaskViewHolder(#NonNull View itemView) {
super(itemView);
mView = itemView;
}
public void setTask(String task) {
TextView taskTextView = mView.findViewById(R.id.taskTv);
taskTextView.setText(task);
}
public void setDesc(String desc) {
TextView descTextView = mView.findViewById(R.id.descriptionTv);
descTextView.setText(desc);
}
public void setDate(String date) {
TextView dateTextView = mView.findViewById(R.id.dateTv);
}
}
public interface TaskUpdateListener {
void onTaskUpdate(Model model, int position);
}
}
And here is my HomeActivity:
public class HomeActivity extends AppCompatActivity {
private Toolbar toolbar;
private RecyclerView recyclerView;
private FloatingActionButton floatingActionButton;
private FirebaseDatabase database = FirebaseDatabase.getInstance();
private DatabaseReference userTasksRef;
private FirebaseAuth mAuth;
private FirebaseUser mUser;
private String onlineUserID;
private ProgressDialog loader;
private String key = "";
private String task;
private String description;
#Override
public void onBackPressed(){
new AlertDialog.Builder(this)
.setMessage("Are you sure you want exit ?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_home);
toolbar = findViewById(R.id.homeToolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Todo List App");
mAuth = FirebaseAuth.getInstance();
recyclerView = findViewById(R.id.recyclerView);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(linearLayoutManager);
loader = new ProgressDialog(this);
mUser = mAuth.getCurrentUser();
onlineUserID = mUser.getUid();
database = FirebaseDatabase.getInstance("https://todolist-bbccd-default-rtdb.europe-west1.firebasedatabase.app");
userTasksRef = database.getReference("users").child(onlineUserID).child("tasks");
floatingActionButton = findViewById(R.id.fab);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addTask();
}
});
}
private void addTask() {
AlertDialog.Builder myDialog = new AlertDialog.Builder(this);
LayoutInflater inflater = LayoutInflater.from(this);
View myView = inflater.inflate(R.layout.input_file, null);
myDialog.setView(myView);
final AlertDialog dialog = myDialog.create();
dialog.setCancelable(false);
final EditText task = myView.findViewById(R.id.task);
final EditText description = myView.findViewById(R.id.description);
Button save = myView.findViewById(R.id.saveBtn);
Button cancel = myView.findViewById(R.id.CancelBtn);
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mTask = task.getText().toString().trim();
String mDescription = description.getText().toString().trim();
String id = userTasksRef.push().getKey();
String date = DateFormat.getDateInstance().format(new Date());
if (TextUtils.isEmpty(mTask)) {
task.setError("Task Required");
return;
}
if (TextUtils.isEmpty(mDescription)) {
description.setError("Description Required");
return;
} else {
loader.setMessage("Adding your data");
loader.setCanceledOnTouchOutside(false);
loader.show();
Model model = new Model(mTask, mDescription, id, date);
userTasksRef.child(id).setValue(model).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(HomeActivity.this, "Task has been inserted successfully", Toast.LENGTH_SHORT).show();
loader.dismiss();
} else {
String error = task.getException().toString();
Toast.makeText(HomeActivity.this, "Failed: " + error, Toast.LENGTH_SHORT).show();
loader.dismiss();
}
}
});
}
dialog.dismiss();
}
});
dialog.show();
}
#Override
protected void onStart() {
super.onStart();
ArrayList<Model> tasks = new ArrayList<>();
userTasksRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot taskSnapshot : dataSnapshot.getChildren()) {
Model task = taskSnapshot.getValue(Model.class);
tasks.add(task);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
// Handle errors here
}
});
TasksAdapter.TaskUpdateListener listener = new TasksAdapter.TaskUpdateListener() {
#Override
public void onTaskUpdate(Model model, int position) {
updateTask(model, position);
}
};
TasksAdapter adapter = new TasksAdapter(tasks, listener);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
public void updateTask(Model task, final int position ) {
AlertDialog.Builder myDialog = new AlertDialog.Builder(this);
LayoutInflater inflater = LayoutInflater.from(this);
View view = inflater.inflate(R.layout.update_data, null);
myDialog.setView(view);
final AlertDialog dialog = myDialog.create();
final EditText mTask = view.findViewById(R.id.mEditTextTask);
final EditText mDescription = view.findViewById(R.id.mEditTextDescription);
mTask.setText(task.getTask());
mTask.setSelection(task.getTask().length());
mDescription.setText(task.getDescription());
mDescription.setSelection(task.getDescription().length());
Button delButton = view.findViewById(R.id.btnDelete);
Button updateButton = view.findViewById(R.id.btnUpdate);
updateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String tasktxt = mTask.getText().toString().trim();
String descriptiontxt = mDescription.getText().toString().trim();
String date = DateFormat.getDateInstance().format(new Date());
Model model = new Model(tasktxt, descriptiontxt, key, date);
userTasksRef.child(key).setValue(model).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
Toast.makeText(HomeActivity.this, "Data has been updated successfully", Toast.LENGTH_SHORT).show();
}else {
String err = task.getException().toString();
Toast.makeText(HomeActivity.this, "update failed "+err, Toast.LENGTH_SHORT).show();
}
}
});
dialog.dismiss();
}
});
}
}
I have implemented following code for interstitial ads .Problem I am facing is that interstitial ad is shown only on first URL click. I want to adjust ads on every URL click or every 5th URL click in WebView app .Help in this regard will highly be appreciated. Following is the code i want to be modified .
private WebView webview;
private AdView mAdView;
private InterstitialAd mInterstitialAd;
SwipeRefreshLayout mySwipeRefreshLayout;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {}
});
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(this,"ca-app-pub-3940256099942544/1033173712", adRequest,
new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
mInterstitialAd = interstitialAd;
Log.i("TAG", "onAdLoaded");
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
// Handle the error
Log.i("TAG", loadAdError.getMessage());
mInterstitialAd = null;
}
});
private class WebViewClientDemo extends WebViewClient {
#Override
//Keep webview in app when clicking links
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (mInterstitialAd != null) {
mInterstitialAd.show(MainActivity.this);
} else {
Log.d("TAG", "The interstitial ad wasn't ready yet.");
}
return super.shouldOverrideUrlLoading(view, url);
}
You need to load Ad after each show. Create a static counter variable to load it on everyth nth click.
static int instanceCounter = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LoadInterstitial();
}
private void LoadInterstitial(){
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(this,"ca-app-pub-3940256099942544/1033173712", adRequest,
new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
mInterstitialAd = interstitialAd;
Log.i("TAG", "onAdLoaded");
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
// Handle the error
Log.i("TAG", loadAdError.getMessage());
mInterstitialAd = null;
}
});
}
private class WebViewClientDemo extends WebViewClient {
#Override
//Keep webview in app when clicking links
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (mInterstitialAd != null && isDisplayAdvert()) {
mInterstitialAd.show(MainActivity.this);
LoadInterstitial();
} else {
Log.d("TAG", "The interstitial ad wasn't ready yet.");
}
return super.shouldOverrideUrlLoading(view, url);
}
private bool isDisplayAdvert(){
instanceCounter++;
if(instanceCounter==5){
instanceCounter = 0;
return true;
}
return false;
}
Thanks sir Amod Gokhale . I tried the following code and it is working too .
Would you recommend me about the better one between both codes .
private class WebViewClientDemo extends WebViewClient {
int n = 1;
#Override
//Keep webview in app when clicking links
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (mInterstitialAd != null) {
if( n%6 == 0 )
{
mInterstitialAd.show(MainActivity.this);
} n++;
}
LoadInterstitial();
return super.shouldOverrideUrlLoading(view, url);
}
I've created a JavaFX application with JDK8, that contains a window and multiples objects.
I'm trying now to put useless used object available for GarbageCollector.(Testing with JVisualVM).
But I'm stuck with one problem: Clean a Popover that contains handler and listener on window element.
Original code of the popover:
public class CustomPopOver extends PopOver {
/**
* Constructor with the Content of the PopOver.
* #param content the Node.
*/
public CustomPopOver (Node content) {
super(content);
addHandler();
}
/**
* Empty Constructor.
*/
public CustomPopOver () {
super();
addHandler();
}
private void addHandler() {
this.ownerWindowProperty().addListener((observable, oldValue, newValue) -> {
if (newValue != null) {
EventHandler<WindowEvent> preExistingHandler = newValue.getOnCloseRequest();
newValue.setOnCloseRequest(event -> {
if (this.isShowing()) {
this.hide(Duration.millis(0));
}
if (preExistingHandler != null) {
preExistingHandler.handle(event);
}
});
}
});
}
}
I tried lots of thing to go to this, but it's not working properly:
public class CustomPopOver extends PopOver implements DisposableBean {
private MyListener listener = new MyListener();
public CustomPopOver (Node content) {
super(content);
addHandler();
}
/**
* Empty Constructor.
*/
public CustomPopOver () {
super();
addHandler();
}
private void addHandler() {
this.ownerWindowProperty().addListener(listener);
}
#Override
public void destroy() {
if (this.getOwnerWindow() != null){
this.getOwnerWindow()
.removeEventHandler(WindowEvent.WINDOW_CLOSE_REQUEST, listener.windowCloseEventHandler);
this.getOwnerWindow()
.removeEventHandler(WindowEvent.WINDOW_HIDING, listener.windowHidingEventHandler);
}
this.ownerWindowProperty().removeListener(listener);
listener = null;
}
/**
* ChangeListener that removes itself when needed.
*/
private class MyListener implements ChangeListener<Window> {
EventHandler<WindowEvent> windowCloseEventHandler;
EventHandler<WindowEvent> windowHidingEventHandler;
#Override
public void changed(ObservableValue<? extends Window> observable, Window oldValue, Window newValue) {
if (oldValue != null) {
oldValue.removeEventHandler(WindowEvent.WINDOW_CLOSE_REQUEST, windowCloseEventHandler);
oldValue.removeEventHandler(WindowEvent.WINDOW_HIDING, windowHidingEventHandler);
}
if (newValue != null) {
EventHandler<WindowEvent> preExistingHandler = newValue.getOnCloseRequest();
windowCloseEventHandler = new EventHandler<WindowEvent>() {
#Override
public void handle(WindowEvent event) {
if (isShowing()) {
hide(Duration.millis(0));
ownerWindowProperty().removeListener(MyListener.this);
}
if (preExistingHandler != null) {
preExistingHandler.handle(event);
}
newValue.removeEventHandler(WindowEvent.WINDOW_CLOSE_REQUEST, this);
}
};
newValue.setOnCloseRequest(windowCloseEventHandler);
windowHidingEventHandler = new EventHandler<WindowEvent>() {
#Override
public void handle(WindowEvent event) {
ownerWindowProperty().removeListener(MyListener.this);
newValue.removeEventHandler(WindowEvent.WINDOW_HIDING, this);
}
};
newValue.setOnHiding(windowHidingEventHandler);
}
}
}
}
and we call the destroy method to clean the popover from jvm cache.
Code to test class CustomPopOver:
public class PopOverViewer extends Application {
private BorderPane pane;
public PopOverViewer() {
pane = new BorderPane();
pane.setCenter(button());
}
private Node button() {
HBox hBox = new HBox();
List<CustomPopOver > lists = new ArrayList<>();
Button show = new Button("click");
show.setOnAction(event -> {
CustomPopOver popOver = new CustomPopOver ();
lists.add(popOver);
popOver.show(show);
});
Button clean = new Button("clean");
clean.setOnAction(event -> {
lists.forEach(CustomPopOver::destroy);
lists.clear();
});
hBox.getChildren().addAll(show, clean);
return hBox;
}
#Override
public void start(Stage primaryStage) {
PopOverViewer app = new PopOverViewer();
primaryStage.setScene(new Scene(app.getPane()));
primaryStage.show();
}
private Parent getPane() {
return pane;
}
}
I would like that the class CustomPopover is clean from GC.
Thanks #fabian, placing WeakEventHandler on Handler inside of a strong referenced Listener, helped to clean it.
Code that worked:
public class CustomPopOver extends PopOver implements DisposableBean {
private MyListener listener = new MyListener();
/**
* Constructor with the Content of the PopOver.
* #param content the Node.
*/
public CustomPopOver(Node content) {
super(content);
addHandler();
}
/**
* Empty Constructor.
*/
public CustomPopOver() {
super();
addHandler();
}
private void addHandler() {
this.ownerWindowProperty().addListener(listener);
}
#Override
public void destroy() {
this.ownerWindowProperty().removeListener(listener);
listener = null;
}
/**
* ChangeListener that removes itself when needed.
*/
private class MyListener implements ChangeListener<Window> {
#Override
public void changed(ObservableValue<? extends Window> observable, Window oldValue, Window newValue) {
if (newValue != null) {
EventHandler<WindowEvent> preExistingHandler = newValue.getOnCloseRequest();
EventHandler<WindowEvent> windowCloseEventHandler = new WeakEventHandler<>(new EventHandler<WindowEvent>() {
#Override
public void handle(WindowEvent event) {
if (isShowing()) {
hide(Duration.millis(0));
ownerWindowProperty().removeListener(CustomPopOver.MyListener.this);
}
if (preExistingHandler != null) {
preExistingHandler.handle(event);
}
newValue.removeEventHandler(WindowEvent.WINDOW_CLOSE_REQUEST, this);
}
});
newValue.setOnCloseRequest(windowCloseEventHandler);
EventHandler<WindowEvent> windowHidingEventHandler = new WeakEventHandler<>(new EventHandler<WindowEvent>() {
#Override
public void handle(WindowEvent event) {
ownerWindowProperty().removeListener(CustomPopOver.MyListener.this);
newValue.removeEventHandler(WindowEvent.WINDOW_HIDING, this);
}
});
newValue.setOnHiding(windowHidingEventHandler);
}
}
}
}
I want to display my Firebase notification message in textviews in background mode, but it's only working and displaying in foreground mode.
I have already used broadcastReceiver. It is working, but only in the foreground. How can I make it work in background mode?
This is my Firebase Messaging Service class:
public class ProfileActivity extends AppCompatActivity {
TextView notificationTitle, notificationMessage;
public static final String NODE_USERS = "users";
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LocalBroadcastManager.getInstance(this).registerReceiver(mHandler,new IntentFilter("com.example.linguanotification_FCM-MESSAGE"));
setContentView(R.layout.activity_profile);
notificationTitle=findViewById(R.id.title_notification);
notificationMessage=findViewById(R.id.notification_message);
mAuth = FirebaseAuth.getInstance();
FirebaseMessaging.getInstance().subscribeToTopic("updates");
FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
#Override
public void onComplete(#NonNull Task<InstanceIdResult> task) {
if (task.isSuccessful()) {
String token = task.getResult().getToken();
saveToken(token);
} else {
}
}
});
}
#Override
protected void onStart() {
super.onStart();
if (mAuth.getCurrentUser() == null) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
private void saveToken(String token) {
String email = mAuth.getCurrentUser().getEmail();
User user = new User(email, token);
DatabaseReference dbUsers = FirebaseDatabase.getInstance().getReference(NODE_USERS);
dbUsers.child(mAuth.getCurrentUser().getUid())
.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(ProfileActivity.this, "Token Saved", Toast.LENGTH_LONG).show();
}
}
});
}
private BroadcastReceiver mHandler = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String title = intent.getStringExtra("title");
String message=intent.getStringExtra("message");
notificationTitle.setText(title);
notificationMessage.setText(message);
}
};
#Override
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mHandler);
}
}
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
if (remoteMessage.getNotification() != null) {
String title = remoteMessage.getNotification().getTitle();
String body = remoteMessage.getNotification().getBody();
NotificationHelper.displayNotification(getApplicationContext(), title, body);
}
if (remoteMessage.getData().size()>0)
{
String title = remoteMessage.getData().get("title");
String message= remoteMessage.getData().get("message");
Intent intent = new Intent("com.example.linguanotification_FCM-MESSAGE");
intent.putExtra("title",title);
intent.putExtra("message",message);
LocalBroadcastManager localBroadcastManager=LocalBroadcastManager.getInstance(this);
localBroadcastManager.sendBroadcast(intent);
}
}
}
public class NotificationHelper {
public static void displayNotification(Context context, String title, String body) {
Intent intent = new Intent(context, ProfileActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
context,
100,
intent,
PendingIntent.FLAG_CANCEL_CURRENT
);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context, MainActivity.CHANNEL_ID)
.setSmallIcon(R.drawable.dd)
.setContentTitle(title)
.setContentText(body)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH);
NotificationManagerCompat mNotificationMgr = NotificationManagerCompat.from(context);
mNotificationMgr.notify(1, mBuilder.build());
}
}
public class MainActivity extends AppCompatActivity {
//1. Notification Channel
//2. Notification Builder
//3. Notification Manager
public static final String CHANNEL_ID = "12";
public static final String CHANNEL_NAME = "23";
public static final String CHANNEL_DESC = "34";
private EditText editTextEmail, editTextPassword;
private ProgressBar progressBar;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription(CHANNEL_DESC);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
progressBar = findViewById(R.id.progressbar);
progressBar.setVisibility(View.INVISIBLE);
editTextEmail = findViewById(R.id.editTextEmail);
editTextPassword = findViewById(R.id.editTextPassword);
findViewById(R.id.buttonSignUp).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
createUser();
}
});
}
private void createUser() {
final String email = editTextEmail.getText().toString().trim();
final String password = editTextEmail.getText().toString().trim();
if (email.isEmpty()) {
editTextEmail.setError("Email required");
editTextEmail.requestFocus();
return;
}
if (password.isEmpty()) {
editTextPassword.setError("Password required");
editTextPassword.requestFocus();
return;
}
if (password.length() < 6) {
editTextPassword.setError("Password should be atleast 6 char long");
editTextPassword.requestFocus();
return;
}
progressBar.setVisibility(View.VISIBLE);
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
startProfileActivity();
}else{
if(task.getException() instanceof FirebaseAuthUserCollisionException){
userLogin(email, password);
}else{
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(MainActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
}
}
}
});
}
private void userLogin(String email, String password){
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
startProfileActivity();
}else{
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(MainActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
//here we are checking if the user is not null then the user already logged in
#Override
protected void onStart() {
super.onStart();
if (mAuth.getCurrentUser() != null)
{
startProfileActivity();
}
}
private void startProfileActivity() {
Intent intent = new Intent(this, ProfileActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
I'm trying to show interstitial ads in some urls of my webview app, including onPagefinished and url.contains, but it doesn´t work. Here's my code:
#SuppressLint("SetJavaScriptEnabled") public class Juego extends ActionBarActivity {
/** ID intersticial */
private InterstitialAd interstitialAd;
private static final String AD_UNIT_ID = "ca-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_juego);
//Página web enlazada:
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.loadUrl("http://xxxxxxxxxxxxxxxxx.php");
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.setWebViewClient(new WebViewClient());
myWebView.setVerticalScrollBarEnabled(false);
myWebView.setHorizontalScrollBarEnabled(false);
//Barra de progreso
final Activity activity = this;
final ProgressDialog progressDialog = new ProgressDialog(activity);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setCancelable(false);
myWebView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
progressDialog.setTitle("Cargando");
progressDialog.setMessage("Por favor espera");
progressDialog.show();
progressDialog.setProgress(0);
activity.setProgress(progress * 1);
progressDialog.incrementProgressBy(progress);
if(progress == 100 && progressDialog.isShowing())
progressDialog.dismiss();
}
});
}
public void onPageFinished (WebView view, String url) {
// Anuncios intersticiales: Create the interstitial.
interstitialAd = new InterstitialAd(this);
interstitialAd.setAdUnitId(AD_UNIT_ID);
// Create ad request.
AdRequest adRequest = new AdRequest.Builder().build();
// Begin loading your interstitial.
interstitialAd.loadAd(adRequest);
if (url.contains("game")) {
interstitialAd.show();
}
}
}
Any help?
use this
public void onPageFinished (WebView view, String url) {
interstitial = new InterstitialAd(this);
interstitial.setAdUnitId("ca-app-pub-5236990339136194/xxxxxxxxxx");
// Begin loading your interstitial.
interstitial.loadAd(adRequest);
interstitial.setAdListener(new AdListener(){
public void onAdLoaded(){
displayInterstitial();
}
// Invoke displayInterstitial() when you are ready to display an interstitial.
public void displayInterstitial() {
if (interstitial.isLoaded()) {
interstitial.show();
}
}
} );
}
and don't forget add this on your onCreate blog
AdView adView = (AdView) this.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);