Android: Shakelistener error - android

i have a shake listener as follows
public class ShakeListener implements SensorEventListener {
private String TAG = ShakeListener.class.getSimpleName();
private static final int FORCE_THRESHOLD = 800;
private static final int TIME_THRESHOLD = 100;
private static final int SHAKE_TIMEOUT = 500;
private static final int SHAKE_DURATION = 1000;
private static final int SHAKE_COUNT = 5;
private SensorManager mSensorMgr;
private float mLastX = -1.0f, mLastY = -1.0f, mLastZ = -1.0f;
private long mLastTime;
private OnShakeListener mShakeListener;
private Context mContext;
private int mShakeCount = 0;
private long mLastShake;
private long mLastForce;
public interface OnShakeListener {
public void onShake();
}
public ShakeListener(Context context) {
Log.d(TAG,"ShakeListener invoked---->");
mContext = context;
resume();
}
public void setOnShakeListener(OnShakeListener listener) {
mShakeListener = listener;
}
public void resume() {
mSensorMgr = (SensorManager) mContext
.getSystemService(Context.SENSOR_SERVICE);
if (mSensorMgr == null) {
throw new UnsupportedOperationException("Sensors not supported");
}
boolean supported = false;
try {
supported = mSensorMgr.registerListener(this,
mSensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_GAME);
} catch (Exception e) {
Toast.makeText(mContext, "Shaking not supported", Toast.LENGTH_LONG)
.show();
}
if ((!supported) && (mSensorMgr != null))
mSensorMgr.unregisterListener(this);
}
public void pause() {
if (mSensorMgr != null) {
mSensorMgr.unregisterListener(this);
mSensorMgr = null;
}
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER)
return;
long now = System.currentTimeMillis();
if ((now - mLastForce) > SHAKE_TIMEOUT) {
mShakeCount = 0;
}
if ((now - mLastTime) > TIME_THRESHOLD) {
long diff = now - mLastTime;
float speed = Math.abs(event.values[SensorManager.DATA_X]
+ event.values[SensorManager.DATA_Y]
+ event.values[SensorManager.DATA_Z] - mLastX - mLastY
- mLastZ)
/ diff * 10000;
if (speed > FORCE_THRESHOLD) {
if ((++mShakeCount >= SHAKE_COUNT)
&& (now - mLastShake > SHAKE_DURATION)) {
mLastShake = now;
mShakeCount = 0;
Log.d(TAG,"ShakeListener mShakeListener---->"+mShakeListener);
if (mShakeListener != null) {
mShakeListener.onShake();
}
}
mLastForce = now;
}
mLastTime = now;
mLastX = event.values[SensorManager.DATA_X];
mLastY = event.values[SensorManager.DATA_Y];
mLastZ = event.values[SensorManager.DATA_Z];
}}}
iam using this listener in one of my activity as ffollows
mShaker = new ShakeListener(this);
mShaker.setOnShakeListener(new ShakeListener.OnShakeListener () {
public void onShake()
{
Intent myIntent = new Intent(myActivity.this, loginActivity.class);
startActivity(myIntent);
}
});
this shake should trigger only when iam on that particular activity..but it s triggering in all activities ,worse part is even when i close the app if i shake, the event is triggering and making the app open..Any help is appreciated.

add this method in your activity:
#Override
protected void finalize() throws Throwable {
try {
stop();
} catch (Exception e){
e.printStackTrace();
}
super.finalize();
}
public void stop(){
try {
sensorMgr.unregisterListener(this, mAccelerometer);
} catch (Exception e){
e.printStackTrace();
}
}

Related

How to Crop the visible portion of landscape video in android?

