Admob without overlaying the Android Game - android

I know this should be easy but I am still learning and I am unsure how to get the AdMob banner to display at the top (stretched in width to fill the screen) without overlaying the game. This is written without any XML files and below is the code the I have that just displays the ad at the top of the screen overlaying the game.
Thank you guys in advance for any help you can provide.
public class Screen extends Activity implements Runnable, OnTouchListener, SensorEventListener {
private SurfaceHolder holder;
private boolean locker = true, initialised = false;
private Thread thread;
//public WakeLock WL;
private int width = 0, height = 0;
public float cameraX = 0, cameraY = 0;
public Activity activity = this;
public boolean debug_mode = false;
private long now = SystemClock.elapsedRealtime(), lastRefresh, lastfps;
public SurfaceView surface;
private int fps = 0, frames = 0, runtime = 0, drawtime = 0;
//sensor
SensorManager sm;
Sensor s;
float sensorx, calibratex = 0;
float sensory, calibratey = 0;
private boolean default_lanscape = false;
private int default_lanscape_rotation = 0;
//world origin
public final int TOP_LEFT = 0, BOTTOM_LEFT = 1;
public int origin = TOP_LEFT;
//layout
public RelativeLayout layout;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = this;
//full screen
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
//create surface
layout = new RelativeLayout(this);
surface = new SurfaceView(this);
setContentView(layout);
layout.addView(surface);
AdView ad = new AdView(this, AdSize.BANNER, "XXXXXXXX");
//layout
layout.addView(ad);
AdRequest request = new AdRequest();
AdRequest adRequest = new AdRequest();
adRequest.addTestDevice("xxxxxxxxxxxxxxxxx");
ad.loadAd(request);
holder = surface.getHolder();
//listeners
surface.setOnTouchListener(this);
// start game loop
thread = new Thread(this);
thread.start();
onCreate();
}

You really need to read about and understand how Android layouts or you aren't going to understand any help that is offered. http://developer.android.com/guide/topics/ui/declaring-layout.html
Having said that, start by replacing the RelativeLayout with a LinearLayout. And I strongly recommend you use an XML layout. You are far less likely to get lost especially since you are new to this.

Related

How to start an animation immediately on activity launch without any start delay

My MainAactivity starts with a background music( via service) and I have implemented an animation which should start as soon as the activity is launched along with the background music, but the animation starts after 10 seconds of activity launch(music starts with activity launch), even though I have not implemented any start delay. Can someone help me? I am new to android.
I have followed the following tutorial for animation:
https://www.javacodegeeks.com/2012/10/android-leaf-fall-like-animation-using.html
My MainActivity.java:
private int[] PICTURES = {
R.mipmap.f1, R.mipmap.f2, R.mipmap.f3, R.mipmap.f4,
};
private Rect display_Size = new Rect();
private RelativeLayout root_Layout;
private ArrayList<View> all_imageViews = new ArrayList<View>();
private float scale;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent i = new Intent(this,MusicService.class);
startService(i);
Display display = getWindowManager().getDefaultDisplay();
display.getRectSize(display_Size);
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
scale = metrics.density;
root_Layout = (RelativeLayout) findViewById(R.id.main_layout);
new Timer().schedule(new ExecTime(),0 , 1000);
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
int viewId = new Random().nextInt(PICTURES.length);
Drawable d = getResources().getDrawable(PICTURES[viewId]);
LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
ImageView imageView = (ImageView) inflater.inflate(R.layout.animated_image_view, null);
imageView.setImageDrawable(d);
root_Layout.addView(imageView);
all_imageViews.add(imageView);
RelativeLayout.LayoutParams animationLayout = (RelativeLayout.LayoutParams) imageView.getLayoutParams();
animationLayout.setMargins(0, (int)(-3000*scale), 0, 0);
animationLayout.width = (int) (50*scale);
animationLayout.height = (int) (50*scale);
startAnimation(imageView);
}
};
public void startAnimation(final ImageView animView) {
animView.setPivotX(animView.getWidth()/2);
animView.setPivotY(animView.getHeight()/2);
final ValueAnimator animator = ValueAnimator.ofFloat(0, 1);
animator.setDuration(15000);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
int angle = 50 + (int)(Math.random() * 101);
int move = new Random().nextInt(display_Size.right);
#Override
public void onAnimationUpdate(ValueAnimator animation) {
float value = (Float) (animation.getAnimatedValue());
animView.setRotation(angle*value);
animView.setTranslationX((move-100)*value);
animView.setTranslationY((display_Size.bottom + (3000*scale))*value);
}
});
animator.start();
}
private class ExecTime extends TimerTask {
#Override
public void run() {
handler.sendEmptyMessage(Constants.EMPTY_MESSAGE);
}
}
When application is launched android creates a new process that during it charge and create a black/white screen based on the application theme or the theme of the activity that is entry point.
This load can be increased if our application is complex and overwrites the application object, which is normally used to initialize the analytics.
Read this article for more info. http://saulmm.github.io/avoding-android-cold-starts

