I'm new to Android and this is my first app. I have problem with adding ads. Generally I've been following this tutorial http://www.kilobolt.com/unit-1-writing-basic-android-apps.html .
Then I tried following this official thing https://developers.google.com/admob/android/eclipse - I've modified android manifest file, strings.xml but I do not have activity_main.xml (Because I didn't check "create Activity" at the beginning...?).
So after a long searching I found this question:
Android AdMob without XML
So I tried this solution and now I have 2 errors:
AdSize cannot be resolved to a variable AndroidGame.java/gametitle/src/com/username/framework/implementation
The constructor AdRequest() is undefined AndroidGame.java/gametitle/src/com/username/framework/implementation
(I thought that sth may be wrong with the google play libs I've downloaded so I tried making a simple app from the official link mentioned above. There was no errors but the app didn't run - it just stopped at "launching 99%".)
Here's the full code for AndroidGame:
package com.username.framework.implementation;
import android.app.Activity;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import com.username.framework.Audio;
import com.username.framework.FileIO;
import com.username.framework.Game;
import com.username.framework.Graphics;
import com.username.framework.Input;
import com.username.framework.Screen;
public abstract class AndroidGame extends Activity implements Game {
AndroidFastRenderView renderView;
Graphics graphics;
Audio audio;
Input input;
FileIO fileIO;
Screen screen;
WakeLock wakeLock;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
boolean isPortrait = getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
int frameBufferWidth = isPortrait ? 480: 800;
int frameBufferHeight = isPortrait ? 800: 480;
Bitmap frameBuffer = Bitmap.createBitmap(frameBufferWidth,
frameBufferHeight, Config.RGB_565);
float scaleX = (float) frameBufferWidth
/ getWindowManager().getDefaultDisplay().getWidth();
float scaleY = (float) frameBufferHeight
/ getWindowManager().getDefaultDisplay().getHeight();
renderView = new AndroidFastRenderView(this, frameBuffer);
graphics = new AndroidGraphics(getAssets(), frameBuffer);
fileIO = new AndroidFileIO(this);
audio = new AndroidAudio(this);
input = new AndroidInput(this, renderView, scaleX, scaleY);
screen = getInitScreen();
//setContentView(renderView);
RelativeLayout layout = new RelativeLayout(this);
AdView adView = new AdView(this, AdSize.BANNER, "a151bf25136cf46");
layout.addView(renderView);
layout.addView(adView);
setContentView(layout);
adView.loadAd(new AdRequest());
PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "MyGame");
}
#Override
public void onResume() {
super.onResume();
wakeLock.acquire();
screen.resume();
renderView.resume();
}
#Override
public void onPause() {
super.onPause();
wakeLock.release();
renderView.pause();
screen.pause();
if (isFinishing())
screen.dispose();
}
#Override
public Input getInput() {
return input;
}
#Override
public FileIO getFileIO() {
return fileIO;
}
#Override
public Graphics getGraphics() {
return graphics;
}
#Override
public Audio getAudio() {
return audio;
}
#Override
public void setScreen(Screen screen) {
if (screen == null)
throw new IllegalArgumentException("Screen must not be null");
this.screen.pause();
this.screen.dispose();
screen.resume();
screen.update(0);
this.screen = screen;
}
public Screen getCurrentScreen() {
return screen;
}
}
And I do not want to switch to Android Studio. My computer is too poor for this. :(
Related
I'm starting an activity from the background service by using following piece of code:
Intent intent = new Intent(getApplicationContext(),AlarmActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
But when I finish the activity by clicking the OK or Snooze button the app doesn't close but minimises instead.
When that minimised app is opened, the alarm starts ringing again until the app is closed manually.
I've tried by following commands as well but no gain.
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
What could be the issue?
ActivityCode:
import android.content.Context;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.os.Vibrator;
import android.support.annotation.RequiresApi;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import com.solutionz.battery.saver.master.alarm.utils.AdInterstitial;
import com.solutionz.battery.saver.master.alarm.utils.AppGlobal;
import com.solutionz.battery.saver.master.alarm.utils.MySharedPreferences;
public class AlarmActivity extends AppCompatActivity {
Context context;
TextView title_tv, message_tv;
ImageView batteryIcon_iv;
TextView ok_tv, snooze_tv;
boolean isCharging;
Ringtone ringtone;
Vibrator vibrator;
Handler handler;
Runnable runnable;
PowerManager.WakeLock screenLock;
MySharedPreferences mySharedPreferences;
AdInterstitial adInterstitial;
long[] pattern = {1000, 500, 1000, 1000, 500};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_alarm);
mySharedPreferences = new MySharedPreferences(context);
adInterstitial = new AdInterstitial(context);
screenLock = ((PowerManager) getSystemService(POWER_SERVICE)).newWakeLock(
PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
screenLock.acquire();
setScreenSize();
setViews();
setContent();
setTimer();
adInterstitial.requestLoadInterstitial(false);
}
private void setScreenSize() {
// getting and setting the window size
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
// int width = (int) (size.x * 0.7);
// int height = (int) (size.y * 0.4);
WindowManager.LayoutParams params = getWindow().getAttributes();
params.gravity = Gravity.CENTER;
//params.height = height;
//params.width = width;
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
params.width = WindowManager.LayoutParams.WRAP_CONTENT;
this.getWindow().setAttributes(params);
}
private void setViews() {
title_tv = (TextView) findViewById(R.id.title_tv);
message_tv = (TextView) findViewById(R.id.message_tv);
batteryIcon_iv = (ImageView) findViewById(R.id.batteryIcon_iv);
ok_tv = (TextView) findViewById(R.id.ok_tv);
snooze_tv = (TextView) findViewById(R.id.snooze_tv);
scaleView(batteryIcon_iv, 0.7f, 1.0f);
ok_tv.getCompoundDrawables()[1].mutate().setColorFilter(ContextCompat.getColor(context, R.color.white), PorterDuff.Mode.SRC_ATOP);
snooze_tv.getCompoundDrawables()[1].mutate().setColorFilter(ContextCompat.getColor(context, R.color.white), PorterDuff.Mode.SRC_ATOP);
ok_tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mySharedPreferences.SetLastNotifiedChargingState(isCharging);
mySharedPreferences.SetIsNotified(true);
finish();
//android.os.Process.killProcess(android.os.Process.myPid());
// System.exit(1);
}
});
snooze_tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mySharedPreferences.SetIsSnoozed(true);
finish();
//android.os.Process.killProcess(android.os.Process.myPid());
// System.exit(1);
}
}
});
}
private void setContent() {
Bundle bundle = getIntent().getBundleExtra("data");
title_tv.setText(bundle.getString("title"));
message_tv.setText(bundle.getString("message"));
isCharging = bundle.getBoolean("isCharging");
if (!isCharging) {
batteryIcon_iv.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_battery_30));
batteryIcon_iv.getDrawable().mutate().setColorFilter(ContextCompat.getColor(context, R.color.white), PorterDuff.Mode.SRC_ATOP);
} else {
batteryIcon_iv.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_battery_charging_80));
batteryIcon_iv.getDrawable().mutate().setColorFilter(ContextCompat.getColor(context, R.color.white), PorterDuff.Mode.SRC_ATOP);
}
// playAlarmTone();
mediaPlayerSetting();
}
public void scaleView(View v, float startScale, float endScale) {
Animation anim = new ScaleAnimation(
startScale, endScale, // Start and end values for the X axis scaling
startScale, endScale, // Start and end values for the Y axis scaling
Animation.RELATIVE_TO_SELF, 0.5f, // Pivot point of X scaling
Animation.RELATIVE_TO_SELF, 0.5f); // Pivot point of Y scaling
anim.setFillAfter(true); // Needed to keep the result of the animation
anim.setDuration(1000);
anim.setRepeatMode(Animation.REVERSE);
anim.setRepeatCount(Animation.INFINITE);
v.startAnimation(anim);
}
public void mediaPlayerSetting() {
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
ringtone = RingtoneManager.getRingtone(getApplicationContext(), notification);
if (mySharedPreferences.GetIsSoundEnabled()) // Play sound
{
int volume = audioManager.getStreamVolume(AudioManager.STREAM_ALARM);
if (volume == 0)
volume = audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM);
audioManager.setStreamVolume(AudioManager.STREAM_ALARM, volume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
ringtone = RingtoneManager.getRingtone(getApplicationContext(), notification);
if (ringtone != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ringtone.setAudioAttributes(new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_ALARM).build());
} else {
ringtone.setStreamType(AudioManager.STREAM_ALARM);
}
ringtone.play();
}
}
if (mySharedPreferences.GetIsVibrationEnabled()) // Start vibration
{
vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(pattern, 0);
}
}
private void setTimer() {
handler = new Handler();
runnable = new Runnable() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void run() {
AppGlobal.showNotification(getApplicationContext(), title_tv.getText().toString(), message_tv.getText().toString());
AlarmActivity.this.finish();
}
};
handler.postDelayed(runnable, mySharedPreferences.GetAlarmDuration() * 1000);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (ringtone != null && ringtone.isPlaying()) ringtone.stop();
if (vibrator != null) vibrator.cancel();
handler.removeCallbacks(runnable);
screenLock.release();
}
}
In Android finish() method is not closing the app but minizing it
No. First of all there's no concept of "minimizing" apps on Android, and finish() is NOT closing the main app process, but only finished the activity.
i am new to android and stuck with getting screen size. Here is my code,
package com.piyush.droidz;
import android.app.Activity;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import com.piyush.droidz.model.boy;
public class MainGamePanel extends SurfaceView implements SurfaceHolder.Callback {
private static final String TAG = MainGamePanel.class.getSimpleName();
private GameThread td;
private boy b1;
private int s_width;
private int s_height;
public MainGamePanel(Context context) {
super(context);
getHolder().addCallback(this);
Log.d(TAG, "Screen width=" + s_width);
b1 = new boy(BitmapFactory.decodeResource(getResources(), R.drawable.boy), 50, 50);
td = new GameThread(getHolder(), this);
setFocusable(true);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
s_width = getHolder().getSurfaceFrame().width();
Log.d(TAG, "Present Screen width=" + s_width);
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
td.setRunning(true);
td.start();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
td.setRunning(false);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
b1.handleActionDown((int)event.getX(), (int)event.getY());
if (event.getY()>getHeight()-50) {
td.setRunning(false);
((Activity) getContext()).finish();
}
else {
Log.d(TAG, "Coordinates: X="+event.getX()+", Y="+event.getY());
}
}
if (event.getAction()==MotionEvent.ACTION_MOVE) {
if (b1.isTouched()) {
b1.setX((int)event.getX());
b1.setY((int)event.getY());
}
}
if (event.getAction()==MotionEvent.ACTION_UP) {
b1.setTouched(false);
}
return true;
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.parseColor("#ff0000"));
b1.draw(canvas);
}
}
in the first log-tag it shows 0 where as in the second log-tag it shows exact width of emulator. I have tried initializing the "s_width" with getHolder().getSurfaceFrame().width() even before the constructor but still "s_width" is 0. Also tried WindowManagerand getwindowManager() but it is not recognized by IDE in this class. Here is my Activity class,
package com.piyush.droidz;
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
public class DroidzActivity extends Activity {
MainGamePanel mgp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mgp = new MainGamePanel(this);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(mgp);
}
}
please help!
Have you tried?
DisplayMetrics metrics = new DisplayMetrics();
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
windowManager.getDefaultDisplay().getMetrics(metrics);
You need to use context for getting the WindowManager. please see the documentation
http://developer.android.com/reference/android/view/WindowManager.html
Preferably the above should be done inside the constructor
public MainGamePanel(Context context) {}
Hope it helps. :)
I have been trying to implement libgdx without a core project in a new eclipse project, but I keep getting:
The method initialize(ApplicationListener,
AndroidApplicationConfiguration) in the type AndroidApplication is not
applicable for the arguments (AndroidApplication,
AndroidApplicationConfiguration)
The code I use is quite simple at the moment:
package com.debels.androidapplication;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
import android.os.Bundle;
public class MainActivity extends AndroidApplication{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration();
cfg.useGL20 = false;
initialize(new AndroidApplication(), cfg);
}
}
and
package com.debels.androidapplication;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.FPSLogger;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
//import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
//import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.debels.androidapplication.screens.MainMenuScreen;
public class AndroidApplication extends Game{
private OrthographicCamera camera;
private SpriteBatch batch;
private Texture texture;
private Sprite sprite;
private FPSLogger fps;
#Override
public void create(){
float w = Gdx.graphics.getWidth();
float h = Gdx.graphics.getHeight();
camera = new OrthographicCamera(1, h/w);
batch = new SpriteBatch();
//texture = new Texture(Gdx.files.internal("data/libgdx.png"));
//texture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
//TextureRegion region = new TextureRegion(texture, 0, 0, 512, 275);
/*sprite = new Sprite(region);
sprite.setSize(0.9f, 0.9f * sprite.getHeight() / sprite.getWidth());
sprite.setOrigin(sprite.getWidth()/2, sprite.getHeight()/2);
sprite.setPosition(-sprite.getWidth()/2, -sprite.getHeight()/2);*/
setScreen(new MainMenuScreen(this));
fps = new FPSLogger();
}
#Override
public void dispose() {
super.dispose();
}
#Override
public void render() {
super.render();
/*fps.log();
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
batch.setProjectionMatrix(camera.combined);
batch.begin();
sprite.draw(batch);
batch.end();*/
}
#Override
public void resize(int width, int height) {
super.resize(width, height);
}
#Override
public void pause() {
super.pause();
}
#Override
public void resume() {
super.resume();
}
}
Thats because you are sending a (gdx)AndroidApplication instance to the ini instead of a (gdx)AndroidApplicationListener (which is any class that extends Game or implements ApplicationListener).
You get all confused because you named that class AndroidApplication...
Change this:
initialize(new AndroidApplication(), cfg);
to this:
initialize(new com.debels.androidapplication.AndroidApplication(), cfg);
Or better yet, change the name of that class.
Also dont forget to copy the gdx.jar to the android project libs folder.
I am developing a game for android. Between stages, i want to show a part of a map with a route, and move it from a city to city (stage to stage).
First i want to do it on my phone, this a Samsung Galaxy Y, 240x320 Qvga ldpi.
So i have the map file in jpg format. This picture is 2463x602, this is a world map.
I did it, everything is done except one thing. This "animation" is slow for me.
When i start with this, i thought, it will be so fast, and i will handle the speed with a Thread.sleep(); but the matter is, it is not fast.
How can i make it more faster this?
Here is my code:
package hu.mycompany.myproject;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class MapActivity extends Activity {
DrawView drawView;
SoundPool soundPool;
int soundId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
soundId = soundPool.load(this, R.raw.airplane, 1);
drawView = new DrawView(this);
setContentView(drawView);
}
public void playSound() {
soundPool.play(soundId, 1f, 1f, 1, 0, 1f);
}
#Override
public void onResume() {
super.onResume();
playSound();
drawView.resume();
}
#Override
public void onPause() {
super.onPause();
drawView.pause();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_map, menu);
return true;
}
public class DrawView extends SurfaceView implements Runnable {
Bitmap gameMap = null;
Thread gameLoop = null;
SurfaceHolder surface;
Rect rect;
volatile boolean running;
volatile boolean moved;
public DrawView(Context context) {
super(context);
moved = false;
surface = getHolder();
gameMap = BitmapFactory.decodeResource(getResources(),
R.drawable.map);
}
public void resume() {
running = true;
gameLoop = new Thread(this);
gameLoop.start();
}
public void pause() {
running = false;
while (true) {
try {
gameLoop.join();
} catch (InterruptedException e) {
}
}
}
#Override
public void run() {
Rect canvasSize = new Rect(0, 0, 240, 320);
Paint paint = new Paint();
paint.setAntiAlias(true);
while (running) {
if (!surface.getSurface().isValid()) {
continue;
}
if (!moved) {
int i;
for (i = 80; i <= 830; i++) {
Canvas canvas = surface.lockCanvas();
rect = new Rect(i, 250, (i + 240), 570);
canvas.drawBitmap(gameMap, rect, canvasSize, paint);
surface.unlockCanvasAndPost(canvas);
}
moved = true;
}
}
}
}
}
1-try to reduce picture size by exporting it save for web in photoshop and select png as extension type
2- You should create two class one for handling thread and other for rendering and game logic. The thread will manage it by locking canvas when system is rendering. Take a look at this link
http://android-er.blogspot.com/2010/05/android-surfaceview.html
I have a simple application, where I created a SurfaceView class, then in the main activity, I created an object of the class, then added this SurfaceView to a relative layout, and set the content view to the relative layout.
package com.my.game;
import com.google.ads.Ad;
import com.google.ads.AdListener;
import com.google.ads.AdRequest;
import com.google.ads.AdRequest.ErrorCode;
import com.google.ads.AdSize;
import com.google.ads.AdView;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.RelativeLayout;
public class ShootLetters extends Activity {
private Panel panel;
private int newWidth;
private int newHeight;
private AdView adView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bitmap bg = BitmapFactory.decodeResource(this.getResources(),
R.drawable.shooting_background);
;
int width = bg.getWidth();
int height = bg.getHeight();
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
newWidth = metrics.widthPixels;
newHeight = metrics.heightPixels;
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// CREATE A MATRIX FOR THE MANIPULATION
Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizedBackGround = Bitmap.createBitmap(bg, 0, 0, width, height,
matrix, false);
Window win = getWindow();
Drawable d = new BitmapDrawable(resizedBackGround);
win.setBackgroundDrawable(d);
panel = new Panel(this, newWidth, newHeight);
panel.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
panel.setClickX(event.getX());
panel.setClickY(event.getY());
}
return true;
}
});
adView = new AdView(this, AdSize.BANNER, "admobidxxx222");
RelativeLayout rl = new RelativeLayout(this);
rl.addView(panel);
rl.addView(adView);
setContentView(rl);
// Initiate a generic request to load it with an ad
adView.loadAd(new AdRequest());
}
#Override
public void onDestroy() {
if (adView != null) {
adView.destroy();
}
panel.stopThread();
panel = null;
super.onDestroy();
}
}
This works fine for starting and stopping the application.
The problem is when another activity comes on top of this one, it behaves in an unstable way (no need for details at this stage as sometimes it crashes and sometimes it works with missing layout objects).
I read that I should implement onPause() & onResume() methods to handle this.
I only need pause the activity or resume it on resume. No persistent data required.
What should I put in which methods in this case?
Thanks
I guess its your Panel that is the surfaceview? I see you are doing something with its thread in onDestroy but that is not sufficient. You had a correct hunch about implementing onPause() and onResume() Now my idea(without being able to see all of your code) is that you are not dealing with the thread correctly. In your Panel class which extends surfaceview you should have something like these two functions:
public void pause(){
Loop = false;
while (true){
try{
panelThread.join();//end it
}catch (InterruptedException e){
e.printStackTrace();
}
break;
}
panelThread = null;
}
public void resume(){
Loop = true;
panelThread = new Thread(this);
panelThread.start();
}
Ignore the Loop part if you are not using a loop in your run() method.
Then, in your activity's onPause() and onResume() methods you call panel.pause() and panel.resume() respectively. This makes sure that the surface view thread is being handled in a safe way.