I am working on Panning and cropping the landscape video using Texture View.I am in a half way that I can pan the landscape video from left to right vice versa by using this example
https://github.com/crust87/Android-VideoCropView.
FFMPEG can crop the particular portion of the video by using this command
ffmpeg -i /sdcard/videokit/in.mp4 -filter:v crop=720:1088:0:0 -c:a
copy /sdcard/videokit/out.mp4
How can I crop only the video which is visible in Texture View and save it local storage in Android.
crop=720:1088:0:0 is a hard coded width and height of the video and it is cropping fine.But how can I get the width and height of the visible video in Texture View to crop the visible video and Save it to the local storage in android.
public class MainActivity extends Activity {
// Layout Components
private FrameLayout top_frame;
// Attributes
private String originalPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.check);
top_frame = (FrameLayout)findViewById(R.id.top_frame);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1000 && resultCode == RESULT_OK) {
final VideoCropView mVideoCropView = new VideoCropView(this);
mVideoCropView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mVideoCropView.start();
}
});
top_frame.addView(mVideoCropView);
Uri selectedVideoUri = data.getData();
originalPath = getRealPathFromURI(selectedVideoUri);
mVideoCropView.setVideoURI(selectedVideoUri);
mVideoCropView.seekTo(1);
}
}
public void onButtonLoadClick(View v) {
top_frame.removeAllViews();
Intent lIntent = new Intent(Intent.ACTION_PICK);
lIntent.setType("video/*");
lIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivityForResult(lIntent, 1000);
}
public String getRealPathFromURI(Uri contentUri) { // getting image path from gallery.
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = getApplicationContext().getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
}
CropVideoView
public class VideoCropView extends TextureView implements MediaPlayerControl {
// Constants
private static final String LOG_TAG = "VideoCropView";
private static final int STATE_ERROR = -1;
private static final int STATE_IDLE = 0;
private static final int STATE_PREPARING = 1;
private static final int STATE_PREPARED = 2;
private static final int STATE_PLAYING = 3;
private static final int STATE_PAUSED = 4;
private static final int STATE_PLAYBACK_COMPLETED = 5;
// MediaPlayer Components
protected Context mContext;
private MediaPlayer mMediaPlayer;
private Surface mSurface;
private OnInfoListener mOnInfoListener;
private OnCompletionListener mOCompletionListener;
private OnErrorListener mOnErrorListener;
private OnPreparedListener mOnPreparedListener;
private OnTranslatePositionListener mOnTranslatePositionListener;
// CropView Components
private Matrix mMatrix;
// MediaPlayer Attributes
protected Uri mUri;
private int mCurrentBufferPercentage;
private int mSeekWhenPrepared;
protected int mVideoWidth;
protected int mVideoHeight;
// CropView Attributes
private float mRatioWidth;
private float mRatioHeight;
private float mPositionX;
private float mPositionY;
private float mBoundX;
private float mBoundY;
private int mRotate;
private float mScaleX;
private float mScaleY;
private float mScale;
// Working Variables
private int mCurrentState = STATE_IDLE;
private int mTargetState = STATE_IDLE;
// Touch Event
// past position x, y and move point
float mPastX;
float mPastY;
float mTouchDistance;
private Context context;
// Constructors
public VideoCropView(final Context context) {
super(context);
mContext = context;
initAttributes();
initVideoView();
}
public VideoCropView(final Context context, final AttributeSet attrs) {
super(context, attrs);
mContext = context;
initAttributes(context, attrs, 0);
initVideoView();
}
public VideoCropView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mContext = context;
initAttributes(context, attrs, defStyleAttr);
initVideoView();
}
private void initAttributes() {
mRatioWidth = 1;
mRatioHeight = 1;
}
private void initAttributes(Context context, AttributeSet attrs, int defStyleAttr) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.VideoCropView, defStyleAttr, 0);
mRatioWidth = typedArray.getInteger(R.styleable.VideoCropView_ratio_width, 3);
mRatioHeight = typedArray.getInteger(R.styleable.VideoCropView_ratio_height, 4);
}
#Override
protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
int heightLayout;
int widthLayout;
widthLayout = MeasureSpec.getSize(widthMeasureSpec);
heightLayout = MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(widthLayout, heightLayout);
/*if(widthMeasureSpec < heightMeasureSpec){
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = (int) ((width / mRatioWidth) * mRatioHeight);
setMeasuredDimension(width, height);
}else{
int width = MeasureSpec.getSize(widthMeasureSpec);
int height =MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(width, height);
}
*/
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if(mCurrentState == STATE_ERROR || mCurrentState == STATE_IDLE || mCurrentState == STATE_PREPARING) {
return false;
}
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mPastX = event.getX();
mPastY = event.getY();
mTouchDistance = 0;
case MotionEvent.ACTION_MOVE:
if(mBoundX!=0 || mBoundY!=0) {
float dx = event.getX() - mPastX;
float dy = event.getY() - mPastY;
updateViewPosition(dx, dy);
mPastX = event.getX();
mPastY = event.getY();
mTouchDistance += (Math.abs(dx) + Math.abs(dy));
}
break;
case MotionEvent.ACTION_UP:
if (mTouchDistance < 25) {
if (isPlaying()) {
pause();
} else {
start();
}
}
mTouchDistance = 0;
break;
}
return true;
}
#Override
public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
super.onInitializeAccessibilityEvent(event);
event.setClassName(VideoView.class.getName());
}
#Override
public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
super.onInitializeAccessibilityNodeInfo(info);
info.setClassName(VideoView.class.getName());
}
public int resolveAdjustedSize(int desiredSize, int measureSpec) {
Log.d(LOG_TAG, "Resolve called.");
int result = desiredSize;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
switch (specMode) {
case MeasureSpec.UNSPECIFIED:
/*
* Parent says we can be as big as we want. Just don't be larger
* than max size imposed on ourselves.
*/
result = desiredSize;
break;
case MeasureSpec.AT_MOST:
/*
* Parent says we can be as big as we want, up to specSize. Don't be
* larger than specSize, and don't be larger than the max size
* imposed on ourselves.
*/
result = Math.min(desiredSize, specSize);
break;
case MeasureSpec.EXACTLY:
// No choice. Do what we are told.
result = specSize;
break;
}
return result;
}
public void initVideoView() {
mVideoHeight = 0;
mVideoWidth = 0;
setFocusable(false);
setSurfaceTextureListener(mSurfaceTextureListener);
mCurrentState = STATE_IDLE;
mTargetState = STATE_IDLE;
}
public void setVideoPath(String path) {
if (path != null) {
setVideoURI(Uri.parse(path));
}
}
public void setVideoURI(Uri pVideoURI) {
mUri = pVideoURI;
mSeekWhenPrepared = 0;
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(mContext, pVideoURI);
// create thumbnail bitmap
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
String rotation = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION);
try {
mRotate = Integer.parseInt(rotation);
} catch(NumberFormatException e) {
mRotate = 0;
}
}
retriever.release();
openVideo();
requestLayout();
invalidate();
}
public void stopPlayback() {
if (mMediaPlayer != null) {
mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
mCurrentState = STATE_IDLE;
mTargetState = STATE_IDLE;
}
}
public void openVideo() {
if ((mUri == null) || (mSurface == null)) {
// not ready for playback just yet, will try again later
return;
}
// Tell the music playback service to pause
// TODO: these constants need to be published somewhere in the
// framework.
Intent intent = new Intent("com.android.music.musicservicecommand");
intent.putExtra("command", "pause");
mContext.sendBroadcast(intent);
// we shouldn't clear the target state, because somebody might have
// called start() previously
release(false);
try {
mMediaPlayer = new MediaPlayer();
// TODO: create SubtitleController in MediaPlayer, but we need
// a context for the subtitle renderers
mMediaPlayer.setOnPreparedListener(mPreparedListener);
mMediaPlayer.setOnVideoSizeChangedListener(mSizeChangedListener);
mMediaPlayer.setOnCompletionListener(mCompletionListener);
mMediaPlayer.setOnErrorListener(mErrorListener);
mMediaPlayer.setOnInfoListener(mInfoListener);
mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener);
mCurrentBufferPercentage = 0;
mMediaPlayer.setDataSource(mContext, mUri);
mMediaPlayer.setSurface(mSurface);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setScreenOnWhilePlaying(true);
mMediaPlayer.prepareAsync();
mMediaPlayer.setLooping(true);
mCurrentState = STATE_PREPARING;
} catch (IllegalStateException e) {
mCurrentState = STATE_ERROR;
mTargetState = STATE_ERROR;
e.printStackTrace();
} catch (IOException e) {
mCurrentState = STATE_ERROR;
mTargetState = STATE_ERROR;
e.printStackTrace();
}
}
private OnVideoSizeChangedListener mSizeChangedListener = new OnVideoSizeChangedListener() {
#Override
public void onVideoSizeChanged(final MediaPlayer mp, final int width,
final int height) {
mVideoWidth = mp.getVideoWidth();
mVideoHeight = mp.getVideoHeight();
if (mVideoWidth != 0 && mVideoHeight != 0) {
requestLayout();
if(mVideoWidth >= mVideoHeight)
initVideo();
}
}
};
private OnPreparedListener mPreparedListener = new OnPreparedListener() {
#Override
public void onPrepared(final MediaPlayer mp) {
mCurrentState = STATE_PREPARED;
if (mOnPreparedListener != null) {
mOnPreparedListener.onPrepared(mp);
}
mVideoWidth = mp.getVideoWidth();
mVideoHeight = mp.getVideoHeight();
int seekToPosition = mSeekWhenPrepared; // mSeekWhenPrepared may be
// changed after seekTo()
if (seekToPosition != 0) {
seekTo(seekToPosition);
}
if ((mVideoWidth != 0) && (mVideoHeight != 0)) {
if(mVideoWidth >= mVideoHeight) initVideo();
if (mTargetState == STATE_PLAYING) {
start();
}
} else {
// We don't know the video size yet, but should start anyway.
// The video size might be reported to us later.
if (mTargetState == STATE_PLAYING) {
start();
}
}
}
};
private OnCompletionListener mCompletionListener = new OnCompletionListener() {
#Override
public void onCompletion(final MediaPlayer mp) {
mCurrentState = STATE_PLAYBACK_COMPLETED;
mTargetState = STATE_PLAYBACK_COMPLETED;
if (mOCompletionListener != null) {
mOCompletionListener.onCompletion(mMediaPlayer);
}
}
};
private OnInfoListener mInfoListener = new OnInfoListener() {
public boolean onInfo(MediaPlayer mp, int arg1, int arg2) {
if (mOnInfoListener != null) {
mOnInfoListener.onInfo(mp, arg1, arg2);
}
return true;
}
};
private OnErrorListener mErrorListener = new OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int framework_err, int impl_err) {
Log.d(LOG_TAG, "Error: " + framework_err + "," + impl_err);
mCurrentState = STATE_ERROR;
mTargetState = STATE_ERROR;
/* If an error handler has been supplied, use it and finish. */
if (mOnErrorListener != null) {
if (mOnErrorListener.onError(mMediaPlayer, framework_err,
impl_err)) {
return true;
}
}
return true;
}
};
private OnBufferingUpdateListener mBufferingUpdateListener = new OnBufferingUpdateListener() {
#Override
public void onBufferingUpdate(final MediaPlayer mp, final int percent) {
mCurrentBufferPercentage = percent;
}
};
public void setOnPreparedListener(OnPreparedListener listener) {
mOnPreparedListener = listener;
}
public void setOnCompletionListener(OnCompletionListener listener) {
mOCompletionListener = listener;
}
public void setOnErrorListener(OnErrorListener listener) {
mOnErrorListener = listener;
}
public void setOnInfoListener(OnInfoListener listener) {
mOnInfoListener = listener;
}
private void release(boolean cleartargetstate) {
if (mMediaPlayer != null) {
mMediaPlayer.reset();
mMediaPlayer.release();
mMediaPlayer = null;
mCurrentState = STATE_IDLE;
if (cleartargetstate) {
mTargetState = STATE_IDLE;
}
}
}
#Override
public void start() {
if (isInPlaybackState()) {
mMediaPlayer.start();
mCurrentState = STATE_PLAYING;
}
mTargetState = STATE_PLAYING;
}
#Override
public void pause() {
if (isInPlaybackState()) {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
mCurrentState = STATE_PAUSED;
}
}
mTargetState = STATE_PAUSED;
}
#Override
public int getDuration() {
if (isInPlaybackState()) {
return mMediaPlayer.getDuration();
}
return -1;
}
#Override
public int getCurrentPosition() {
if (isInPlaybackState()) {
return mMediaPlayer.getCurrentPosition();
}
return 0;
}
#Override
public void seekTo(int msec) {
if (isInPlaybackState()) {
mMediaPlayer.seekTo(msec);
mSeekWhenPrepared = 0;
} else {
mSeekWhenPrepared = msec;
}
}
#Override
public boolean isPlaying() {
return isInPlaybackState() && mMediaPlayer.isPlaying();
}
#Override
public int getBufferPercentage() {
if (mMediaPlayer != null) {
return mCurrentBufferPercentage;
}
return 0;
}
private boolean isInPlaybackState() {
return (mMediaPlayer != null && mCurrentState != STATE_ERROR
&& mCurrentState != STATE_IDLE && mCurrentState != STATE_PREPARING);
}
#Override
public boolean canPause() {
return false;
}
#Override
public boolean canSeekBackward() {
return false;
}
#Override
public boolean canSeekForward() {
return false;
}
#Override
public int getAudioSessionId() {
return -1;
}
SurfaceTextureListener mSurfaceTextureListener = new SurfaceTextureListener() {
#Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
mSurface = new Surface(surface);
openVideo();
}
#Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
boolean isValidState = (mTargetState == STATE_PLAYING);
boolean hasValidSize = (mVideoWidth == width && mVideoHeight == height);
if (mMediaPlayer != null && isValidState && hasValidSize) {
start();
}
}
#Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
if (mMediaPlayer != null) {
mMediaPlayer.reset();
mMediaPlayer.release();
mMediaPlayer = null;
}
if (mSurface != null) {
mSurface.release();
mSurface = null;
}
return true;
}
#Override
public void onSurfaceTextureUpdated(final SurfaceTexture surface) {
}
};
#Override
protected void onVisibilityChanged(View changedView, int visibility) {
super.onVisibilityChanged(changedView, visibility);
if (visibility == View.INVISIBLE || visibility == View.GONE) {
if (isPlaying()) {
stopPlayback();
}
}
}
public float getScale() {
return mScale;
}
private void initVideo() {
try {
int width = getWidth();
int height = getHeight();
mScaleX = 1.0f;
mScaleY = 1.0f;
mPositionX = 0;
mPositionY = 0;
mBoundX = 0;
mBoundY = 0;
mMatrix = new Matrix();
mScaleX = (float) mVideoWidth / width;
mScaleY = (float) mVideoHeight / height;
mBoundX = width - mVideoWidth / mScaleY;
mBoundY = height - mVideoHeight / mScaleX;
if (mScaleX < mScaleY) {
mScale = mScaleX;
mScaleY = mScaleY * (1.0f / mScaleX);
mScaleX = 1.0f;
mBoundX = 0;
} else {
mScale = mScaleY;
mScaleX = mScaleX * (1.0f / mScaleY);
mScaleY = 1.0f;
mBoundY = 0;
}
mMatrix = new Matrix();
mMatrix.setScale(mScaleX, mScaleY);
setTransform(mMatrix);
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
public void updateViewPosition(float x, float y) {
float nextX = mPositionX + x;
float nextY = mPositionY + y;
if(mScaleX == 1.0f) {
x = 0;
} else {
if(nextX > 0) {
x = -mPositionX;
mPositionX = mPositionX + x;
} else if(nextX < mBoundX) {
x = mBoundX - mPositionX;
mPositionX = mPositionX + x;
} else {
mPositionX = nextX;
}
}
if(mScaleY == 1.0f) {
y = 0;
} else {
if(nextY > 0) {
y = -mPositionY;
mPositionY = mPositionY + y;
} else if(nextY < mBoundY) {
y = mBoundY - mPositionY;
mPositionY = mPositionY + y;
} else {
mPositionY = nextY;
}
}
if(mOnTranslatePositionListener != null) {
mOnTranslatePositionListener.onTranslatePosition(mPositionX, mPositionY, mPositionX * -mScale, mPositionY * -mScale);
}
mMatrix.postTranslate(x, y);
setTransform(mMatrix);
invalidate();
}
// public void setOriginalRatio() {
// if(mVideoWidth != 0 && mVideoHeight != 0) {
// int gcd = gcd(mVideoWidth, mVideoHeight);
// setRatio(mVideoWidth / gcd, mVideoHeight / gcd);
// }
// }
public int gcd(int n, int m) {
while (m != 0) {
int t = n % m;
n = m;
m = t;
}
return Math.abs(n);
}
// public void setRatio(float ratioWidth, float ratioHeight) {
// mRatioWidth = ratioWidth;
// mRatioHeight = ratioHeight;
//
// int seek = getCurrentPosition();
//
// requestLayout();
// invalidate();
// openVideo();
//
// seekTo(seek);
// }
public float getRatioWidth() {
return mRatioWidth;
}
public float getRatioHeight() {
return mRatioHeight;
}
public float getRealPositionX() {
return mPositionX * -mScale;
}
public float getRealPositionY() {
return mPositionY * -mScale;
}
public int getVideoWidth() {
return mVideoWidth;
}
public int getVideoHeight() {
return mVideoHeight;
}
public int getRotate() {
return mRotate;
}
public void setOnTranslatePositionListener(OnTranslatePositionListener pOnTranslatePositionListener) {
mOnTranslatePositionListener = pOnTranslatePositionListener;
}
public void setContext(Context context) {
this.context = context;
}
public interface OnTranslatePositionListener {
public abstract void onTranslatePosition(float x, float y, float rx, float ry);
}
}
FFMPEG for cropping particular portion
ffmpeg -i /sdcard/videokit/in.mp4 -filter:v crop=720:1088:0:0 -c:a copy /sdcard/videokit/out.mp4
public class SimpleExample extends Activity {
String workFolder = null;
String demoVideoFolder = null;
String demoVideoPath = null;
String vkLogPath = null;
private boolean commandValidationFailedFlag = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ffmpeg_demo_client_1);
demoVideoFolder = Environment.getExternalStorageDirectory().getAbsolutePath() + "/videokit/";
demoVideoPath = demoVideoFolder + "in.mp4";
Log.i(Prefs.TAG, getString(R.string.app_name) + " version: " + GeneralUtils.getVersionName(getApplicationContext()) );
workFolder = getApplicationContext().getFilesDir().getAbsolutePath() + "/";
//Log.i(Prefs.TAG, "workFolder: " + workFolder);
vkLogPath = workFolder + "vk.log";
GeneralUtils.copyLicenseFromAssetsToSDIfNeeded(this, workFolder);
GeneralUtils.copyDemoVideoFromAssetsToSDIfNeeded(this, demoVideoFolder);
Button invoke = (Button)findViewById(R.id.invokeButton);
invoke.setOnClickListener(new OnClickListener() {
public void onClick(View v){
Log.i(Prefs.TAG, "run clicked.");
if (GeneralUtils.checkIfFileExistAndNotEmpty(demoVideoPath)) {
new TranscdingBackground(SimpleExample.this).execute();
}
else {
Toast.makeText(getApplicationContext(), demoVideoPath + " not found", Toast.LENGTH_LONG).show();
}
}
});
int rc = GeneralUtils.isLicenseValid(getApplicationContext(), workFolder);
Log.i(Prefs.TAG, "License check RC: " + rc);
}
public class TranscdingBackground extends AsyncTask<String, Integer, Integer>
{
ProgressDialog progressDialog;
Activity _act;
String commandStr;
public TranscdingBackground (Activity act) {
_act = act;
}
#Override
protected void onPreExecute() {
EditText commandText = (EditText)findViewById(R.id.CommandText);
commandStr = commandText.getText().toString();
progressDialog = new ProgressDialog(_act);
progressDialog.setMessage("FFmpeg4Android Transcoding in progress...");
progressDialog.show();
}
protected Integer doInBackground(String... paths) {
Log.i(Prefs.TAG, "doInBackground started...");
// delete previous log
boolean isDeleted = GeneralUtils.deleteFileUtil(workFolder + "/vk.log");
Log.i(Prefs.TAG, "vk deleted: " + isDeleted);
PowerManager powerManager = (PowerManager)_act.getSystemService(Activity.POWER_SERVICE);
WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "VK_LOCK");
Log.d(Prefs.TAG, "Acquire wake lock");
wakeLock.acquire();
///////////// Set Command using code (overriding the UI EditText) /////
//commandStr = "ffmpeg -y -i /sdcard/videokit/in.mp4 -strict experimental -s 320x240 -r 30 -aspect 3:4 -ab 48000 -ac 2 -ar 22050 -vcodec mpeg4 -b 2097152 /sdcard/videokit/out.mp4";
//String[] complexCommand = {"ffmpeg", "-y" ,"-i", "/sdcard/videokit/in.mp4","-strict","experimental","-s", "160x120","-r","25", "-vcodec", "mpeg4", "-b", "150k", "-ab","48000", "-ac", "2", "-ar", "22050", "/sdcard/videokit/out.mp4"};
///////////////////////////////////////////////////////////////////////
LoadJNI vk = new LoadJNI();
try {
vk.run(GeneralUtils.utilConvertToComplex(commandStr), workFolder, getApplicationContext());
GeneralUtils.copyFileToFolder(vkLogPath, demoVideoFolder);
} catch (Throwable e) {
Log.e(Prefs.TAG, "vk run exeption.", e);
}
finally {
if (wakeLock.isHeld())
wakeLock.release();
else{
Log.i(Prefs.TAG, "Wake lock is already released, doing nothing");
}
}
Log.i(Prefs.TAG, "doInBackground finished");
return Integer.valueOf(0);
}
protected void onProgressUpdate(Integer... progress) {
}
#Override
protected void onCancelled() {
Log.i(Prefs.TAG, "onCancelled");
//progressDialog.dismiss();
super.onCancelled();
}
#Override
protected void onPostExecute(Integer result) {
Log.i(Prefs.TAG, "onPostExecute");
progressDialog.dismiss();
super.onPostExecute(result);
// finished Toast
String rc = null;
if (commandValidationFailedFlag) {
rc = "Command Vaidation Failed";
}
else {
rc = GeneralUtils.getReturnCodeFromLog(vkLogPath);
}
final String status = rc;
SimpleExample.this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(SimpleExample.this, status, Toast.LENGTH_LONG).show();
if (status.equals("Transcoding Status: Failed")) {
Toast.makeText(SimpleExample.this, "Check: " + vkLogPath + " for more information.", Toast.LENGTH_LONG).show();
}
}
});
}
}
}
try to use getBitmap: TextureView.getBitmap for VideoCropView
it returns bitmap wanted resolution.
Then you can crop using Bitmap.createBitmap
like this
resizedbitmap=Bitmap.createBitmap(bmp, 0,0,yourwidth, yourheight);
Use this library to crop video with visible portion
Video Trimmer Library