How to know if there is available space in TextView?

Because I would like to make the same, like Whatsapp, it puts message and hour in the same line
or in another line.
Sometimes there is space and Whatsapp puts the hour in same line. However sometimes there is not space and Whatsapp puts the hour in other line.
Inside or outside...
Any idea?
public static final String TAG = "MainActivity";
private TextView mText;
private RelativeLayout relativeLayout;
private Boolean mFirstTime = true;
private static final int WIDH_HOUR = 382;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final int width = getScreensWidh();
mText = (TextView) findViewById(R.id.activity_main_text);
relativeLayout = (RelativeLayout) findViewById(R.id.activity_main_relative);
mText.setText("aaaaa dfsafsa afdsfa fdsafas adfas fdasf adfsa dsa aaaa dfsafsa afdsfa fdsafas adfas fdasf adfsa");
ViewTreeObserver vto = mText.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if (mFirstTime) {
Layout layout = mText.getLayout();
int lines = layout.getLineCount();
int offset = layout.layout.getLineWidth(lines - 1);
int freeSpace = width - offset;
TextView hour = new TextView(MainActivity.this);
hour.setText("12:20");
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
if (freeSpace > WIDH_HOUR) {
params.addRule(RelativeLayout.ALIGN_BOTTOM, R.id.activity_main_text);
} else {
params.addRule(RelativeLayout.BELOW, R.id.activity_main_text);
}
hour.setLayoutParams(params);
relativeLayout.addView(hour);
Log.d(TAG, String.valueOf(freeSpace));
mFirstTime = false;
}
}
});
}
public int getScreensWidh() {
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
return size.x;
}
Two Public Methods
public abstract int getLineCount ()
Return the number of lines of text in this layout.
public int getLineWidth(int line)
Gets the unsigned horizontal extent of the specified line, including leading margin indent and trailing whitespace.
I think you can give textView.getLayout().getLineWidth(lineNum) a try (lineNum is obviously the last line).
Then compare it to the parent layout width, and if the difference is bigger than timestamp.getWidth() plus some extra padding, then you display it on the same line.

I want to display the image view at different position on the screen randomly

