I'm trying to make a basic AndEngine game but the sprite doesn't appear. I don't get any errors.
I can't find the issue and neither can the guy who's helping me with this so any help is greatly appreciated.
public class Game extends BaseGameActivity implements SensorEventListener {
Scene scene;
protected static final int CAMERA_WIDTH = 800;
protected static final int CAMERA_HEIGHT = 480;
private BuildableBitmapTextureAtlas playerTexture;
private TextureRegion regionCell;
private Sprite sprCell;
private SensorManager sensorManager;
private float accellSpeedX, accellSpeedY;
private float sprX, sprY;
#Override
public EngineOptions onCreateEngineOptions() {
// TODO Auto-generated method stub
Camera mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
EngineOptions options = new EngineOptions(true,
ScreenOrientation.LANDSCAPE_FIXED, new RatioResolutionPolicy(
CAMERA_WIDTH, CAMERA_HEIGHT), mCamera);
return options;
}
#Override
public void onCreateResources(
OnCreateResourcesCallback pOnCreateResourcesCallback)
throws Exception {
// TODO Auto-generated method stub
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
// BitmapTextureAtlas must be power of 2 for width and height.
playerTexture = new BuildableBitmapTextureAtlas(
this.getTextureManager(), 256, 64);
regionCell = BitmapTextureAtlasTextureRegionFactory.createFromAsset(
playerTexture, this.getAssets(), "player.png");
playerTexture.load();
pOnCreateResourcesCallback.onCreateResourcesFinished();
}
#SuppressWarnings("static-access")
#Override
public void onCreateScene(OnCreateSceneCallback pOnCreateSceneCallback)
throws Exception {
// TODO Auto-generated method stub
sensorManager = (SensorManager) getSystemService(this.SENSOR_SERVICE);
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
sensorManager.SENSOR_DELAY_GAME);
this.mEngine.registerUpdateHandler(new FPSLogger());
this.mEngine.registerUpdateHandler(new IUpdateHandler() {
#Override
public void reset() {
// TODO Auto-generated method stub
}
#Override
public void onUpdate(float pSecondsElapsed) {
// TODO Auto-generated method stub
updateSpritePosistion();
}
private void updateSpritePosistion() {
// TODO Auto-generated method stub
if (accellSpeedX != 0 || accellSpeedY != 0) {
int tL = 0;
int iL = 0;
int rL = CAMERA_WIDTH - (int) sprCell.getWidth();
int bL = CAMERA_HEIGHT - (int) sprCell.getHeight();
if (sprX >= iL) {
sprX += accellSpeedX;
} else {
sprX = iL;
}
if (sprX <= rL) {
sprX += accellSpeedX;
} else {
sprX = rL;
}
if (sprY >= tL) {
sprY += accellSpeedY;
} else {
sprY = tL;
}
if (sprY <= bL) {
sprY += accellSpeedY;
} else {
sprY = bL;
}
if (sprX < iL) {
sprX = iL;
} else if (sprX > rL) {
sprX = rL;
}
if (sprY < tL) {
sprY = tL;
} else if (sprY > bL) {
sprY = bL;
}
sprCell.setPosition(sprX, sprY);
}
}
});
this.scene = new Scene();
this.scene.setBackground(new Background(0, 122, 222));
sprX = (CAMERA_WIDTH - this.regionCell.getWidth()) / 2;
sprY = (CAMERA_HEIGHT - this.regionCell.getHeight()) / 2;
sprCell = new Sprite(sprX, sprY, regionCell,
getVertexBufferObjectManager());
scene.attachChild(sprCell);
pOnCreateSceneCallback.onCreateSceneFinished(this.scene);
}
#Override
public void onPopulateScene(Scene pScene,
OnPopulateSceneCallback pOnPopulateSceneCallback) throws Exception {
// TODO Auto-generated method stub
pOnPopulateSceneCallback.onPopulateSceneFinished();
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
synchronized (this) {
switch (event.sensor.getType()) {
case Sensor.TYPE_ACCELEROMETER:
accellSpeedX = (int) event.values[1];
accellSpeedY = (int) event.values[0];
break;
}
}
}
}
Try this..I have tried it and solved the problem... Just set & change the size of your image in mBitmapTextureAtlas and name of your image in mTextureRegion under onCreateResources...
public class MainActivity extends BaseGameActivity implements
SensorEventListener {
Scene scene;
private ITextureRegion mTextureRegion;
private BuildableBitmapTextureAtlas mBitmapTextureAtlas;
protected static final int CAMERA_WIDTH = 800;
protected static final int CAMERA_HEIGHT = 480;
private BuildableBitmapTextureAtlas playerTexture;
private Sprite sprCell;
private SensorManager sensorManager;
private float accellSpeedX, accellSpeedY;
private float sprX, sprY;
Rectangle rect;
#Override
public EngineOptions onCreateEngineOptions()
{
// TODO Auto-generated method stub
Camera mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
EngineOptions options = new EngineOptions(true,
ScreenOrientation.LANDSCAPE_FIXED, new RatioResolutionPolicy(
CAMERA_WIDTH, CAMERA_HEIGHT), mCamera);
return options;
}
#Override
public void onCreateResources(
OnCreateResourcesCallback pOnCreateResourcesCallback)
throws Exception {
// TODO Auto-generated method stub
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
this.mBitmapTextureAtlas = new BuildableBitmapTextureAtlas(this.getTextureManager(), 100, 100);
this.mTextureRegion = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(this.mBitmapTextureAtlas, this, "mo.png");
try
{
this.mBitmapTextureAtlas
.build(new BlackPawnTextureAtlasBuilder<IBitmapTextureAtlasSource, BitmapTextureAtlas>(
0, 0, 0));
this.mBitmapTextureAtlas.load();
}
catch (TextureAtlasBuilderException e)
{
Debug.e(e);
}
pOnCreateResourcesCallback.onCreateResourcesFinished();
}
#SuppressWarnings("static-access")
#Override
public void onCreateScene(OnCreateSceneCallback pOnCreateSceneCallback)
throws Exception {
// TODO Auto-generated method stub
this.scene = new Scene();
this.scene.setBackground(new Background(0, 122, 222));
sprX = (CAMERA_WIDTH - this.mTextureRegion.getWidth()) / 2;
sprY = (CAMERA_HEIGHT - this.mTextureRegion.getHeight()) / 2;
sprCell = new Sprite(sprX, sprY, mTextureRegion, getVertexBufferObjectManager());
scene.attachChild(sprCell);
sensorManager = (SensorManager) getSystemService(this.SENSOR_SERVICE);
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
sensorManager.SENSOR_DELAY_GAME);
this.mEngine.registerUpdateHandler(new FPSLogger());
this.mEngine.registerUpdateHandler(new IUpdateHandler() {
#Override
public void reset() {
// TODO Auto-generated method stub
}
#Override
public void onUpdate(float pSecondsElapsed) {
// TODO Auto-generated method stub
updateSpritePosistion();
}
private void updateSpritePosistion() {
// TODO Auto-generated method stub
if (accellSpeedX != 0 || accellSpeedY != 0) {
int tL = 0;
int iL = 0;
int rL = CAMERA_WIDTH - (int) sprCell.getWidth();
int bL = CAMERA_HEIGHT - (int) sprCell.getHeight();
if (sprX >= iL) {
sprX += accellSpeedX;
} else {
sprX = iL;
}
if (sprX <= rL) {
sprX += accellSpeedX;
} else {
sprX = rL;
}
if (sprY >= tL) {
sprY += accellSpeedY;
} else {
sprY = tL;
}
if (sprY <= bL) {
sprY += accellSpeedY;
} else {
sprY = bL;
}
if (sprX < iL) {
sprX = iL;
} else if (sprX > rL) {
sprX = rL;
}
if (sprY < tL) {
sprY = tL;
} else if (sprY > bL) {
sprY = bL;
}
sprCell.setPosition(sprX, sprY);
}
}
});
pOnCreateSceneCallback.onCreateSceneFinished(this.scene);
}
#Override
public void onPopulateScene(Scene pScene,
OnPopulateSceneCallback pOnPopulateSceneCallback) throws Exception {
// TODO Auto-generated method stub
pOnPopulateSceneCallback.onPopulateSceneFinished();
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
synchronized (this) {
switch (event.sensor.getType()) {
case Sensor.TYPE_ACCELEROMETER:
accellSpeedX = (int) event.values[1];
accellSpeedY = (int) event.values[0];
break;
}
}
}
}
You should load your textures before you create texture region from them.
Related
I am creating an custom camera and when I click to take the pic, I am getting some errors.
I have used a SurfaceView to take the image.
Error:
10-10 16:17:00.269: E/AndroidRuntime(29256): FATAL EXCEPTION: main
10-10 16:17:00.269: E/AndroidRuntime(29256): Process: com.example.abc, PID: 29256
10-10 16:17:00.269: E/AndroidRuntime(29256): java.lang.RuntimeException: startPreview failed
10-10 16:17:00.269: E/AndroidRuntime(29256): at android.hardware.Camera.startPreview(Native Method)
10-10 16:17:00.269: E/AndroidRuntime(29256): at com.example.abc.Custom_CameraActivity.onClick(Custom_CameraActivity.java:237)
10-10 16:17:00.269: E/AndroidRuntime(29256): at android.view.View.performClick(View.java:4471)
10-10 16:17:00.269: E/AndroidRuntime(29256): at android.view.View$PerformClick.run(View.java:18778)
10-10 16:17:00.269: E/AndroidRuntime(29256): at android.os.Handler.handleCallback(Handler.java:808)
10-10 16:17:00.269: E/AndroidRuntime(29256): at android.os.Handler.dispatchMessage(Handler.java:103)
10-10 16:17:00.269: E/AndroidRuntime(29256): at android.os.Looper.loop(Looper.java:193)
10-10 16:17:00.269: E/AndroidRuntime(29256): at android.app.ActivityThread.main(ActivityThread.java:5304)
10-10 16:17:00.269: E/AndroidRuntime(29256): at java.lang.reflect.Method.invokeNative(Native Method)
10-10 16:17:00.269: E/AndroidRuntime(29256): at java.lang.reflect.Method.invoke(Method.java:515)
10-10 16:17:00.269: E/AndroidRuntime(29256): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
10-10 16:17:00.269: E/AndroidRuntime(29256): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
10-10 16:17:00.269: E/AndroidRuntime(29256): at dalvik.system.NativeStart.main(Native Method)
My Code:
public class Custom_CameraActivity extends Activity implements OnClickListener, Callback {
private static Camera camera;
private static int vesion;
private static int which;
private int brightness;
private Bitmap cameraBitmap;
private ImageView capt_btn;
int currBrightness;
private ImageView flash_btn;
private VerticalSeekBar greenSeekbar;
#SuppressLint({"HandlerLeak"})
Handler handler;
private boolean hasFlash;
private boolean isLighOn;
private ImageView list_btn;
private PictureCallback mPicture;
private int max_zoom_factor;
private boolean previewing;
private int screenHeight;
private int screenWidth;
private Bitmap surfaceBitmap;
private SurfaceHolder surfaceHolder;
private SurfaceView surfaceView;
private ImageView turn_btn;
private SeekBar zoomSeekBar;
private int zoom_factor;
public Custom_CameraActivity() {
this.previewing = false;
this.isLighOn = false;
this.zoom_factor = 0;
this.max_zoom_factor = 0;
this.handler = new Handler(){
public void handleMessage(Message msg) {
if (msg.what == 0) {
Toast.makeText(Custom_CameraActivity.this, Custom_CameraActivity.this.getResources().getString(R.string.txt_toastPhotoNotSaved), 0).show();
} else {
Toast.makeText(Custom_CameraActivity.this, Custom_CameraActivity.this.getResources().getString(R.string.txt_toastPhotoSaved), 0).show();
}
Custom_CameraActivity.this.surfaceView.setBackgroundColor(Color.argb(100, 0, MotionEventCompat.ACTION_MASK, 0));
}
};
this.mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
Custom_CameraActivity.this.cameraBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
Custom_CameraActivity.this.cameraBitmap = Custom_CameraActivity.getResizedBitmap(Custom_CameraActivity.this.cameraBitmap, Custom_CameraActivity.this.screenHeight, Custom_CameraActivity.this.screenWidth);
Custom_CameraActivity.this.joinBitmap();
camera.startPreview();
}
};
}
static {
camera = null;
which = 0;
vesion = 0;
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Window window = getWindow();
requestWindowFeature(1);
window.setFlags(AccessibilityNodeInfoCompat.ACTION_NEXT_HTML_ELEMENT, AccessibilityNodeInfoCompat.ACTION_NEXT_HTML_ELEMENT);
setContentView(R.layout.activity_main);
bindView();
init();
addListener();
}
protected void onResume() {
super.onResume();
}
private void bindView() {
this.surfaceView = (SurfaceView) findViewById(R.id.camerapreview);
this.flash_btn = (ImageView) findViewById(R.id.flash);
this.capt_btn = (ImageView) findViewById(R.id.capture);
this.turn_btn = (ImageView) findViewById(R.id.turn);
this.zoomSeekBar = (SeekBar) findViewById(R.id.zoom_seekbar);
this.greenSeekbar = (VerticalSeekBar) findViewById(R.id.sbGreen);
this.list_btn = (ImageView) findViewById(R.id.list);
}
private void init() {
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
this.screenHeight = metrics.heightPixels;
this.screenWidth = metrics.widthPixels;
this.surfaceHolder = this.surfaceView.getHolder();
this.surfaceHolder.addCallback(this);
this.surfaceHolder.setType(3);
try {
this.brightness = System.getInt(getContentResolver(), "screen_brightness");
this.currBrightness = this.brightness;
} catch (Exception e) {
Log.m0d("TAG", "Cannot access system brightness");
e.printStackTrace();
}
this.greenSeekbar.setMax(220);
this.greenSeekbar.setProgress(100);
this.surfaceView.setBackgroundColor(Color.argb(100, 0, MotionEventCompat.ACTION_MASK, 0));
}
private void addListener() {
this.flash_btn.setOnClickListener(this);
this.capt_btn.setOnClickListener(this);
this.turn_btn.setOnClickListener(this);
this.list_btn.setOnClickListener(this);
this.zoomSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// TODO Auto-generated method stub
Custom_CameraActivity.this.zoomTo(progress, false);
}
});
this.greenSeekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// TODO Auto-generated method stub
Custom_CameraActivity.this.surfaceView.setBackgroundColor(Color.argb(progress, 0, MotionEventCompat.ACTION_MASK, 0));
}
});
}
private void screenBrightness(double newBrightnessValue) {
LayoutParams lp = getWindow().getAttributes();
lp.screenBrightness = ((float) newBrightnessValue) / 255.0f;
getWindow().setAttributes(lp);
}
#SuppressWarnings("deprecation")
public void onClick(View v) {
switch (v.getId()) {
case R.id.turn:
turn();
case R.id.capture:
camera.takePicture(null, null, this.mPicture);
case R.id.flash:
this.hasFlash = getApplicationContext().getPackageManager().hasSystemFeature("android.hardware.camera.flash");
if (this.hasFlash) {
Parameters p = camera.getParameters();
if (this.isLighOn) {
p.setFlashMode("off");
camera.setParameters(p);
flash_btn.setBackgroundResource(R.drawable.ic_off);
camera.stopPreview();
camera.startPreview();
this.isLighOn = false;
return;
}
p.setFlashMode("torch");
camera.setParameters(p);
flash_btn.setBackgroundResource(R.drawable.ic_on);
camera.startPreview();
this.isLighOn = true;
return;
}
AlertDialog alert = new AlertDialog.Builder(this).create();
alert.setTitle(getResources().getString(R.string.txt_dialogFlashTitle));
alert.setMessage(getResources().getString(R.string.txt_dialogFlashMsg));
alert.setButton(getResources().getString(R.string.txt_dialogFlashBtnOk), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
alert.show();
case R.id.list:
startActivity(new Intent(this, MySavedPics.class));
default:
}
}
void setCameraDisplayOrientation(Activity activity, int cameraId, Camera camera) {
if (camera != null) {
int result;
CameraInfo info = new CameraInfo();
int degrees = 0;
switch (activity.getWindowManager().getDefaultDisplay().getRotation()) {
case 0:
degrees = 0;
break;
case 1:
degrees = 90;
break;
case 2:
degrees = 180;
break;
case 3:
degrees = 270;
break;
}
if (info.facing == 1) {
result = (360 - ((info.orientation + degrees) % 360)) % 360;
} else {
result = ((info.orientation - degrees) + 360) % 360;
}
camera.setDisplayOrientation(result);
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if (this.previewing) {
camera.stopPreview();
this.previewing = false;
}
Parameters parameters = camera.getParameters();
if (camera != null) {
try {
camera.setPreviewDisplay(this.surfaceHolder);
camera.startPreview();
this.previewing = true;
if (parameters.isZoomSupported()) {
this.max_zoom_factor = parameters.getMaxZoom();
this.zoomSeekBar.setMax(this.max_zoom_factor);
this.zoomSeekBar.setProgress(this.zoom_factor);
this.zoomSeekBar.setVisibility(0);
return;
}
this.zoomSeekBar.setVisibility(8);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void surfaceCreated(SurfaceHolder holder) {
try {
if (vesion == 1) {
Camera.open(which);
} else {
camera = Camera.open();
}
} catch (Exception e) {
camera.release();
}
try {
Parameters parameters = camera.getParameters();
if (getResources().getConfiguration().orientation != 2) {
parameters.set("orientation", "portrait");
camera.setDisplayOrientation(90);
parameters.setRotation(90);
} else {
parameters.set("orientation", "landscape");
camera.setDisplayOrientation(0);
parameters.setRotation(0);
}
camera.setParameters(parameters);
camera.setPreviewDisplay(this.surfaceHolder);
} catch (IOException e2) {
camera.release();
}
camera.startPreview();
}
public void surfaceDestroyed(SurfaceHolder arg0) {
camera.stopPreview();
camera.release();
camera = null;
vesion = 0;
this.previewing = false;
}
public void zoomTo(int new_zoom_factor, boolean update_seek_bar) {
Log.m0d("TAG", "ZoomTo(): " + new_zoom_factor);
if (new_zoom_factor < 0) {
new_zoom_factor = 0;
}
if (new_zoom_factor > this.max_zoom_factor) {
new_zoom_factor = this.max_zoom_factor;
}
if (new_zoom_factor != this.zoom_factor && camera != null) {
Parameters parameters = camera.getParameters();
if (parameters.isZoomSupported()) {
Log.m0d("TAG", "zoom was: " + parameters.getZoom());
parameters.setZoom(new_zoom_factor);
try {
camera.setParameters(parameters);
this.zoom_factor = new_zoom_factor;
if (update_seek_bar) {
this.zoomSeekBar.setProgress(this.max_zoom_factor - this.zoom_factor);
}
} catch (RuntimeException e) {
e.printStackTrace();
}
}
}
}
public void turn() {
if (VERSION.SDK_INT <= 9) {
AlertDialog.Builder ab1 = new AlertDialog.Builder(this);
ab1.setTitle(getResources().getString(R.string.txt_dialogTurnTitlesec));
ab1.setMessage(getResources().getString(R.string.txt_dialogTurnMsgsec));
ab1.setCancelable(false);
ab1.setPositiveButton(getResources().getString(R.string.txt_dialogTurnBtnOksec), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}).show();
//9967559972
} else if (Camera.getNumberOfCameras() >= 2) {
vesion = 1;
camera.stopPreview();
camera.release();
switch (which) {
case 0:
camera = Camera.open(1);
this.flash_btn.setEnabled(false);
camera.setDisplayOrientation(90);
which = 1;
break;
case 1:
camera = Camera.open(0);
this.flash_btn.setEnabled(true);
camera.setDisplayOrientation(90);
which = 0;
break;
}
try {
camera.setPreviewDisplay(this.surfaceHolder);
camera.setPreviewCallback(null);
camera.startPreview();
} catch (IOException e) {
camera.release();
camera = null;
}
} else {
vesion = 0;
AlertDialog.Builder ab = new AlertDialog.Builder(this);
ab.setTitle(getResources().getString(R.string.txt_dialogTurnTitle));
ab.setMessage(getResources().getString(R.string.txt_dialogTurnMsg));
ab.setCancelable(false);
ab.setPositiveButton(getResources().getString(R.string.txt_dialogTurnBtnOk), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}).show();
}
}
public void joinBitmap() {
this.surfaceView.setBackgroundColor(-16711936);
this.surfaceView.setDrawingCacheEnabled(true);
this.surfaceView.buildDrawingCache();
this.surfaceView.refreshDrawableState();
new Thread() {
public void run() {
try {
Custom_CameraActivity.this.surfaceBitmap = Custom_CameraActivity.this.surfaceView.getDrawingCache();
if (Custom_CameraActivity.this.surfaceBitmap != null) {
File pictureFile = Custom_CameraActivity.getOutputMediaFile();
if (pictureFile != null) {
Bitmap finalbitmap = Custom_CameraActivity.overlay(Custom_CameraActivity.this.cameraBitmap, Custom_CameraActivity.this.surfaceBitmap, Custom_CameraActivity.this.greenSeekbar.getProgress() + 15);
if (pictureFile.exists()) {
pictureFile.delete();
}
try {
FileOutputStream out = new FileOutputStream(pictureFile);
finalbitmap.compress(CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
} catch (IOException e2) {
}
Custom_CameraActivity.this.handler.sendEmptyMessage(1);
return;
}
return;
}
Custom_CameraActivity.this.handler.sendEmptyMessage(0);
} catch (Exception e3) {
}
}
}.start();
}
public static Bitmap getResizedBitmap(Bitmap bitmap, int newHeight, int newWidth) {
Bitmap dest = null;
try {
int sourceWidth = bitmap.getWidth();
int sourceHeight = bitmap.getHeight();
float scale = Math.min(((float) sourceWidth) / ((float) newWidth), ((float) sourceHeight) / ((float) newHeight));
float scaledWidth = ((float) sourceWidth/ scale);
float scaledHeight = ((float) sourceHeight/ scale);
dest = Bitmap.createBitmap(Bitmap.createScaledBitmap(bitmap, (int) scaledWidth, (int) scaledHeight, true), (int) ((scaledWidth - ((float) newWidth)) / 2.0f), (int) ((scaledHeight - ((float) newHeight)) / 2.0f), newWidth, newHeight);
} catch (Exception e) {
}
return dest;
}
public static Bitmap overlay(Bitmap bitmap1, Bitmap bitmapOverlay, int opacity) {
Bitmap resultBitmap = Bitmap.createBitmap(bitmapOverlay.getWidth(), bitmapOverlay.getHeight(), Config.ARGB_8888);
Canvas c = new Canvas(resultBitmap);
c.drawBitmap(bitmap1, 0.0f, 0.0f, null);
Paint p = new Paint();
p.setAlpha(opacity);
c.drawBitmap(bitmapOverlay, 0.0f, 0.0f, p);
return resultBitmap;
}
#SuppressLint({"SimpleDateFormat"})
private static File getOutputMediaFile() {
File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), "Night Vision Camera");
if (mediaStorageDir.exists() || mediaStorageDir.mkdirs()) {
return new File(mediaStorageDir.getPath() + File.separator + "IMG_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".jpg");
}
Log.m0d("Night Vision Camera", "failed to create directory");
return null;
}
}
I followed tutorial from this link-> http://android-er.blogspot.com/2015/02/create-audio-visualizer-for-mediaplayer.html
where graphics is done by extending view class.Now i am trying to do the same with surface view .Here`s the code:
MainActivity:
public class MainActivity extends Activity {
VisualizerView mVisualizerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mVisualizerView= new VisualizerView(this);
setContentView(mVisualizerView);
}
#Override
protected void onPause(){
super.onPause();
if(isFinishing()){
mVisualizerView.clean();
}
}}
Sufaceview class:
public class VisualizerView extends SurfaceView implements SurfaceHolder.Callback {
private byte[] mBytes;
private float[] mPoints;
private Rect mRect = new Rect();
private Paint mForePaint = new Paint();
SurfaceThread _thread;
private MediaPlayer player;
private Visualizer visualizer;
private Context context;
public VisualizerView(Context context) {
super(context);
init();
getHolder().addCallback(this);
_thread = new SurfaceThread(getHolder(), this);
this.context=context;
}
private void init(){
mBytes = null;
mForePaint.setStrokeWidth(1f);
mForePaint.setAntiAlias(true);
mForePaint.setColor(Color.rgb(0,0, 255));
}
public void updateVisualizer(byte[] bytes) {
mBytes = bytes;
// invalidate();
}
private void initAudio(){
player= MediaPlayer.create(context, R.raw.duck);
setupVisualizerFxAndUI();
visualizer.setEnabled(true);
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener(){
public void onCompletion(MediaPlayer mediaPlayer){
visualizer.setEnabled(false);
}
}
);
player.start();
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mBytes == null) {
return;
}
if (mPoints == null || mPoints.length < mBytes.length * 4) {
mPoints = new float[mBytes.length * 4];
}
mRect.set(0, 0, getWidth(), getHeight());
for (int i = 0; i < mBytes.length - 1; i++) {
mPoints[i * 4] = mRect.width() * i / (mBytes.length - 1);
mPoints[i * 4 + 1] = mRect.height() / 2
+ ((byte) (mBytes[i] + 128)) * (mRect.height() / 2) / 128;
mPoints[i * 4 + 2] = mRect.width() * (i + 1) / (mBytes.length - 1);
mPoints[i * 4 + 3] = mRect.height() / 2
+ ((byte) (mBytes[i + 1] + 128)) * (mRect.height() / 2)
/ 128;
}
canvas.drawColor(Color.WHITE);
canvas.drawLines(mPoints, mForePaint);
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
_thread.setRunning(true);
_thread.start();
initAudio();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
boolean retry = true;
_thread.setRunning(false);
while (retry) {
try {
_thread.join();
retry = false;
} catch (InterruptedException e) {
// we will try it again and again...
}
}
}
public void clean(){
if(player!=null){
visualizer.release();
player.release();
player= null;
}
}
private void setupVisualizerFxAndUI(){
Equalizer mEqualizer = new Equalizer(0, player.getAudioSessionId());
mEqualizer.setEnabled(false);
visualizer =new Visualizer(player.getAudioSessionId());
visualizer.setCaptureSize(Visualizer.getCaptureSizeRange()[1]);
visualizer.setDataCaptureListener(new Visualizer.OnDataCaptureListener() {
#Override
public void onWaveFormDataCapture(Visualizer visualizer, byte[] waveform,
int samplingRate) {
// TODO Auto-generated method stub
updateVisualizer(waveform);
}
#Override
public void onFftDataCapture(Visualizer visualizer, byte[] fft,
int samplingRate) {
// TODO Auto-generated method stub
}
},Visualizer.getMaxCaptureRate()/2,true,false) ;
// Log.d(Tag,String.valueOf(Visualizer.getMaxCaptureRate()));
}}
Thread class:
public class SurfaceThread extends Thread {
private SurfaceHolder surfaceHolder;
private VisualizerView panel;
private boolean run = false;
public SurfaceThread(SurfaceHolder surfaceHolder, VisualizerView panel) {
this. surfaceHolder = surfaceHolder;
this. panel = panel;
}
public void setRunning(boolean run) {
this.run = run;
}
#Override
public void run() {
Canvas c;
while (run) {
c = null;
try {
c = surfaceHolder.lockCanvas(null);
synchronized (surfaceHolder) {
panel.onDraw(c);
}
} finally {
// do this in a finally so that if an exception is thrown
// during the above, we don't leave the Surface in an
// inconsistent state
if (c != null) {
surfaceHolder.unlockCanvasAndPost(c);
}
}
}
}}
Now problem is that app will crash after running it twice.I know that i am
not passing data correctly from:
public void onWaveFormDataCapture(Visualizer visualizer, byte[] waveform,
int samplingRate) {
// TODO Auto-generated method stub
updateVisualizer(waveform);
}
So, how do i manage it ?
Also i am confused in which thread visualizer/mediaplayer is running and where should it go?
Does anyone have an idea what would cause the below error?
queueBuffer: error queuing buffer to SurfaceTexture, -32
I'm using SurfaceTexture in my app. The above error occurs when I try to set as
a livewallpaper
Below is the code:
public class ClockWallpaperService extends WallpaperService {
private WallpaperEngine myEngine;
public void onCreate() {
super.onCreate();
}
#Override
public Engine onCreateEngine() {
System.out.println("Service: onCreateEngine");
this.myEngine = new WallpaperEngine();
return myEngine;
}
public void onDestroy() {
this.myEngine = null;
super.onDestroy();
}
private class WallpaperEngine extends Engine implements OnGestureListener,
OnSharedPreferenceChangeListener {
public Bitmap image1, backgroundImage;
private ArrayList<Leaf> leafList;
private Bitmap bitmap1;
private Bitmap bitmap2;
private Bitmap bitmap3;
private Bitmap currentBackgroundBitmap;
private Paint paint;
private int count;
private int heightOfCanvas;
private int widthOfCanvas;
private float touchX;
private float touchY;
private int interval;
private int amount;
private boolean fallingDown;
private float bgX = 0;
private String colorFlag;
private String backgroundFlag;
private Random rand;
private GestureDetector detector;
private static final int DRAW_MSG = 0;
private static final int MAX_SIZE = 101;
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case DRAW_MSG:
drawPaper();
break;
}
}
};
/** hands colors for hour, min, sec */
private int[] colors = { 0xFFFF0000, 0xFF0000FF, 0xFFA2BC13 };
// private int bgColor;
private int width;
private int height;
private boolean visible = true;
private boolean displayHandSec;
private AnalogClock clock;
private SharedPreferences prefs;
WallpaperEngine() {
// get the fish and background image references
backgroundImage = BitmapFactory.decodeResource(getResources(),
R.drawable.bg1);
SharedPreferences sp = getSharedPreferences("back_position",
Activity.MODE_PRIVATE);
int position = sp.getInt("back_position", 1);
Global.backgroundDial = BitmapFactory.decodeResource(
getResources(), Global.BackgroundId[position]);
prefs = PreferenceManager
.getDefaultSharedPreferences(ClockWallpaperService.this);
prefs.registerOnSharedPreferenceChangeListener(this);
displayHandSec = prefs.getBoolean(
SettingsActivity.DISPLAY_HAND_SEC_KEY, true);
paint = new Paint();
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(5);
// bgColor = Color.parseColor("#C0C0C0");
clock = new AnalogClock(getApplicationContext());
}
#Override
public void onCreate(SurfaceHolder surfaceHolder) {
// TODO Auto-generated method stub
super.onCreate(surfaceHolder);
System.out.println("Engine: onCreate");
this.leafList = new ArrayList<Leaf>();
this.bitmap1 = BitmapFactory.decodeResource(getResources(),
R.drawable.flower1);
this.bitmap2 = BitmapFactory.decodeResource(getResources(),
R.drawable.flower2);
this.bitmap3 = BitmapFactory.decodeResource(getResources(),
R.drawable.flower3);
this.paint = new Paint();
this.paint.setAntiAlias(true);
this.count = -1;
this.rand = new Random();
this.detector = new GestureDetector(this);
this.touchX = -1.0f;
this.touchY = -1.0f;
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(ClockWallpaperService.this);
pref.registerOnSharedPreferenceChangeListener(this);
String speedStr = pref.getString("leaf_falling_speed", "20");
String amountStr = pref.getString("leaf_number", "50");
this.interval = Integer.parseInt(speedStr);
this.amount = Integer.parseInt(amountStr);
this.colorFlag = pref.getString("leaf_color", "0");
this.backgroundFlag = pref.getString("paper_background", "0");
String directionFlag = pref.getString("leaf_moving_direction", "0");
if (directionFlag.equals("0")) {
this.fallingDown = true;
} else {
this.fallingDown = false;
}
this.setTouchEventsEnabled(true);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
System.out.println("Engine: onDestroy");
this.mHandler.removeMessages(DRAW_MSG);
PreferenceManager.getDefaultSharedPreferences(
ClockWallpaperService.this)
.unregisterOnSharedPreferenceChangeListener(this);
super.onDestroy();
}
#Override
public void onSurfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
// TODO Auto-generated method stub
this.width = width;
this.height = height;
super.onSurfaceChanged(holder, format, width, height);
}
#Override
public void onSurfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
super.onSurfaceCreated(holder);
System.out.println("Engine: onSurfaceCreate");
Canvas canvas = holder.lockCanvas();
this.heightOfCanvas = canvas.getHeight();
this.widthOfCanvas = canvas.getWidth();
System.out.println("Width = " + widthOfCanvas + ", Height = "
+ heightOfCanvas);
holder.unlockCanvasAndPost(canvas);
this.mHandler.sendEmptyMessage(DRAW_MSG);
}
#Override
public void onSurfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
System.out.println("Engine: onSurfaceDestroyed");
this.mHandler.removeMessages(DRAW_MSG);
if (this.currentBackgroundBitmap != null) {
this.currentBackgroundBitmap.recycle();
this.currentBackgroundBitmap = null;
}
if (this.bitmap1 != null) {
this.bitmap1.recycle();
this.bitmap1 = null;
}
if (this.bitmap2 != null) {
this.bitmap2.recycle();
this.bitmap2 = null;
}
if (this.bitmap3 != null) {
this.bitmap3.recycle();
this.bitmap3 = null;
}
super.onSurfaceDestroyed(holder);
}
#Override
public void onOffsetsChanged(float xOffset, float yOffset,
float xOffsetStep, float yOffsetStep, int xPixelOffset,
int yPixelOffset) {
super.onOffsetsChanged(xOffset, yOffset, xOffsetStep, yOffsetStep,
xPixelOffset, yPixelOffset);
System.out.println("xPixelOffset: " + xPixelOffset
+ ", yPixelOffset: " + yPixelOffset);
this.bgX = xPixelOffset;
}
private void drawPaper() {
count++;
if (count >= 10000) {
count = 0;
}
if (count % 10 == 0) {
if (this.leafList.size() < MAX_SIZE) {
Leaf l = null;
Bitmap temp = bitmap1;
if (colorFlag.equals("0")) {
int index = rand.nextInt(3) + 1;
switch (index) {
case 1:
temp = bitmap1;
break;
case 2:
temp = bitmap2;
break;
case 3:
temp = bitmap3;
break;
default:
temp = bitmap1;
break;
}
} else if (colorFlag.equals("1")) {
temp = bitmap1;
} else if (colorFlag.equals("2")) {
temp = bitmap2;
} else if (colorFlag.equals("3")) {
temp = bitmap3;
}
l = new Leaf(temp, this.heightOfCanvas, this.widthOfCanvas);
this.leafList.add(l);
}
}
SurfaceHolder holder = this.getSurfaceHolder();
Canvas canvas = holder.lockCanvas();
drawBackground(canvas);
int size = Math.min(this.amount, this.leafList.size());
for (int i = 0; i < size; i++) {
Leaf l = this.leafList.get(i);
if (l.isTouched()) {
l.handleTouched(touchX, touchY);
} else {
l.handleFalling(this.fallingDown);
}
l.drawLeaf(canvas, paint);
}
holder.unlockCanvasAndPost(canvas);
this.mHandler.sendEmptyMessageDelayed(DRAW_MSG, this.interval);
}
private void drawBackground(Canvas c) {
c.drawBitmap(backgroundImage, 0, 0, null);
clock.config(width / 2, height / 2, (int) (width * 0.6f),
new Date(), paint, colors, displayHandSec);
clock.draw(c);
}
#Override
public void onTouchEvent(MotionEvent event) {
super.onTouchEvent(event);
this.detector.onTouchEvent(event);
}
public boolean onDown(MotionEvent e) {
touchX = e.getX();
touchY = e.getY();
int size = Math.min(this.amount, this.leafList.size());
for (int i = 0; i < size; i++) {
Leaf l = this.leafList.get(i);
float centerX = l.getX() + l.getBitmap().getWidth() / 2.0f;
float centerY = l.getY() + l.getBitmap().getHeight() / 2.0f;
if (!l.isTouched()) {
if (Math.abs(centerX - touchX) <= 80
&& Math.abs(centerY - touchY) <= 80
&& centerX != touchX) {
l.setTouched(true);
}
}
}
return true;
}
public void onShowPress(MotionEvent e) {
}
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
return false;
}
public void onLongPress(MotionEvent e) {
}
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
return false;
}
public void onSharedPreferenceChanged(
SharedPreferences sharedPreferences, String key) {
if (key.equals("leaf_falling_speed")) {
String speedStr = sharedPreferences.getString(key, "20");
this.interval = Integer.parseInt(speedStr);
} else if (key.equals("leaf_number")) {
String amountStr = sharedPreferences.getString(key, "50");
this.amount = Integer.parseInt(amountStr);
} else if (key.equals("leaf_moving_direction")) {
String directionFlag = sharedPreferences.getString(key, "0");
if (directionFlag.equals("0")) {
this.fallingDown = true;
} else {
this.fallingDown = false;
}
} else if (key.equals("leaf_color")) {
this.colorFlag = sharedPreferences.getString(key, "0");
this.leafList.removeAll(leafList);
}
}
}
}
I'm doing an android application where I have to move different images. I have done some coding, but the problem is : when I want to move ONE image, the others follow with it. Is it possible to make different an on touch listener for each images on a bitmap??
MyBringBackSurface ourSurfaceView, ourSurfaceView2;
float x, y, sX, sY, fX, fY, dX, dY, aniX, aniY, scaledX, scaledY;
Bitmap test;
Bitmap dress, dress2;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
ourSurfaceView = new MyBringBackSurface(this);
ourSurfaceView.setOnTouchListener(this);
x = 0;
y = 0;
sX = 0;
sY = 0;
fX = 0;
fY = 0;
dX = dY = aniX = aniY = scaledX = scaledY = 0;
dress = BitmapFactory.decodeResource(getResources(), R.drawable.dress);
dress2 = BitmapFactory
.decodeResource(getResources(), R.drawable.dress2);
test = BitmapFactory.decodeResource(getResources(),
R.drawable.cinderelladoll);
setContentView(ourSurfaceView);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
ourSurfaceView.pause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
ourSurfaceView.resume();
}
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
x = event.getX();
y = event.getY();
sX = event.getX();
sY = event.getY();
return true;
}
public class MyBringBackSurface extends SurfaceView implements Runnable {
SurfaceHolder ourHolder;
Thread ourThread = null;
boolean isRunning = false;
Bitmap back;
public MyBringBackSurface(Context context) {
super(context);
ourHolder = getHolder();
back = BitmapFactory.decodeResource(getResources(),
R.drawable.wallpaper);
}
public void pause() {
isRunning = false;
while (true) {
try {
ourThread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
ourThread = null;
}
public void resume() {
isRunning = true;
ourThread = new Thread(this);
ourThread.start();
}
#Override
public void run() {
// TODO Auto-generated method stub
while (isRunning) {
if (!ourHolder.getSurface().isValid())
continue;
Canvas canvas = ourHolder.lockCanvas();
canvas.drawRGB(02, 02, 150);
canvas.drawBitmap(back, 0, 0, null);
if (x != 0 && y != 0) {
canvas.drawBitmap(test, 150, 150, null);
canvas.drawBitmap(dress2, x - (dress2.getWidth() / 2), y
- (dress2.getHeight() / 2), null);
canvas.drawBitmap(dress, x - (dress.getWidth() / 2), y
- (dress.getHeight() / 2), null);
}
ourHolder.unlockCanvasAndPost(canvas);
}
}
}
}
guys. I'm playing around with making my very first Android game, but stumbled into a problem. The framerate seems to have random lag spikes. If I comment the background(s) out the framerate gets much smoother. I've looked around SO and can't find anything to solve my problems. I have a feeling it has something to do with allocating a specific amount of time every time I draw, but I don't know how to properly implement such a feature. Any suggestions? Btw, tryed hardware ac, anti etc.
This is the class that starts the surfaceview :
package com.example.glassrunner;
Imports Here
public class Game extends Activity
{
MySurfaceView mySurfaceView;
public SoundPool spool;
private int soundID;
int length=0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
mySurfaceView = new MySurfaceView(this);
setContentView(mySurfaceView);
}
#Override
protected void onResume()
{
// TODO Auto-generated method stub
super.onResume();
mySurfaceView.onResumeMySurfaceView();
}
#Override
protected void onPause()
{
// TODO Auto-generated method stub
super.onPause();
mySurfaceView.onPauseMySurfaceView();
}
#Override
protected void onDestroy()
{
super.onDestroy();
mySurfaceView = null;
}
}
This is the surfaceview class :
package com.example.glassrunner;
Imports here
public class MySurfaceView extends SurfaceView implements Runnable
{
public static boolean gameOver = false;
SurfaceHolder surfaceHolder;
Thread thread = null;
public Integer score=0;
public SoundPool spool;
private int soundID;
int length=0;
public static MediaPlayer mp;
volatile boolean running = false;
int Yposition = 450;
int Xposition = 50;
Paint textPaint;
long mLastTime;
Bitmap background;
Bitmap background2;
Bitmap lines;
Bitmap runSprite;
Bitmap box;
Paint bitmapPaint ;
Paint textPaint2;
Bitmap scaledBackground ;
Bitmap scaledBackground2 ;
Bitmap scaledLines ;
Bitmap scaledBox;
Canvas canvas;
Paint paint;
int SpX=0;
int SpY=0;
Bitmap[][] sprite;
/** Variables for the counter */
int frameSamplesCollected = 0;
int frameSampleTime = 0;
int fps = 0;
int speed = 5;
Toast GameOverToast;
Context context;
MediaPlayer mMediaPlayer;
public MySurfaceView(Context context)
{
super(context);
this.context = context;
// TODO Auto-generated constructor stub
surfaceHolder = getHolder();
surfaceHolder.setFormat(PixelFormat.RGB_565);
CharSequence text = "Game Over!";
int duration = Toast.LENGTH_SHORT;
GameOverToast = Toast.makeText(context, text, duration);
spool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
soundID = spool.load(context, R.raw.jump, 1);
mp = MediaPlayer.create(context, R.raw.saturdaymorningfunk);
initialization();
}
public void initialization()
{
mp.setLooping(true);
mp.start();
Options options = new Options();
options.inSampleSize = 1/4;
options.inPreferredConfig = Bitmap.Config.RGB_565;
background=BitmapFactory.decodeResource(getResources(),R.drawable.background,options);
lines=BitmapFactory.decodeResource(getResources(),R.drawable.lines);// getting the png from drawable folder
background2=BitmapFactory.decodeResource(getResources(),R.drawable.background2,options);
runSprite=BitmapFactory.decodeResource(getResources(),R.drawable.runsprite);
box=BitmapFactory.decodeResource(getResources(),R.drawable.box);
bitmapPaint = new Paint(Paint.ANTI_ALIAS_FLAG); // tool for painting on the canvas
bitmapPaint.setAntiAlias(true);
bitmapPaint.setFilterBitmap(true);
textPaint = new Paint();
textPaint.setColor(Color.RED);
textPaint.setTextSize(32);
textPaint2 = new Paint();
textPaint2.setColor(Color.BLUE);
textPaint2.setTextSize(50);
scaledBackground = Bitmap.createScaledBitmap(background, 2560, 500, true);
scaledBackground2 = Bitmap.createScaledBitmap(background2, 2560, 400, true);
scaledLines = Bitmap.createScaledBitmap(lines, 2560, 30, true);
runSprite = Bitmap.createScaledBitmap(runSprite, 1400, 1000, true);
scaledBox = Bitmap.createScaledBitmap(box, 100, 100, true);
sprite = new Bitmap[4][7];
for(int row=0;row<=3;row++)
{
for(int col=0;col<=6;col++)
{
sprite[row][col] = Bitmap.createBitmap(runSprite, SpX, SpY, 200, 250);
SpX+=200;
}
SpX=0;
SpY+=250;
}
}
public void onResumeMySurfaceView()
{
mp.seekTo(length);
mp.start();
running = true;
thread = new Thread(this);
thread.start();
}
public void onPauseMySurfaceView()
{
mp.pause();
length=mp.getCurrentPosition();
boolean retry = true;
running = false;
while(retry){
try {
thread.join();
retry = false;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void onDestroyMySurfaceView()
{
mp.stop();
running = false;
thread = null;
thread.stop();
}
private void fps()
{
long now = System.currentTimeMillis();
if (mLastTime != 0)
{
//Time difference between now and last time we were here
int time = (int) (now - mLastTime);
frameSampleTime += time;
frameSamplesCollected++;
//After 10 frames
if (frameSamplesCollected == 10)
{
//Update the fps variable
fps = (int) (10000 / frameSampleTime);
//Reset the sampletime + frames collected
frameSampleTime = 0;
frameSamplesCollected = 0;
}
}
mLastTime = now;
}
public boolean pressDown = false;
public long pressTime;
public boolean onTouchEvent(MotionEvent event)
{
if (event != null)
{
if (event.getAction() == MotionEvent.ACTION_DOWN)
{ if(Yposition == orgPos)
{
spool.play(soundID, 15, 15, 1, 0, 1f);
pressDown = true;
pressTime = System.currentTimeMillis();
}
}else if (event.getAction() == MotionEvent.ACTION_UP)
{
pressDown = false;
}
}
return true;
}
int x=0;
int y=100;
int x2=0;
int y2=20;
int row=0;
int col=0;
int limit = 100;
int orgPos = 450;
int Xbox = 1280;
int Ybox = 580;
Random r = new Random();
int RBox;
public static String Fscore;
boolean onTop = false;
long now;
long start;
long stop;
long time ;
int spritePosition = 0 ;
int spriteSize;
#Override
public void run()
{
while(running)
{
canvas = null;
if(surfaceHolder.getSurface().isValid())
{
canvas = surfaceHolder.lockCanvas();
fps(); // fps
// Update screen parameters
update();
draw();
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
public void update()
{
if(score<500)
{
speed = 7;
}
else if(score%500 == 0)
{
speed = 7 + (score / 500);
}
if(col==6)
{
row++;
col=0;
}
if(row==4)
{
row=0;
}
score++;
Fscore = score.toString();
if(x>-1280)
{
x-=speed;
}else if(x<=-1280)
{
x=0;
}
if(x2>-1280)
{
x2-=5;
}else if(x2<=-1280)
{
x2=-0;
}
RBox = r.nextInt(999)+1280;
if(Xbox > -100)
{
Xbox-=speed;
}else if(Xbox<=-100)
{
Xbox=RBox;
}
if( (Xposition + 200 == Xbox +40 )&&(Yposition + 250 > Ybox+20)||( Xposition+200<=Xbox+70)&&( Xposition+200>=Xbox+20)&&(Yposition + 250 > Ybox+30) ) // collision
{
GameOverToast.show();
running = false;
spool.release();
mp.release();
Looper.prepare();
Intent database = new Intent(context, MainHighscore.class);
database.putExtra("score", Fscore);
context.startActivity(database);
onDestroyMySurfaceView();
}
now = System.currentTimeMillis();
if(( now - pressTime) <= 600)
{
if(Yposition > limit)
{
Yposition -= 10;
}
}
onTop = false;
if((now - pressTime) >= 600 && (now - pressTime) <= 1200)
{
if(!(Yposition == orgPos))
{
if(Yposition+250 >= Ybox && Xposition+200>=Xbox+70 && Xposition <= Xbox+40)
{
onTop=true;
Yposition = 340;
}else
{
Yposition += 10;
}
}
}
if((now - pressTime) >= 1200)
{
if(Yposition < 450) Yposition +=10;
else Yposition = 450;
}
}
public void draw()
{
canvas.drawColor(Color.WHITE);
//canvas.drawBitmap(scaledBackground, x2,y2, bitmapPaint);
canvas.drawBitmap(scaledBackground2, x,y, bitmapPaint);
canvas.drawBitmap(scaledLines, x,650, bitmapPaint);
canvas.drawText(Fscore, 1050, 50, textPaint2);
canvas.drawText(fps + " fps", getWidth() / 2, getHeight() / 2, textPaint);
canvas.drawBitmap(sprite[row][col],Xposition,Yposition,bitmapPaint );
canvas.drawBitmap(scaledBox,Xbox,Ybox,bitmapPaint);
col++;
}
}
I think your problem might be actually the moving part. Your just drawing too much stuff, and the surfaceView is not meant for that.