Android Canvas error - error queuing buffer to SurfaceTexture

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);
}
}
}
}

why jd-gui lost some info when decompile a .class file?

I have decompiled a class by jd-gui below, but I am unable to understand how the "linearLayout" is being initialized and why linearLayout.startAnimation(animationset) should be invoked, the LockScreen member "linearLayout" is not referred to any instance.
Can anybody tell me how this work? Is it possible for jd-gui lose something while decompilin a .class file ?
the decompiled file below:
// Referenced classes of package com.android.internal.policy.impl:
// KeyguardScreen, KeyguardStatusViewManager, DrawWaterWave, KeyguardUpdateMonitor,
// KeyguardScreenCallback
class LockScreen extends RelativeLayout
implements KeyguardScreen
{
class MultiWaveViewMethods
implements com.android.internal.widget.multiwaveview.MultiWaveView.OnTriggerListener, UnlockWidgetCommonMethods
{
private boolean mCameraDisabled;
private final MultiWaveView mMultiWaveView;
final LockScreen this$0;
public View getView()
{
return mMultiWaveView;
}
public void onGrabbed(View view, int i)
{
}
public void onGrabbedStateChange(View view, int i)
{
if (i != 0)
mCallback.pokeWakelock();
}
public void onReleased(View view, int i)
{
}
public void onTrigger(View view, int i)
{
if (i != 0 && i != 1) goto _L2; else goto _L1
_L1:
mCallback.goToUnlockScreen();
_L4:
return;
_L2:
if (i == 2 || i == 3)
if (!mCameraDisabled)
{
Intent intent = new Intent("android.intent.action.CAMERA_BUTTON", null);
mContext.sendOrderedBroadcast(intent, null);
mCallback.goToUnlockScreen();
} else
{
toggleRingMode();
mUnlockWidgetMethods.updateResources();
mCallback.pokeWakelock();
}
if (true) goto _L4; else goto _L3
_L3:
}
public void ping()
{
mMultiWaveView.ping();
}
public void reset(boolean flag)
{
mMultiWaveView.reset(flag);
}
public void updateResources()
{
int i;
if (mCameraDisabled)
{
if (mSilentMode)
i = 0x107000b;
else
i = 0x107000e;
} else
{
i = 0x1070010;
}
mMultiWaveView.setTargetResources(i);
}
MultiWaveViewMethods(MultiWaveView multiwaveview)
{
boolean flag = true;
this$0 = LockScreen.this;
super();
mMultiWaveView = multiwaveview;
if (mLockPatternUtils.getDevicePolicyManager().getCameraDisabled(null))
{
Log.v("LockScreen", "Camera disabled by Device Policy");
mCameraDisabled = flag;
} else
{
if (mMultiWaveView.getTargetResourceId() == 0x1070010)
flag = false;
mCameraDisabled = flag;
}
}
}
class SlidingTabMethods
implements com.android.internal.widget.SlidingTab.OnTriggerListener, UnlockWidgetCommonMethods
{
private final SlidingTab mSlidingTab;
final LockScreen this$0;
public View getView()
{
return mSlidingTab;
}
public void onGrabbedStateChange(View view, int i)
{
if (i == 2)
{
mSilentMode = isSilentMode();
SlidingTab slidingtab = mSlidingTab;
int j;
if (mSilentMode)
j = 0x104030b;
else
j = 0x104030c;
slidingtab.setRightHintText(j);
}
if (i != 0)
mCallback.pokeWakelock();
}
public void onTrigger(View view, int i)
{
if (i != 1) goto _L2; else goto _L1
_L1:
mCallback.goToUnlockScreen();
_L4:
return;
_L2:
if (i == 2)
{
toggleRingMode();
mCallback.pokeWakelock();
}
if (true) goto _L4; else goto _L3
_L3:
}
public void ping()
{
}
public void reset(boolean flag)
{
mSlidingTab.reset(flag);
}
public void updateResources()
{
int i = 1;
SlidingTab slidingtab;
int j;
int k;
int l;
int i1;
if (!mSilentMode || mAudioManager.getRingerMode() != i)
i = 0;
slidingtab = mSlidingTab;
if (mSilentMode)
{
if (i != 0)
j = 0x10802cc;
else
j = 0x10802c9;
} else
{
j = 0x10802ca;
}
if (mSilentMode)
k = 0x1080398;
else
k = 0x1080395;
if (mSilentMode)
l = 0x1080381;
else
l = 0x1080380;
if (mSilentMode)
i1 = 0x1080394;
else
i1 = 0x1080393;
slidingtab.setRightTabResources(j, k, l, i1);
}
SlidingTabMethods(SlidingTab slidingtab)
{
this$0 = LockScreen.this;
super();
mSlidingTab = slidingtab;
}
}
private static interface UnlockWidgetCommonMethods
{
public abstract View getView();
public abstract void ping();
public abstract void reset(boolean flag);
public abstract void updateResources();
}
class WaveViewMethods
implements com.android.internal.widget.WaveView.OnTriggerListener, UnlockWidgetCommonMethods
{
private final WaveView mWaveView;
final LockScreen this$0;
public View getView()
{
return mWaveView;
}
public void onGrabbedStateChange(View view, int i)
{
if (i == 10)
mCallback.pokeWakelock(30000);
}
public void onTrigger(View view, int i)
{
Log.i("LockScreen", (new StringBuilder()).append("onTrigger, whichHandle=").append(i).toString());
if (i == 10)
{
Log.i("LockScreen", "onTrigger, requestUnlockScreen");
requestUnlockScreen();
}
}
public void ping()
{
}
public void reset(boolean flag)
{
mWaveView.reset();
}
public void updateResources()
{
}
WaveViewMethods(WaveView waveview)
{
this$0 = LockScreen.this;
super();
mWaveView = waveview;
}
}
private static final boolean DBG = true;
private static final String ENABLE_MENU_KEY_FILE = "/data/local/enable_menu_key";
static final String LOCKSCREEN_WALLPAPER = "lockScreenWallpaper";
static final File LOCKSCREEN_WALLPAPER_DIR;
static final File LOCKSCREEN_WALLPAPER_FILE;
private static final int MASTER_STREAM_TYPE = 3;
private static final int ON_RESUME_PING_DELAY = 500;
private static final int STAY_ON_WHILE_GRABBED_TIMEOUT = 30000;
private static final String TAG = "LockScreen";
private static final int WAIT_FOR_ANIMATION_TIMEOUT;
Bitmap BitmapLock;
Bitmap BitmapLockin;
Bitmap BitmapLockout;
final float MAX_LOCK_VOLUME = 0.2F;
final float MIN_LOCK_VOLUME = 0.05F;
int circleinwidth;
int circlewidth;
private ImageView imageCircle;
private LinearLayout linearLayout;
private LinearLayout linearLayout2;
private int locationBrower[];
private int locationCall[];
private int locationCamera[];
private boolean mAnimate;
private AudioManager mAudioManager;
private ImageView mBrower;
private boolean mBrowerPress;
private ImageView mCall;
private boolean mCallPress;
private KeyguardScreenCallback mCallback;
private ImageView mCamera;
private boolean mCameraPress;
private RelativeLayout mChildView;
private Context mContext;
private int mCreationOrientation;
private boolean mDMLock;
private boolean mEnableMenuKeyInLockScreen;
private float mFirstMotionX;
private float mFirstMotionY;
private HDMINative mHDMI;
private int mKeyboardHidden;
private float mLastMotionX;
private float mLastMotionY;
private LockPatternUtils mLockPatternUtils;
private int mLockSoundId;
private int mLockSoundStreamId;
private SoundPool mLockSounds;
private TextView mLockString;
private int mMasterStreamMaxVolume;
private float mMotionDeltaX;
private float mMotionDeltaY;
private int mMoveFirst;
private boolean mMoveFirst2;
private final Runnable mOnResumePing = new Runnable() {
final LockScreen this$0;
public void run()
{
if (mDMLock)
mUnlockWidgetMethods.ping();
}
{
this$0 = LockScreen.this;
super();
}
};
Paint mPaintin;
Paint mPaintout;
private boolean mScreenOn;
private boolean mSilentMode;
private KeyguardStatusViewManager mStatusViewManager;
private boolean mTouching;
private boolean mUnlock;
private int mUnlockSoundId;
private View mUnlockWidget;
private UnlockWidgetCommonMethods mUnlockWidgetMethods;
private KeyguardUpdateMonitor mUpdateMonitor;
private final WallpaperManager mWallpaperManager;
private float mYVelocity;
DrawWaterWave m_DrawWaterWave;
LockScreen(Context context, Configuration configuration, LockPatternUtils lockpatternutils, KeyguardUpdateMonitor keyguardupdatemonitor, KeyguardScreenCallback keyguardscreencallback)
{
super(context);
mHDMI = new HDMINative();
BitmapLockin = null;
BitmapLockout = null;
BitmapLock = null;
circleinwidth = 75;
circlewidth = 180;
mMoveFirst = 0;
mMoveFirst2 = false;
mPaintin = null;
mPaintout = null;
mTouching = false;
mAnimate = false;
mUnlock = false;
mScreenOn = false;
mDMLock = false;
mContext = null;
mCallPress = false;
mBrowerPress = false;
mCameraPress = false;
locationCall = new int[2];
locationBrower = new int[2];
locationCamera = new int[2];
mContext = context;
mLockPatternUtils = lockpatternutils;
mUpdateMonitor = keyguardupdatemonitor;
mCallback = keyguardscreencallback;
mEnableMenuKeyInLockScreen = shouldEnableMenuKey();
mWallpaperManager = WallpaperManager.getInstance(context);
mCreationOrientation = configuration.orientation;
mKeyboardHidden = configuration.hardKeyboardHidden;
LayoutInflater layoutinflater = LayoutInflater.from(context);
Log.v("LockScreen", (new StringBuilder()).append("Creation orientation = ").append(mCreationOrientation).toString());
Log.i("LockScreen", "we will initialize the LockScreen single portrait layout");
layoutinflater.inflate(0x109005a, this, true);
mChildView = (RelativeLayout)findViewById(0x10202b4);
setBackDrawable();
mStatusViewManager = new KeyguardStatusViewManager(this, mUpdateMonitor, mLockPatternUtils, mCallback, false);
setFocusable(true);
setFocusableInTouchMode(true);
setDescendantFocusability(0x60000);
mAudioManager = (AudioManager)mContext.getSystemService("audio");
mSilentMode = isSilentMode();
m_DrawWaterWave = new DrawWaterWave(context);
if (mDMLock)
{
mUnlockWidget = findViewById(0x102029b);
android.content.ContentResolver contentresolver;
String s;
StringBuilder stringbuilder;
if (mUnlockWidget instanceof SlidingTab)
{
SlidingTab slidingtab = (SlidingTab)mUnlockWidget;
slidingtab.setHoldAfterTrigger(true, false);
slidingtab.setLeftHintText(0x104030a);
slidingtab.setLeftTabResources(0x10802cb, 0x1080396, 0x1080377, 0x108038a);
SlidingTabMethods slidingtabmethods = new SlidingTabMethods(slidingtab);
slidingtab.setOnTriggerListener(slidingtabmethods);
mUnlockWidgetMethods = slidingtabmethods;
} else
if (mUnlockWidget instanceof WaveView)
{
WaveView waveview = (WaveView)mUnlockWidget;
WaveViewMethods waveviewmethods = new WaveViewMethods(waveview);
waveview.setOnTriggerListener(waveviewmethods);
mUnlockWidgetMethods = waveviewmethods;
} else
if (mUnlockWidget instanceof MultiWaveView)
{
MultiWaveView multiwaveview = (MultiWaveView)mUnlockWidget;
MultiWaveViewMethods multiwaveviewmethods = new MultiWaveViewMethods(multiwaveview);
multiwaveview.setOnTriggerListener(multiwaveviewmethods);
mUnlockWidgetMethods = multiwaveviewmethods;
} else
{
throw new IllegalStateException((new StringBuilder()).append("Unrecognized unlock widget: ").append(mUnlockWidget).toString());
}
mUnlockWidgetMethods.updateResources();
}
BitmapLockin = ((BitmapDrawable)(BitmapDrawable)getResources().getDrawable(0x1080617)).getBitmap();
BitmapLockout = ((BitmapDrawable)(BitmapDrawable)getResources().getDrawable(0x1080619)).getBitmap();
BitmapLock = ((BitmapDrawable)(BitmapDrawable)getResources().getDrawable(0x1080618)).getBitmap();
imageCircle = (ImageView)findViewById(0x10202c7);
mCall = (ImageView)findViewById(0x10202c0);
mBrower = (ImageView)findViewById(0x10202c1);
mCamera = (ImageView)findViewById(0x10202c2);
mLockString = (TextView)findViewById(0x10202bd);
mPaintin = new Paint();
mPaintout = new Paint();
contentresolver = mContext.getContentResolver();
mLockSounds = new SoundPool(1, 1, 0);
s = android.provider.Settings.System.getString(contentresolver, "lock_sound");
if (s != null)
mLockSoundId = mLockSounds.load(s, 1);
if (s == null || mLockSoundId == 0)
Log.d("LockScreen", (new StringBuilder()).append("failed to load sound from ").append(s).toString());
if ("/system/media/audio/ui/Effect_Tick.ogg" != null)
mUnlockSoundId = mLockSounds.load("/system/media/audio/ui/Effect_Tick.ogg", 1);
if ("/system/media/audio/ui/Effect_Tick.ogg" == null || mUnlockSoundId == 0)
Log.d("LockScreen", (new StringBuilder()).append("failed to load sound from ").append("/system/media/audio/ui/Effect_Tick.ogg").toString());
if (mUpdateMonitor.DM_IsLocked() && mDMLock)
{
Log.i("LockScreen", "we should hide unlock widget");
mUnlockWidget.setVisibility(4);
}
if (mDMLock)
{
stringbuilder = (new StringBuilder()).append("*** LockScreen accel is ");
String s1;
if (mUnlockWidget.isHardwareAccelerated())
s1 = "on";
else
s1 = "off";
Log.v("LockScreen", stringbuilder.append(s1).toString());
}
}
private boolean isScreenOn()
{
PowerManager powermanager = (PowerManager)mContext.getSystemService("power");
boolean flag = false;
if (powermanager != null)
{
flag = powermanager.isScreenOn();
Log.d("LockScreen", (new StringBuilder()).append("screenOn:").append(flag).toString());
}
return flag;
}
private boolean isSilentMode()
{
boolean flag;
if (mAudioManager.getRingerMode() != 2)
flag = true;
else
flag = false;
return flag;
}
private void playSounds(boolean flag)
{
if (android.provider.Settings.System.getInt(mContext.getContentResolver(), "lockscreen_sounds_enabled", 1) != 1) goto _L2; else goto _L1
_L1:
int i;
if (flag)
i = mLockSoundId;
else
i = mUnlockSoundId;
mLockSounds.stop(mLockSoundStreamId);
if (mAudioManager != null) goto _L4; else goto _L3
_L3:
mAudioManager = (AudioManager)mContext.getSystemService("audio");
if (mAudioManager != null) goto _L5; else goto _L2
_L2:
return;
_L5:
mMasterStreamMaxVolume = mAudioManager.getStreamMaxVolume(3);
_L4:
int j = mAudioManager.getStreamVolume(3);
if (j != 0)
{
float f = 0.05F + 0.15F * ((float)j / (float)mMasterStreamMaxVolume);
Log.d("LockScreen", (new StringBuilder()).append("playSounds").append(i).toString());
mLockSoundStreamId = mLockSounds.play(i, f, f, 1, 0, 1.0F);
}
if (true) goto _L2; else goto _L6
_L6:
}
private void requestUnlockScreen()
{
postDelayed(new Runnable() {
final LockScreen this$0;
public void run()
{
mCallback.goToUnlockScreen();
}
{
this$0 = LockScreen.this;
super();
}
}, 0L);
}
private void setBackDrawable()
{
}
private boolean shouldEnableMenuKey()
{
boolean flag = getResources().getBoolean(0x111001a);
boolean flag1 = ActivityManager.isRunningInTestHarness();
boolean flag2 = (new File("/data/local/enable_menu_key")).exists();
boolean flag3;
if (!flag || flag1 || flag2)
flag3 = true;
else
flag3 = false;
return flag3;
}
private void toggleRingMode()
{
int i = 1;
boolean flag;
if (!mSilentMode)
flag = i;
else
flag = false;
mSilentMode = flag;
if (mSilentMode)
{
int j;
AudioManager audiomanager;
if (android.provider.Settings.System.getInt(mContext.getContentResolver(), "vibrate_in_silent", i) == i)
j = i;
else
j = 0;
audiomanager = mAudioManager;
if (j == 0)
i = 0;
audiomanager.setRingerMode(i);
} else
{
mAudioManager.setRingerMode(2);
}
}
public void cleanUp()
{
mUpdateMonitor.removeCallback(this);
mLockPatternUtils = null;
mUpdateMonitor = null;
mCallback = null;
}
protected void dispatchDraw(Canvas canvas)
{
if ((mTouching || mMoveFirst != 0) && !mDMLock)
{
super.dispatchDraw(canvas);
canvas.save();
canvas.translate(0.0F, 0.0F);
if (mMotionDeltaX * mMotionDeltaX + mMotionDeltaY * mMotionDeltaY > (float)(circleinwidth * circleinwidth))
{
float f = mMotionDeltaX * mMotionDeltaX + mMotionDeltaY * mMotionDeltaY;
float f1 = (0 + (0 + circlewidth)) * (0 + (0 + circlewidth));
float f2 = (255F * f) / f1;
if (f2 >= 255F)
f2 = 255F;
mPaintin.setAlpha((int)(255F - f2));
} else
{
mPaintin.setAlpha(255);
}
canvas.drawBitmap(BitmapLockin, mFirstMotionX - (float)circlewidth, mFirstMotionY - (float)circlewidth, mPaintin);
canvas.drawBitmap(BitmapLock, mFirstMotionX - 25F, mFirstMotionY - 25F, null);
canvas.restore();
invalidate();
if (mMoveFirst == 1)
mMoveFirst = 2;
if (isScreenOn())
mCallback.pokeWakelock();
else
Log.i("LockScreen", "dispatch, screenoff");
} else
{
setBackDrawable();
super.dispatchDraw(canvas);
}
}
public boolean needsInput()
{
return false;
}
protected void onAttachedToWindow()
{
super.onAttachedToWindow();
updateConfiguration();
}
public void onClick2(View view)
{
if (view.getId() != 0x10202c0) goto _L2; else goto _L1
_L1:
mCallPress = true;
mBrowerPress = false;
mCameraPress = false;
mCall.setVisibility(0);
mBrower.setVisibility(4);
mCamera.setVisibility(4);
_L4:
return;
_L2:
if (view.getId() == 0x10202c1)
{
mCallPress = false;
mBrowerPress = true;
mCameraPress = false;
mCall.setVisibility(4);
mBrower.setVisibility(0);
mCamera.setVisibility(4);
} else
if (view.getId() == 0x10202c2)
{
mCallPress = false;
mBrowerPress = false;
mCameraPress = true;
mCall.setVisibility(4);
mBrower.setVisibility(4);
mCamera.setVisibility(0);
}
if (true) goto _L4; else goto _L3
_L3:
}
protected void onConfigurationChanged(Configuration configuration)
{
super.onConfigurationChanged(configuration);
updateConfiguration();
}
public boolean onKeyDown(int i, KeyEvent keyevent)
{
if (i == 82 && mEnableMenuKeyInLockScreen)
mCallback.goToUnlockScreen();
return false;
}
public void onPause()
{
mScreenOn = false;
mTouching = false;
mStatusViewManager.onPause();
setBackDrawable();
if (mDMLock)
mUnlockWidgetMethods.reset(false);
mHDMI.hdmiPortraitEnable(false);
}
public void onPhoneStateChanged(String s)
{
}
public void onResume()
{
mAnimate = false;
mTouching = false;
mMotionDeltaY = 0.0F;
mStatusViewManager.onResume();
postDelayed(mOnResumePing, 500L);
mHDMI.hdmiPortraitEnable(true);
mScreenOn = isScreenOn();
setBackDrawable();
}
public void onRingerModeChanged(int i)
{
boolean flag;
if (2 != i)
flag = true;
else
flag = false;
if (flag != mSilentMode)
{
mSilentMode = flag;
if (mDMLock)
mUnlockWidgetMethods.updateResources();
}
}
public boolean onTouchEvent(MotionEvent motionevent)
{
if (mScreenOn && !mDMLock) goto _L2; else goto _L1
_L1:
boolean flag;
Log.w("LockScreen", " ** Lock Screen is off or animation is running **");
flag = false;
_L8:
return flag;
_L2:
int i;
int j;
int k;
int l;
int i1;
int j1;
int k1;
int l1;
int i2;
i = motionevent.getAction();
j = (int)motionevent.getX();
mUnlock = false;
k = (int)motionevent.getY();
l = mCall.getWidth();
i1 = mCall.getHeight();
j1 = mBrower.getWidth();
k1 = mBrower.getHeight();
l1 = mCamera.getWidth();
i2 = mCamera.getHeight();
mCall.getLocationInWindow(locationCall);
mBrower.getLocationInWindow(locationBrower);
mCamera.getLocationInWindow(locationCamera);
i & 0xff;
JVM INSTR tableswitch 0 2: default 172
// 0 193
// 1 834
// 2 662;
goto _L3 _L4 _L5 _L6
_L5:
break MISSING_BLOCK_LABEL_834;
_L3:
break; /* Loop/switch isn't completed */
_L4:
break; /* Loop/switch isn't completed */
_L9:
if (mUnlock)
mCallback.goToUnlockScreen();
flag = true;
if (true) goto _L8; else goto _L7
_L7:
if (!mAnimate)
{
if (k > locationCall[1] && k < i1 + locationCall[1] && j > locationCall[0] && j < l + locationCall[0])
{
mCallPress = true;
mBrowerPress = false;
mCameraPress = false;
mCall.setVisibility(0);
mBrower.setVisibility(4);
mCamera.setVisibility(4);
mLockString.setText(0x10404db);
} else
if (k > locationBrower[1] && k < k1 + locationBrower[1] && j > locationBrower[0] && j < j1 + locationBrower[0])
{
mCallPress = false;
mBrowerPress = true;
mCameraPress = false;
mCall.setVisibility(4);
mBrower.setVisibility(0);
mCamera.setVisibility(4);
mLockString.setText(0x10404db);
} else
if (k > locationCamera[1] && k < i2 + locationCamera[1] && j > locationCamera[0] && j < l1 + locationCamera[0])
{
mCallPress = false;
mBrowerPress = false;
mCameraPress = true;
mCall.setVisibility(4);
mBrower.setVisibility(4);
mCamera.setVisibility(0);
mLockString.setText(0x10404db);
} else
{
onWallpaperTap(motionevent);
}
playSounds(true);
mFirstMotionX = j;
mFirstMotionY = k;
mMoveFirst2 = true;
m_DrawWaterWave.DropStone(j, k, 10, 50);
if (mMoveFirst == 10)
{
mMoveFirst = 1;
AnimationSet animationset = new AnimationSet(false);
b8 b8_1 = new b8(mFirstMotionX - (float)circlewidth, mFirstMotionY - (float)circlewidth, linearLayout, linearLayout2);
b8_1.initialize(circlewidth, circlewidth, 0, 0);
animationset.addAnimation(b8_1);
linearLayout.startAnimation(animationset);
android.view.animation.Animation.AnimationListener animationlistener = new android.view.animation.Animation.AnimationListener() {
final LockScreen this$0;
public void onAnimationEnd(Animation animation)
{
if (mTouching)
linearLayout2.setVisibility(0);
linearLayout.clearAnimation();
linearLayout.setVisibility(4);
}
public void onAnimationRepeat(Animation animation)
{
}
public void onAnimationStart(Animation animation)
{
}
{
this$0 = LockScreen.this;
super();
}
};
b8_1.setAnimationListener(animationlistener);
}
}
goto _L9
_L6:
if (!mAnimate)
{
mTouching = true;
mMotionDeltaY = (float)k - mFirstMotionY;
mMotionDeltaX = (float)j - mFirstMotionX;
if ((mMotionDeltaX % 3F == 0.0F || mMotionDeltaY % 3F == 0.0F) && mFirstMotionY < 750F)
onWallpaperTap(motionevent);
if (mMoveFirst2 && (mMotionDeltaX >= 20F || mMotionDeltaY >= 20F || mMotionDeltaX <= -20F || mMotionDeltaY <= -20F) && mFirstMotionY < 750F)
mMoveFirst2 = false;
if (mMotionDeltaY <= 0.0F);
m_DrawWaterWave.DropStone(j, k, 10, 50);
}
goto _L9
if (!mAnimate)
{
onWallpaperTap(motionevent);
float f = mMotionDeltaX;
float f1 = mMotionDeltaY;
mTouching = false;
mMotionDeltaY = 0.0F;
mMotionDeltaX = 0.0F;
mMoveFirst = 0;
if ((mCallPress || mBrowerPress || mCameraPress) && k < 700 && mFirstMotionY > 750F)
{
Intent intent = new Intent();
if (mCallPress)
{
intent.setClassName("com.android.contacts", "com.android.contacts.DialtactsActivity");
intent.setAction("android.intent.action.DIAL");
} else
if (mBrowerPress)
intent.setClassName("com.android.browser", "com.android.browser.BrowserActivity");
else
if (mCameraPress)
intent.setClassName("com.android.camera", "com.android.camera.Camera");
intent.setFlags(0x10000000);
mCallback.goToUnlockScreen();
mContext.startActivity(intent);
mUnlock = false;
} else
if (f * f + f1 * f1 > (float)(circlewidth * circlewidth))
{
mUnlock = true;
} else
{
mCall.setVisibility(0);
mBrower.setVisibility(0);
mCamera.setVisibility(0);
mLockString.setText(0x10404a0);
mUnlock = false;
}
imageCircle.setVisibility(8);
}
goto _L9
}
protected void onWallpaperTap(MotionEvent motionevent)
{
motionevent.findPointerIndex(motionevent.getPointerId(0));
Log.d("SlideButton", (new StringBuilder()).append("eee ").append(motionevent).toString());
mWallpaperManager.sendWallpaperTouch(getWindowToken(), motionevent);
}
protected void onWallpaperTapSecondary(MotionEvent motionevent)
{
int i = motionevent.findPointerIndex(motionevent.getPointerId(0));
mWallpaperManager.sendWallpaperCommand(getWindowToken(), "android.wallpaper.secondaryTap", 0 + (int)motionevent.getX(i), 0 + (int)motionevent.getY(i), 0, null);
}
void updateConfiguration()
{
int i;
Configuration configuration;
i = 1;
configuration = getResources().getConfiguration();
if (configuration.orientation == mCreationOrientation) goto _L2; else goto _L1
_L1:
mCallback.recreateMe(configuration);
_L4:
return;
_L2:
if (configuration.hardKeyboardHidden != mKeyboardHidden)
{
mKeyboardHidden = configuration.hardKeyboardHidden;
if (mKeyboardHidden != i)
i = 0;
if (mUpdateMonitor.isKeyguardBypassEnabled() && i != 0)
mCallback.goToUnlockScreen();
}
if (true) goto _L4; else goto _L3
_L3:
}
static
{
LOCKSCREEN_WALLPAPER_DIR = new File("/data/data/com.android.settings/mtk");
LOCKSCREEN_WALLPAPER_FILE = new File(LOCKSCREEN_WALLPAPER_DIR, "lockScreenWallpaper");
}
/*
static boolean access$002(LockScreen lockscreen, boolean flag)
{
lockscreen.mSilentMode = flag;
return flag;
}
*/
enter code here
}
A good rule of thumb is that these decompilers only generate something that resembles java code. There are often syntax/compilation problems, and there's no guarantee that the semantics match that of the original class.
If you want a lossless representation, it's better to use a disassembler to view the bytecode. For dex files, you can use baksmali, dexdump or dedexer.