Here the ImageView is displaying only at one position, after closing the activity the next time the activity is opened the ImageView will be on another position... I want to display the ImageView randomly at diff position on the same activity itself. The image view should appear on one point suddenly the next second ImageView should disappear from that position and appear on the next position. How can i do it?
public class page2 extends ActionBarActivity {
ImageView b2;
int count = 0;
Handler handler = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page2);
Intent c = getIntent();
String name = c.getStringExtra("t");
Toast.makeText(getApplicationContext(), name, Toast.LENGTH_SHORT).show();
b2 = (ImageView) findViewById(R.id.redball);
AbsoluteLayout.LayoutParams absParams =
(AbsoluteLayout.LayoutParams)b2.getLayoutParams();
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int width = displaymetrics.widthPixels;
int height = displaymetrics.heightPixels;
Random r = new Random();
absParams.x = r.nextInt(width ) ;
absParams.y = r.nextInt(height );
b2.setLayoutParams(absParams);
Animation animation = AnimationUtils.loadAnimation(page2.this, R.anim.fade);
// Animation animation1 = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.activity_move);
b2.startAnimation(animation);
// b2.startAnimation(animation1);
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
count = count + 1;
}
});
handler = new Handler();
final Runnable t = new Runnable() {
public void run() {
Intent d = new Intent(getApplicationContext(), Page3.class);
d.putExtra("count", count);
d.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(d);
}
};
handler.postDelayed(t, 4000);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_page2, menu);
return true;
}
Don't use AbsoluteLayout, Why not use a custom view draw it?
You can achieve this by using Imageview within FrameLayout. Just change the layoutParams of the image to change its position.
As I understand it, you want that each time the activity is opened, so f you dont want to actually view to the user that the ImageView moves, why are you using Animation? You may just dynamically add the ImageView to the activity each time, and each time assign it different Margin attributes.
LinearLayout layout = (LinearLayout) view.findViewById(R.id.linear);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
params.setMargins(0, 0, 10, 0); //substitute parameters for left, top, right, bottom
ImageView iv = new ImageView(getActivity());
iv.setLayoutParams(params);
iv.setImageResource(R.drawable.yourimage);
layout.addView(iv);
for calucation
ContainerHeight = blinkerContainer.getHeight(); // total height of screen
ContainerWidth = blinkerContainer.getWidth(); //total width
blinkerHeight = blinkView.getHeight();
blinkerWidth = blinkView.getWidth();
minTopMargin = 30;
minLeftMargin = 30;
maxTopMargin = ContainerHeight - blinkerHeight - 30;
maxLeftMargin = ContainerWidth - blinkerWidth - 30;
for positioning
LinearLayout.LayoutParams params = (android.widget.LinearLayout.LayoutParams) blinkView
.getLayoutParams();
params.leftMargin = minLeftMargin
+ new Random().nextInt(maxLeftMargin - minLeftMargin);
params.topMargin = minTopMargin
+ new Random().nextInt(maxTopMargin - minTopMargin);
and you can use AlaramManager for Scheduling
Your solution is almost correct. Unfortunately, it looks like you're restarting the activity from your timer. Instead, you should just trigger the redraw.
This question has a couple of solutions on how to create a recurring timer. The solution with runOnUiThread() should allow you to execute the randomisation and re-displaying of the ImageView.

ScrollView with a SurfaceView

Currently I have a custom SurfaceView for a specific size of Panels that I used for my project. But I'm looking into expanding it hence I need a ScrollView to scroll it accordingly. But I'm not sure how do I merge the 2 together.
My SurfaceView is using a .java file to create its layout. It is not using .xml to create the layout.
//MySurfaceView.class
public class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback , Runnable{
private SurfaceHolder surfaceHolder;
private boolean isDestroyed = false;
private Canvas canvas;
private Paint paint;
private int maxWidth;
private int maxHeight;
private Resources resources;
int offset;
final byte ON=1;
final byte OFF=0;
int[] ledPositionControl = new int[97];
int ledBmpSize;
int positionControlSize;
int maxControl=96;
int sizeControl=0;
int row;
int col;
public MySurfaceView(Context context) {
super(context);
resources = context.getResources();
init(); //load pictures
surfaceHolder = this.getHolder();
surfaceHolder.addCallback(this);
paint =new Paint();
}
This is the class that runs the SurfaceView.
//Class that runs the SurfaceView Layout
public class drawingMode extends Activity implements OnClickListener {
public static int screenWidth;
public static int screenHeight;
private SharedPreferences sPrefs;
final byte ON = 1;
final byte OFF = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(new MySurfaceView(this));
DisplayMetrics metric = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metric);
screenWidth = metric.widthPixels;
screenHeight = metric.heightPixels;
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
Now how do I merge this SurfaceView into a ScrollView Layout? I have a .xml file that has a ScrollView inside but I tried to put the SurfaceView via tag wise through .xml but it didn't worked. I also tried the .addView and it didn't work too gave me some errors.
//I put this in a the onCreate of a class.
myScrollView = new ScrollView(getApplicationContext());
myScrollView.addView(new MySurfaceView(this));
setContentView(R.layout.scrollsurfaceview);
Firstly, you didn't specify LayoutParams. Secondly, you had a wrong setContentView. The best way is to place ScrollView in layout.xml. If you rather prefer to do in in the code, here is a hint:
ScrollView myScrollView = new ScrollView(this);
myScrollView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, MATCH_PARENT));
MySurfaceView myView = new MySurfaceView(this);
myView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, myHeight));
myScrollView.addView(myView);
setContentView(myScrollView); // !!!!!!

Setting Window Dim only working in onCreate()

I have a little problem with my Window dimming.
Basically, I want to set the dimAmount of my Activity to zero as soon as I swipe it into one direction.
Please be aware that my Activity is displayed as a dialog, and can be swiped to the left or right. This works perfectly fine. But the setWindowDim() method has no effect when called after swipe.
If i call the setWindowDim inside my onCreate method, it works perfectly fine.
I have no idea why it doesnt work anywhere else.
public class FinishDialog extends Activity {
private FrameLayout frame = null;
private GestureDetector gd = null;
private int displaywidth = 0;
private int original_x = 0;
private int dialog_width = 0;
private final int POS_LEFT = -1;
private final int POS_MID = 0;
private final int POS_RIGHT = 1;
/** the dialogs current position, POS_MID on startup */
private int current_pos = POS_MID;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//this.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
frame = new FrameLayout(this);
gd = new GestureDetector(this, new TouchManager(this));
// fill the challenge layout into the framelayout
frame.addView(LayoutInflater.from(getBaseContext()).inflate(R.layout.finishdialog, null));
setContentView(frame);
FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) frame.getLayoutParams();
GameLogic g = new GameLogic();
displaywidth = g.getDisplayWidth(this);
lp.width = displaywidth - displaywidth / 6;
lp.gravity = Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL;
LinearLayout llFinish = (LinearLayout) findViewById(R.id.llFinishDialog);
LinearLayout.LayoutParams lpLL = (LinearLayout.LayoutParams) llFinish.getLayoutParams();
lp.height = lpLL.height;
frame.setLayoutParams(lp);
// setWindowDim(0.0f); ---> if i set the dim here, it works perfectly fine
original_x = (int) frame.getX();
dialog_width = lp.width;
}
private void setWindowDim(float dim) {
Log.i("FinishDialog", "Setting window dim to " + dim + ".");
WindowManager.LayoutParams lpWin = getWindow().getAttributes();
lpWin.dimAmount = dim;
getWindow().setAttributes(lpWin);
}
/**
* move the dialog, depending on the swipe direction and the
* current position of the dialog
* #param action
*/
public void interpretTouch(int action) {
switch(action) {
case TouchManager.MOVE_DIALOG_RIGHT:
if(frame != null) {
if(current_pos == POS_MID) {
swipeDialog(600, frame, 0, dialog_width, 0, 0);
current_pos = POS_RIGHT;
setWindowDim(0.0f); // here setting the dim has no effect
} else if (current_pos == POS_LEFT) {
swipeDialog(600, frame, - dialog_width, original_x, 0, 0);
current_pos = POS_MID;
setWindowDim(0.9f); // here setting the dim has no effect
} else if (current_pos == POS_RIGHT) {
// if we are on the right and swipe right, nothing happens
}
}
Log.i("Challenge", "Moving dialog to the right.");
break;
case TouchManager.MOVE_DIALOG_LEFT:
if(frame != null) {
if(current_pos == POS_MID) {
swipeDialog(600, frame, 0, -dialog_width, 0, 0);
current_pos = POS_LEFT;
setWindowDim(0.0f); // here setting the dim has no effect
} else if (current_pos == POS_LEFT) {
// if we are on the left and swipe left, nothing happens
} else if (current_pos == POS_RIGHT) {
swipeDialog(600, frame, dialog_width, original_x, 0, 0);
current_pos = POS_MID;
setWindowDim(0.9f); // here setting the dim has no effect
}
}
Log.i("Challenge", "Moving dialog to the left.");
break;
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
return gd.onTouchEvent(event);
}
private void swipeDialog(int time, View framelayout, int fromDeltaX, int toDeltaX, int fromDeltaY, int toDeltaY) {
Log.i("FinishDialog", "Dialog swiped.");
TranslateAnimation trans = new TranslateAnimation(fromDeltaX, toDeltaX,
fromDeltaY, toDeltaY);
trans.setFillAfter(true);
trans.setFillEnabled(true);
trans.setDuration(time);
framelayout.startAnimation(trans);
}
}
Starting this activity right after I change the Window dim finally did the job.
Unfortunately, now the Screen flashes pretty "ugly" when the RefreshActivity gets started, does anyone have a solution for that?
import android.app.Activity;
import android.os.Bundle;
public class RefreshActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
finish();
}
}

Categories

Resources