start other activity from activity that has thread

I want to move from activity that has thread in it (actually it's in the activity's SurfaceView) to other activity. But when I run it, sometimes it works, sometimes it's not responding (it moves to other activity but the activity freezes). I really frustrated right now. I have searched everywhere but I can't find the answer to my problem. Somebody please help me. :(
I'll show you the code. If you need other pieces of code I'll show it to you.
Here is the Activity code:
public class MapActivity extends Activity {
private static final String TAG = MapActivity.class.getSimpleName();
private DisplayMetrics metrics;
private MapView mapView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
DrawableManager.initInstance(getApplicationContext());
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
Log.d(TAG, "start game activity");
metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics); // dapetin
// ukuran
// layar
// mapView =
// new
// MapView(this,
// metrics.widthPixels,
// metrics.heightPixels);
MapView.initInstance(getApplicationContext(), metrics.widthPixels,
metrics.heightPixels);
setContentView(MapView.getInstance());
}
#Override
public void onPause() {
super.onPause();
MapView.getInstance().thread.setRunning(false);
}
}
Here is the SurfaceView code (I don't give you all part of the code because it will be too long):
public class MapView extends SurfaceView implements SurfaceHolder.Callback {
public final Random rand;
private Resources res;
private static MapView instance;
private static int screenWidth;
private static int screenHeight;
private static final String TAG = MapView.class.getSimpleName();
public mapThread thread;
private Matrix matrix = new Matrix();
public static Block blockTile[][];
private Player player;
public static int tileSize;
public static boolean isMalam = false;
public static boolean isAdaMonster = false;
private ArrayList<Monster> monsters;
public static int leftMargin;
public static final int nTileH = 10;
public static final int nTileW = 17;
private int ctrMonster = 0;
private int ctrDetik = 0;
private int ctrMenit = 0;
private int ctrJam = 6;
private int ctrHari = 0;
private static boolean isOutdoor;
private Pair<Float, Float> tapPos;
private Pair<Float, Float> tapPos2;
private Context parentActivity;
private boolean isTouch = false;
private boolean Found = false;
private Street street;
private Store store;
private Combinatorium combinatorium;
private Stadium stadium;
private Home home;
private AreaLuar3 arealuar3;
private AreaLuar2 arealuar2;
private AreaLuar1 arealuar1;
private String dataMap[];
public static String currentMap;
public MapView(Context context, int scrWidth, int scrHeight) {
super(context);
parentActivity = context;
blockTile = new Block[nTileW][nTileH];
screenWidth = scrWidth;
screenHeight = scrHeight;
int sTile = scrHeight / nTileH;
tileSize = sTile;
getHolder().addCallback(this);
res = context.getResources();
rand = new Random();
dataMap = new String[15];
currentMap = "street";
player = new Player(7, 4);
build();
setFocusable(true);
}
public void surfaceCreated(SurfaceHolder arg0) {
// inisialisasi thread
initThread();
Log.d(TAG, "surface created");
}
public void surfaceDestroyed(SurfaceHolder arg0) {
releaseThread();
Log.d(TAG, "surface destroyed");
}
public static void initInstance(Context context, int W, int H) {
assert instance == null;
instance = new MapView(context, W, H);
}
public static MapView getInstance() {
assert instance != null;
return instance;
}
// inisialisasi thread
public void initThread() {
if (thread == null || !thread.isAlive()) {
thread = new mapThread(getHolder(), this);
thread.start();
}
thread.setRunning(true);
}
private void releaseThread() {
boolean retry = true;
while (retry)
try {
thread.join();
retry = false;
thread = null;
} catch (InterruptedException e) {
}
}
public void update() {
ctrDetik++;
if (ctrDetik > 59) {
ctrDetik = 0;
ctrMenit++;
if (ctrMenit > 59) {
ctrMenit = 0;
ctrJam++;
cekMalam();
if (ctrJam > 23) {
ctrJam = 0;
ctrHari++;
}
}
}
if (!Found && isAdaMonster) {
ctrMonster++;
for (Monster mons : monsters) {
if (mons.cekEqualBlock(player)) {
Found = true;
Intent test = new Intent(parentActivity, MainMenu.class);
test.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
parentActivity.startActivity(test);
}
if (Found)
break;
if (ctrMonster == 30) {
ctrMonster = 0;
monsters.get(0).moveRandom();
monsters.get(1).moveCloser(player.getXBlock(),
player.getYBlock());
}
}
}
if (isTouch)
if (Math.abs(tapPos2.first - tapPos.first) > 100
|| Math.abs(tapPos2.second - tapPos.second) > 100)
if (Math.abs(tapPos2.first - tapPos.first) > Math
.abs(tapPos2.second - tapPos.second)) {
if (tapPos2.first - tapPos.first > 0)
player.move(2);
else
player.move(4);
} else if (Math.abs(tapPos2.first - tapPos.first) < Math
.abs(tapPos2.second - tapPos.second))
if (tapPos2.second - tapPos.second > 0)
player.move(3);
else
player.move(1);
}
}
Here is the thread code:
package com.map;
import android.graphics.Canvas;
import android.view.SurfaceHolder;
public class mapThread extends Thread {
private boolean running;
private SurfaceHolder surfaceHolder;
private MapView mapView;
private final static int MAX_FPS = 60; // fps yang
// diinginkan
private final static int MAX_FRAME_SKIPS = 5; // maksimum
// jumlah
// frame
// yang bisa
// diskip
private final static int FRAME_PERIOD = 1000 / MAX_FPS;
public mapThread(SurfaceHolder surfaceHolder, MapView gameMapView) {
super();
this.surfaceHolder = surfaceHolder;
mapView = gameMapView;
}
public void setRunning(boolean val) {
running = val;
}
#Override
public void run() {
Canvas canvas;
long beginTime; // waktu mulai siklus
long timeDiff; // waktu yang diperlukan satu siklus untuk selesai
int sleepTime; // ms untuk tidur(<0 jika ketinggalan)
int framesSkipped; // jumlah frame yang akan diskip
sleepTime = 0;
while (running) {
canvas = null;
// ngunci canvas untuk digambar
try {
canvas = surfaceHolder.lockCanvas();
synchronized (surfaceHolder) {
beginTime = System.currentTimeMillis();
framesSkipped = 0; // reset jumlah frame yang pengen diskip
// update game state
// draw canvas di panel
mapView.update();
mapView.render(canvas);
// hitung berapa lama satu siklus
timeDiff = System.currentTimeMillis() - beginTime;
// hitung waktu tidur
sleepTime = (int) (FRAME_PERIOD - timeDiff);
if (sleepTime > 0)
// tidurin thread selama waktu tidur tsb
// cycle lebih cepat dari fps
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
}
while (sleepTime < 0 && framesSkipped < MAX_FRAME_SKIPS) {
// ketinggalan fps, update tanpa manggil render
mapView.update();
sleepTime += FRAME_PERIOD;
framesSkipped++;
}
}
} finally {
// in case of an exception the surface is not left in
// an inconsistent state
if (canvas != null)
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
}
startActivity is executed in update method in SurfaceView code. What should I do? Really needs help here.
SurfaceView extends View, so you can call the View.post() method.
In the code where you currently startThe activity you want to do this.
You can call another function to do this if you want it to be a little cleaner.
post(new Runnable() {
#Override
public void run() {
Intent test = new Intent(parentActivity, MainMenu.class);
test.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
parentActivity.startActivity(test);
});
This will call startActivity on the mainThread.

how to calculate the vibration of a mobile in android app

in my app when the user walks i want to calculate the shaking(vibration) of a mobile. How to calculate the shaking of a mobile and how to show its output.
here is the code for making a mobile to get vibrated when is shaked....
final Vibrator vibe = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
mShaker = new ShakeListener(this);
mShaker.setOnShakeListener(new ShakeListener.OnShakeListener ()
{
public void onShake()
{
vibe.vibrate(100);
System.out.println("SHAKE LISTENER CALLED");
noofShakes++;
}
});
public class ShakeListener implements SensorEventListener
{
private static final int FORCE_THRESHOLD = 300;
private static final int TIME_THRESHOLD = 100;
private static final int SHAKE_TIMEOUT = 500;
private static final int SHAKE_DURATION = 1000;
private static final int SHAKE_COUNT = 3;
private SensorManager mSensorMgr;
private float mLastX=-1.0f, mLastY=-1.0f, mLastZ=-1.0f;
private long mLastTime;
private OnShakeListener mShakeListener;
private Context mContext;
private int mShakeCount = 0;
private long mLastShake;
private long mLastForce;
public interface OnShakeListener
{
public void onShake();
}
public ShakeListener(Context context)
{
mContext = context;
resume();
}
public void setOnShakeListener(OnShakeListener listener)
{
mShakeListener = listener;
}
public void resume()
{
mSensorMgr = (SensorManager)mContext.getSystemService(Context.SENSOR_SERVICE);
if (mSensorMgr == null)
{
throw new UnsupportedOperationException("Sensors not supported");
}
boolean supported = false;
try
{
supported = mSensorMgr.registerListener(this, mSensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_GAME);
}
catch (Exception e)
{
Toast.makeText(mContext, "Shaking not supported", Toast.LENGTH_LONG).show();
}
if ((!supported)&&(mSensorMgr != null)) mSensorMgr.unregisterListener(this);
}
public void pause()
{
if (mSensorMgr != null)
{
mSensorMgr.unregisterListener(this);
mSensorMgr = null;
}
}
public void onAccuracyChanged(Sensor sensor, int accuracy)
{
}
public void onSensorChanged(SensorEvent event)
{
if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER)
return;
long now = System.currentTimeMillis();
if ((now - mLastForce) > SHAKE_TIMEOUT)
{
mShakeCount = 0;
}
if ((now - mLastTime) > TIME_THRESHOLD)
{
long diff = now - mLastTime;
float speed = Math.abs(event.values[SensorManager.DATA_X] + event.values[SensorManager.DATA_Y] + event.values[SensorManager.DATA_Z] - mLastX - mLastY - mLastZ) / diff * 10000;
System.out.println("SPEED OF THE VIBRATION "+speed);
if (speed > FORCE_THRESHOLD)
{
if ((++mShakeCount >= SHAKE_COUNT) && (now - mLastShake > SHAKE_DURATION))
{
mLastShake = now;
mShakeCount = 0;
if (mShakeListener != null)
{
mShakeListener.onShake();
}
}
mLastForce = now;
}
mLastTime = now;
mLastX = event.values[SensorManager.DATA_X];
mLastY = event.values[SensorManager.DATA_Y];
mLastZ = event.values[SensorManager.DATA_Z];
}
}
}
we have to add the following line in the manifest file
<uses-permission android:name="android.permission.SHAKE" />
<uses-permission android:name="android.permission.VIBRATE" />

Categories

Resources