I have a camera app in android. There is a image view and two button. When i am in landscape mode two button will be available on the image view and when i am in portrait mode buttons have to hidden and the aspect ratio will be right.
public class CustomCameraActivity extends Activity implements SurfaceHolder.Callback {
Camera camera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean previewing = false;
LayoutInflater controlInflater = null;
Context context;
ImageView imageView;
SensorManager sensorManager;
float[] mGravs = new float[3];
float[] mGeoMags = new float[3];
float[] mRotationM = new float[16];
float[] mInclinationM = new float[16];
float[] mOrientation = new float[3];
float[] mOldOreintation = new float[3];
String[] mAccelerometer = new String[3];
String[] mMagnetic = new String[3];
String[] mRotation = new String[16];
String[] mInclination = new String[16];
String[] mOrientationString = new String[3];
String[] mOldOreintationString = new String[3];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
context = this;
sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
imageView = (ImageView)findViewById(R.id.imgError);
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView)findViewById(R.id.camerapreview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
controlInflater = LayoutInflater.from(getBaseContext());
View viewControl = controlInflater.inflate(R.layout.custom, null);
LayoutParams layoutParamsControl = new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT);
Button btn1 = (Button)viewControl.findViewById(R.id.Button01);
Button btn2 = (Button)viewControl.findViewById(R.id.Button02);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
//Toast.makeText(context, "1111111111111111111111111", Toast.LENGTH_SHORT).show();
camera.takePicture(null, null, mPicture);
Constant.rotationValueForCamera = Constant.rotationValue;
}
});
btn2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
//Toast.makeText(context, "22222222222222222222222222", Toast.LENGTH_SHORT).show();
Log.e("0 imagePickerStatus", Constant.imagePickerStatus+"");
Constant.imagePickerStatus = 0;
Log.e("0 imagePickerStatus", Constant.imagePickerStatus+"");
finish();
}
});
this.addContentView(viewControl, layoutParamsControl);
int ot = getResources().getConfiguration().orientation;
if(Configuration.ORIENTATION_LANDSCAPE == ot)
{
imageView.setVisibility(View.GONE);
Log.e("ori1111", "land");
}
else
{
imageView.setVisibility(View.VISIBLE);
Log.e("ori111", "port");
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
//Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
imageView.setVisibility(View.GONE);
Log.e("ori", "land");
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
//Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
imageView.setVisibility(View.VISIBLE);
Log.e("ori", "port");
}
}
public String getPollDeviceAttitude()
{
return Constant.rotationValueForCamera;
}
private SensorEventListener sensorEventListener = new SensorEventListener() {
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
/* Get the Sensors */
public void onSensorChanged(SensorEvent event) {
switch (event.sensor.getType()) {
case Sensor.TYPE_ACCELEROMETER:
System.arraycopy(event.values, 0, mGravs, 0, 3);
break;
case Sensor.TYPE_MAGNETIC_FIELD:
System.arraycopy(event.values, 0, mGeoMags, 0, 3);
break;
case Sensor.TYPE_ORIENTATION:
System.arraycopy(event.values, 0, mOldOreintation, 0, 3);
break;
default:
return;
}
// If mGravs and mGeoMags have values then find rotation matrix
if (mGravs != null && mGeoMags != null) {
// checks that the rotation matrix is found
boolean success = SensorManager.getRotationMatrix(mRotationM, mInclinationM, mGravs, mGeoMags);
if (success) {
/* getOrientation Values */
SensorManager.getOrientation(mRotationM, mOrientation);
for(int i=0; i<3; i++){
mAccelerometer[i] = Float.toString(mGravs[i]);
mMagnetic[i] = Float.toString(mGeoMags[i]);
mOrientationString[i] = Float.toString(mOrientation[i]);
mOldOreintationString[i] = Float.toString(mOldOreintation[i]);
}
/* Make everything text to show on device
TextView xaxisAccelerometerText = (TextView)findViewById(R.id.xaxisAccelerometer);
xaxisAccelerometerText.setText(mAccelerometer[0]);
TextView yaxisAccelerometerText = (TextView)findViewById(R.id.yaxisAccelerometer);
yaxisAccelerometerText.setText(mAccelerometer[1]);
TextView zaxisAccelerometerText = (TextView)findViewById(R.id.zaxisAccelerometer);
zaxisAccelerometerText.setText(mAccelerometer[2]);
TextView xaxisMagneticText = (TextView)findViewById(R.id.xaxisMagnetic);
xaxisMagneticText.setText(mMagnetic[0]);
TextView yaxisMagneticText = (TextView)findViewById(R.id.yaxisMagnetic);
yaxisMagneticText.setText(mMagnetic[1]);
TextView zaxisMagneticText = (TextView)findViewById(R.id.zaxisMagnetic);
zaxisMagneticText.setText(mMagnetic[2]);
TextView xaxisOrientationText = (TextView)findViewById(R.id.xaxisOrientation);
xaxisOrientationText.setText(mOrientationString[0]);
TextView yaxisOrientationText = (TextView)findViewById(R.id.yaxisOrientation);
yaxisOrientationText.setText(mOrientationString[1]);
TextView zaxisOrientationText = (TextView)findViewById(R.id.zaxisOrientation);
zaxisOrientationText.setText(mOrientationString[2]);
TextView xaxisOldOrientationText = (TextView)findViewById(R.id.xaxisOldOrientation);
xaxisOldOrientationText.setText(mOldOreintationString[0]);
TextView yaxisOldOrientationText = (TextView)findViewById(R.id.yaxisOldOrientation);
yaxisOldOrientationText.setText(mOldOreintationString[1]);
TextView zaxisOldOrientationText = (TextView)findViewById(R.id.zaxisOldOrientation);
zaxisOldOrientationText.setText(mOldOreintationString[2]);*/
Constant.rotationValue = mOrientationString[0] + " " + mOrientationString[1] + " " + mOrientationString[2];
}else{
/* Make everything text to show on device even if getRotationMatrix fails
String matrixFailed = "Rotation Matrix Failed";
TextView xaxisAccelerometerText = (TextView)findViewById(R.id.xaxisAccelerometer);
xaxisAccelerometerText.setText(mAccelerometer[0]);
TextView yaxisAccelerometerText = (TextView)findViewById(R.id.yaxisAccelerometer);
yaxisAccelerometerText.setText(mAccelerometer[1]);
TextView zaxisAccelerometerText = (TextView)findViewById(R.id.zaxisAccelerometer);
zaxisAccelerometerText.setText(mAccelerometer[2]);
TextView xaxisMagneticText = (TextView)findViewById(R.id.xaxisMagnetic);
xaxisMagneticText.setText(mMagnetic[0]);
TextView yaxisMagneticText = (TextView)findViewById(R.id.yaxisMagnetic);
yaxisMagneticText.setText(mMagnetic[1]);
TextView zaxisMagneticText = (TextView)findViewById(R.id.zaxisMagnetic);
zaxisMagneticText.setText(mMagnetic[2]);
TextView xaxisOrientationText = (TextView)findViewById(R.id.xaxisOrientation);
xaxisOrientationText.setText(matrixFailed);
TextView yaxisOrientationText = (TextView)findViewById(R.id.yaxisOrientation);
yaxisOrientationText.setText(matrixFailed);
TextView zaxisOrientationText = (TextView)findViewById(R.id.zaxisOrientation);
zaxisOrientationText.setText(matrixFailed);
TextView xaxisOldOrientationText = (TextView)findViewById(R.id.xaxisOldOrientation);
xaxisOldOrientationText.setText(mOldOreintationString[0]);
TextView yaxisOldOrientationText = (TextView)findViewById(R.id.yaxisOldOrientation);
yaxisOldOrientationText.setText(mOldOreintationString[1]);
TextView zaxisOldOrientationText = (TextView)findViewById(R.id.zaxisOldOrientation);
zaxisOldOrientationText.setText(mOldOreintationString[2]);*/
Constant.rotationValue = mOrientationString[0] + " " + mOrientationString[1] + " " + mOrientationString[2];
}
}
}
};
protected void onPause()
{
super.onPause();
sensorManager.unregisterListener(sensorEventListener);
}
#Override
public void onResume()
{
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
sensorManager.registerListener(sensorEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD), SensorManager.SENSOR_DELAY_NORMAL);
sensorManager.registerListener(sensorEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_NORMAL);
if(Constant.isCapturedOk)
{
Constant.isCapturedOk = false;
finish();
}
}
PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
Log.e("Camrera", "22222222222222222");
Intent intent = new Intent(context, PreviewActivity.class);
//intent.putExtra("data", data);
Constant.imageData = data;
startActivity(intent);
}
};
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if(previewing){
camera.stopPreview();
previewing = false;
}
if (camera != null){
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
camera = Camera.open();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
#Override
protected void onStop()
{
super.onStop();
Log.e("Tab", "Stoping");
}
#Override
public boolean onKeyDown(int keyCode,KeyEvent event)
{
if(keyCode==KeyEvent.KEYCODE_BACK)
{
return true;
}
return super.onKeyDown(keyCode, event);
}
}
create different layouts for portrait and landscape
like this:
http://mdaslam.wordpress.com/2013/01/15/android-programming-screen-orientationportrait-landscape/
and change visibility of button in other layout using this:
android:visibility="invisible"
your problem would surely be solved.
Related
I created an EMF reader app in Android Studio and is having trouble with how to increase a drawable animation when the SensorManager and TextView increases as well as decreases with the SensorManager and TextView in the app.
Here's what I have so far:
public class MainActivity extends AppCompatActivity implements SensorEventListener {
TextView pkeEMF;
private static SensorManager sensorManager;
private Sensor emfSensor;
SoundPool spPKE;
int mpPKE;
ImageView animationView;
AnimationDrawable pkeAnimation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pkeEMF = (TextView) findViewById(R.id.pkeEMF);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
emfSensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
animationView = (ImageView) findViewById(R.id.pkeDot);
animationView.setBackgroundResource(R.drawable.pkeamimation);
pkeAnimation = (AnimationDrawable) animationView.getBackground();
pkeAnimation.start();
spPKE = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
spPKE.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
#Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
mpPKE = spPKE.play(sampleId, 1, 1, 0, -1, 1);
}
});
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
getSupportActionBar().hide();
}
public void showAnimation(View view) {
Intent intent = new Intent(this, AnimationSound.class);
startActivity(intent);
}
#Override
protected void onResume() {
super.onResume();
if (emfSensor != null) {
sensorManager.registerListener(this, emfSensor, SensorManager.SENSOR_DELAY_NORMAL);
} else {
Toast.makeText(this, "Not Supported", Toast.LENGTH_SHORT).show();
finish();
}
mpPKE = spPKE.load(getApplicationContext(), R.raw.pke_running_loop, 1);
}
#Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
spPKE.stop(mpPKE);
}
#Override
public void onSensorChanged(SensorEvent event) {
float azimuth = Math.round(event.values[0]);
float pitch = Math.round(event.values[1]);
float roll = Math.round(event.values[2]);
double tesla = Math.sqrt((azimuth * azimuth) + (pitch * pitch) + (roll * roll));
String text = String.format("%.2f", tesla);
pkeEMF.setText(text + "μT");
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
How do I do this? I have been looking everywhere to find the answer on how to do this and came up with nothing.
I gonna show a preview using a PopupWindow based on AirView feature of Samsung SPen
But the problem is that the SurfaceView is not created and non of the SurfaceHolder.Callback methods are called.
The surface region becomes transparent when the popup is displayed because the surface is not created at all.
SurfaceView is not created and is transparent:
HoverPreview:
public class HoverPreview extends LinearLayout implements View.OnHoverListener, SurfaceHolder.Callback {
private static final String TAG = "HoverPreview";
private SurfaceHolder mHolder = null;
View mAnchorView = null;
String videoPath;
int position;
private boolean IsMediaPlayerReady = false;
private MediaPlayer mMediaPlayer;
private SurfaceView mSurfaceView;
Context context;
public HoverPreview(Context context, String videoPath, int position) {
super(context);
this.videoPath = videoPath;
this.position = position;
setupLayout(context);
}
public HoverPreview(Context context, AttributeSet attrs) {
super(context, attrs);
setupLayout(context);
}
public HoverPreview(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setupLayout(context);
}
private void setupLayout(Context context) {
this.context = context;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.media_browser_hover, this);
}
#Override
protected void onFinishInflate() {
super.onFinishInflate();
}
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
Log.d(TAG, "HoverSurface created");
final Surface surface = surfaceHolder.getSurface();
if (surface == null) return;
if (!surface.isValid()) return;
mHolder = surfaceHolder;
mMediaPlayer = new MediaPlayer();
try {
mMediaPlayer.setDataSource(videoPath);
} catch (IOException e) {
e.printStackTrace();
}
mMediaPlayer.setDisplay(mHolder);
mAnchorView.setTag(mMediaPlayer);
mMediaPlayer.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() {
#Override
public void onVideoSizeChanged(MediaPlayer mediaPlayer, int i, int i2) {
mHolder.setFixedSize(i, i2);
}
});
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
Log.d(TAG, "MediaPlayer preview is prepared");
IsMediaPlayerReady = true;
if (mMediaPlayer != null && IsMediaPlayerReady) {
if (position > 0)
mMediaPlayer.seekTo(position);
mMediaPlayer.start();
}
}
});
Log.d(TAG, "MediaPlayer is created");
try {
mMediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i2, int i3) {
Log.d(TAG, "HoverSurface changed");
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
Log.d(TAG, "HoverSurface destroyed");
if (mMediaPlayer != null) {
mMediaPlayer.stop();
mMediaPlayer.release();
//thumbnailImageView.setTag(null);
}
}
public void setAnchorView(View view) {
mAnchorView = view;
}
#Override
public boolean onHover(View view, MotionEvent motionEvent) {
try {
if (motionEvent.getAction() == MotionEvent.ACTION_HOVER_ENTER) {
Log.d(TAG, "ACTION_HOVER_ENTER");
mSurfaceView = (SurfaceView) findViewById(R.id.media_browser_hoverSurfaceView);
mHolder = mSurfaceView.getHolder();
if (mHolder != null) {
mHolder.addCallback(this);
}
} else if (motionEvent.getAction() == MotionEvent.ACTION_HOVER_EXIT) {
Log.d(TAG, "ACTION_HOVER_EXIT");
if (mAnchorView.getTag() != null) {
MediaPlayer mMediaPlayer = (MediaPlayer) mAnchorView.getTag();
mMediaPlayer.stop();
mMediaPlayer.release();
mAnchorView.setTag(null);
}
}
} catch (Exception e) {
Log.e(TAG, e.getMessage() + Utils.toString(e.getStackTrace()));
}
return false;
}
}
The code to show the preview:
final PopupWindow popupWindow = new PopupWindow(context);
final HoverPreview hoverPreview = new HoverPreview(context, videoPath, 0);
hoverPreview.setAnchorView(thumbnailImageView);
thumbnailImageView.setOnHoverListener(new View.OnHoverListener() {
#Override
public boolean onHover(View view, MotionEvent motionEvent) {
hoverPreview.onHover(view, motionEvent);
if (motionEvent.getAction() == MotionEvent.ACTION_HOVER_ENTER) {
popupWindow.setContentView(hoverPreview);
popupWindow.setWidth(600);
popupWindow.setHeight(400);
popupWindow.showAtLocation(thumbnailImageView, ToolHoverPopup.Gravity.NO_GRAVITY, 10, 10);
Log.d(TAG, "Manual Hover Enter");
} else if (motionEvent.getAction() == MotionEvent.ACTION_HOVER_EXIT) {
Log.d(TAG, "Manual Hover Exit");
if (popupWindow != null)
popupWindow.dismiss();
}
return true;
});
Here's my complete working solution:
I borrowed some code from ToolHoverPopup class from SPen library, also I customized for this special popup so that nothing is created or inflated until the actual hovering is happened so that we don't consume resources for enabling such a preview in lists.
We need to have our preview attached to a Window so because of this we have to manage all the underlying job of positioning which is normally done by PopupWindow, so I completely removed the dependency on the PopupWindow and now my HoverPreview class is fully working and manages all the jobs, also it has the ability to determine the Hover Detection delay in milliseconds.
Screenshot (SurfaceView is created)
Usage: (Since the layout contains SurfaceView and is resource intensive, I manually trigger onHover event so that the real surface creation is performed only when the real hover is performed. Also by this, I don't create any object of HoverPreview before it's needed)
thumbnailImageView.setOnHoverListener(new View.OnHoverListener() {
#Override
public boolean onHover(View view, MotionEvent motionEvent) {
HoverPreview hoverPreview;
if (thumbnailImageView.getTag() == null) {
hoverPreview = new HoverPreview(context, getActivity().getWindow(), videoPath, 0);
hoverPreview.setHoverDetectTime(1000);
thumbnailImageView.setTag(hoverPreview);
} else
hoverPreview = (HoverPreview) thumbnailImageView.getTag();
hoverPreview.onHover(null, motionEvent);
if (motionEvent.getAction() == MotionEvent.ACTION_HOVER_EXIT)
thumbnailImageView.setTag(null);
return true;
}
});
HoverPreview:
public class HoverPreview extends LinearLayout implements View.OnHoverListener, SurfaceHolder.Callback {
private static final int MSG_SHOW_POPUP = 1;
private static final int MSG_DISMISS_POPUP = 2;
private static final int HOVER_DETECT_TIME_MS = 300;
private static final int POPUP_TIMEOUT_MS = 60 * 1000;
protected int mHoverDetectTimeMS;
private static final String TAG = "HoverPreview";
private SurfaceHolder mHolder = null;
String videoPath;
int position;
private boolean IsMediaPlayerReady = false;
private MediaPlayer mMediaPlayer;
private SurfaceView mSurfaceView;
Context context;
private HoverPopupHandler mHandler;
Window window;
public HoverPreview(Context context, Window window, String videoPath, int position) {
super(context);
this.mHoverDetectTimeMS = HOVER_DETECT_TIME_MS;
this.videoPath = videoPath;
this.position = position;
this.window = window;
setupLayout(context);
}
private void setupLayout(Context context) {
this.context = context;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rootView = inflater.inflate(R.layout.media_browser_hover, this);
mSurfaceView = (SurfaceView) findViewById(R.id.media_browser_hoverSurfaceView);
}
View rootView;
#Override
protected void onFinishInflate() {
super.onFinishInflate();
}
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
Log.d(TAG, "HoverSurface created");
final Surface surface = surfaceHolder.getSurface();
if (surface == null) return;
if (!surface.isValid()) return;
mHolder = surfaceHolder;
mMediaPlayer = new MediaPlayer();
try {
mMediaPlayer.setDataSource(videoPath);
} catch (IOException e) {
e.printStackTrace();
return;
}
mMediaPlayer.setDisplay(mHolder);
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
Log.d(TAG, "MediaPlayer preview is prepared");
IsMediaPlayerReady = true;
int videoWidth = mMediaPlayer.getVideoWidth();
int videoHeight = mMediaPlayer.getVideoHeight();
Point size = new Point();
int screenHeight = 0;
int screenWidth = 0;
Display display = getDisplay();
display.getSize(size);
screenWidth = size.x - (350 + 30); // margin + padding
screenHeight = size.y;
FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mSurfaceView.getLayoutParams();
lp.width = screenWidth;
lp.height = (int) (((float) videoHeight / (float) videoWidth) * (float) screenWidth);
mSurfaceView.setLayoutParams(lp);
if (mMediaPlayer != null && IsMediaPlayerReady) {
if (position > 0)
mMediaPlayer.seekTo(position);
mMediaPlayer.start();
findViewById(R.id.media_browser_hoverRootFrameLayout).setVisibility(VISIBLE);
}
}
});
Log.d(TAG, "MediaPlayer is created");
try {
mMediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i2, int i3) {
Log.d(TAG, "HoverSurface changed");
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
Log.d(TAG, "HoverSurface destroyed");
try {
if (mMediaPlayer != null) {
mMediaPlayer.stop();
mMediaPlayer.release();
}
} catch (Exception e) {
}
}
#Override
public boolean onHover(View view, MotionEvent motionEvent) {
try {
if (motionEvent.getAction() == MotionEvent.ACTION_HOVER_ENTER) {
Log.d(TAG, "ACTION_HOVER_ENTER");
show(); // checks the timing
} else if (motionEvent.getAction() == MotionEvent.ACTION_HOVER_EXIT) {
Log.d(TAG, "ACTION_HOVER_EXIT");
dismiss();
}
} catch (Exception e) {
Log.e(TAG, e.getMessage() + Utils.toString(e.getStackTrace()));
}
return false;
}
/**
* Sets the time that detecting hovering.
*
* #param ms The time, milliseconds
*/
public void setHoverDetectTime(int ms) {
mHoverDetectTimeMS = ms;
}
public void dismiss() {
dismissPopup();
}
private void dismissPopup() {
// remove pending message and dismiss popup
getMyHandler().removeMessages(MSG_SHOW_POPUP);
getMyHandler().removeMessages(MSG_DISMISS_POPUP);
try {
if (mMediaPlayer != null) {
mMediaPlayer.stop();
mMediaPlayer.release();
}
} catch (Exception e) {
}
if (getParent() != null)
((ViewGroup) getParent()).removeView(this);
}
private Handler getMyHandler() {
if (mHandler == null)
mHandler = new HoverPopupHandler();
return mHandler;
}
public void show() {
// send message to show.
if (getMyHandler().hasMessages(MSG_SHOW_POPUP)) {
return;
// getHandler().removeMessages(MSG_SHOW_POPUP);
}
getMyHandler().sendEmptyMessageDelayed(MSG_SHOW_POPUP, mHoverDetectTimeMS);
}
private void showPopup() {
if (getParent() == null) {
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.CENTER_VERTICAL;
params.x = 350;
window.addContentView(this, params);
}
mHolder = mSurfaceView.getHolder();
if (mHolder != null) {
mHolder.addCallback(this);
}
}
;
private class HoverPopupHandler extends Handler {
#Override
public void handleMessage(Message msg) {
// if (DEBUG)
// android.util.Log.e(TAG, "handleMessage : " + ((msg.what == MSG_SHOW_POPUP) ? "SHOW" : "DISMISS"));
switch (msg.what) {
case MSG_SHOW_POPUP:
showPopup();
sendEmptyMessageDelayed(MSG_DISMISS_POPUP, POPUP_TIMEOUT_MS);
break;
case MSG_DISMISS_POPUP:
dismissPopup();
break;
}
}
}
}
i have problem with live wallpaper on preview mode.ie the wallpaper image doesn't fit well in landscape mode.it works great on portrait.i need your help.hope you would help me.i have added code
RajawaliRenderer.java
public class RipplesRenderer extends RajawaliRenderer {
private final int NUM_CUBES_H = 4;
private final int NUM_CUBES_V = 4;
private final int NUM_CUBES = NUM_CUBES_H * NUM_CUBES_V;
//private Animation3D[] mAnims;
private TouchRippleFilter mFilter;
private long frameCount;
private final int QUAD_SEGMENTS = 40;
int mScreenHeight,
mScreenWeight;
Gallery_Activity mm;
boolean flag_check = false;
int pos = 0;
int viewBackgroundImageName;
Bitmap texture;
SimpleMaterial planeMat;
int randPosition=1;
int change_value;
int Ripple_number,speed1;
Preferences preferences;
private MediaPlayer myplayer;
private boolean sound;
public RipplesRenderer(Context context) {
super(context);
setFrameRate(50);
this.mContext=context;
randPosition = BitmapUpdate.randomGenerator;
texture = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.gthree_one);
//sp=mContext.getSharedPreferences("wallpapersettings",0);
preferences=new Preferences(mContext);
}
protected void initScene() {
if(randPosition!=1) {
texture = BitmapUpdate.bit;
}
mCamera.setPosition(0, 0, -9);
DirectionalLight light = new DirectionalLight(0, 0, 1);
light.setPower(1f);
BaseObject3D group = new BaseObject3D();
DiffuseMaterial material = new DiffuseMaterial();
material.setUseColor(true);
mScreenHeight = GNWallpaper.hieght;
mScreenWeight = GNWallpaper.weight;
Random rnd = new Random();
planeMat = new SimpleMaterial();
Plane plane=new Plane(9,7,1,1);
//Plane plane = new Plane(4, 4, 1, 1);
plane.setRotZ(-90);
plane.setScale(1.0f);
plane.setMaterial(planeMat);
addChild(plane);
mFilter = new TouchRippleFilter();
mPostProcessingRenderer.setQuadSegments(QUAD_SEGMENTS);
mPostProcessingRenderer.setQuality(PostProcessingQuality.MEDIUM);
addPostProcessingFilter(mFilter);
}
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
if (pos != com.themebowlapp.galaxynote3livewallpaper.Gallery_Activity.wallpaper_position || randPosition != BitmapUpdate.randomGenerator) {
texture = BitmapUpdate.bit;
pos = com.themebowlapp.galaxynote3livewallpaper.Gallery_Activity.wallpaper_position;
randPosition = BitmapUpdate.randomGenerator;
}
Ripple_number=preferences.getSpeed_controler();
speed1=Ripple_number*100;
super.onSurfaceCreated(gl, config);
}
public void onDrawFrame(GL10 glUnused) {
super.onDrawFrame(glUnused);
mFilter.setTime((float) frameCount++ *.05f);
}
public void onSurfaceChanged(GL10 gl, int width, int height) {
super.onSurfaceChanged(gl, width, height);
mFilter.setScreenSize(width, height);
mFilter.setRippleSize((40+speed1));
planeMat.addTexture(mTextureManager.addTexture(texture));
}
public void setTouch(float x, float y) {
mFilter.addTouch(x, y, frameCount *.05f);
}
#Override
public void onTouchEvent(MotionEvent event) {
final int action = event.getAction();
if(event.getAction() == MotionEvent.ACTION_DOWN) {
//sound
myplayer = MediaPlayer.create(getContext(), R.raw.water_drop);
myplayer.setVolume(100, 100);
myplayer.start();
myplayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer myplayer) {
myplayer.release();
}
});
setTouch(event.getX() / mScreenWeight, 1.0f - (event.getY() / mScreenHeight));
}
super.onTouchEvent(event);
}
}
Settings.java
public class Settings extends Activity {
public TextView SettingTextObj, BackgroundTextObj;
private RelativeLayout chose_background;
public Preferences preferences;
Context cont = this;
private CheckBox soundcheckbox;
private String PREFRENCES_NAME;
SharedPreferences settings;
// private Button choosebackground;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
chose_background = (RelativeLayout) findViewById(R.id.BackgroundLayoutId);
BackgroundTextObj = (TextView) findViewById(R.id.backgroundTxtViewId);
soundcheckbox = (CheckBox)findViewById(R.id.checkBox1);
settings = getSharedPreferences(PREFRENCES_NAME, 0);
Boolean isChecked = settings.getBoolean("cbx1_ischecked", false);
soundcheckbox.setChecked(isChecked);
soundcheckbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
private MediaPlayer myplayer;
#Override
public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
Editor editor = getSharedPreferences(PREFRENCES_NAME, 0).edit();
editor.putBoolean("cbx1_ischecked", isChecked);
editor.commit();
Toast.makeText(getApplicationContext(), "Check", Toast.LENGTH_SHORT).show();
myplayer = MediaPlayer.create(getBaseContext(), R.raw.water_drop);
myplayer.setVolume(100, 100);
myplayer.start();
}
});
preferences = new Preferences(cont);
chose_background.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final String[] items = { "Phone Gallery", "Choose Background" };
AlertDialog.Builder builder = new AlertDialog.Builder(
Settings.this);
builder.setTitle("Pick a Background");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals(items[0])) {
startActivity(new Intent(Settings.this, PhoneGallery_Activity.class));
} else {
startActivity(new Intent(Settings.this, Gallery_Activity.class));
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.settings, menu);
return true;
}
}
GNWallpaper.java
public class GNWallpaper extends Wallpaper {
private RipplesRenderer mRenderer;
private String imageBg;
private int cvwidth;
private int cvheight;
private int visibleWidth;
private Bitmap bg;
private String LoadText;
private boolean sound;
private MediaPlayer myplayer;
public static WindowManager display;
static int height,width;
//private Integer[] mImageIds = { R.drawable.gthree_one,R.drawable.gthree_two,R.drawable.gthree_three, R.drawable.gthree_four, R.drawable.gthree_five, R.drawable.gthree_six,};
private int position;
public Engine onCreateEngine() {
display =(WindowManager) getSystemService(Context.WINDOW_SERVICE);
height= display.getDefaultDisplay().getHeight();
width= display.getDefaultDisplay().getWidth();
mRenderer = new RipplesRenderer(this);
//Log.i("shibbu"," hello");
return new WallpaperEngine(this.getSharedPreferences(SHARED_PREFS_NAME,
Context.MODE_PRIVATE), getBaseContext(), mRenderer, false);
}
public void onSharedPreferenceChanged(SharedPreferences prefs,
String key) {
imageBg = prefs.getString("image_custom", "Bad Image");
getBackground();
sound=prefs.getBoolean("pref_sound", false);
// //sound
// sound=prefs.getBoolean("pref_sound", false);
}
void getBackground() {
if (this.cvwidth == 0 || this.cvheight == 0 || this.visibleWidth == 0) {
this.cvwidth = 1290;
this.cvheight = 800;
this.visibleWidth = 1290;
}
if(new File(imageBg).exists()) {
int SampleSize = 1;
do {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
bg = BitmapFactory.decodeFile(imageBg, options);
SampleSize = (int) (Math.ceil(options.outWidth/(this.visibleWidth * 2))*2);
options.inJustDecodeBounds = false;
try {
options.inSampleSize = SampleSize;
bg = BitmapFactory.decodeFile(imageBg, options);
} catch (OutOfMemoryError e) {
SampleSize = SampleSize * 2;
}
} while (bg == null);
bg = Bitmap.createScaledBitmap(bg, this.cvwidth/2, this.cvheight, true);
} else {
bg = BitmapFactory.decodeResource(getResources(), R.drawable.gthree_one);
//bg = BitmapFactory.decodeResource(getResources(), mImageIds[position]);
//position++;
bg = Bitmap.createScaledBitmap(bg, this.cvwidth/2, this.cvheight, true);
LoadText = "";
}
}
}
Refer this link.It will help you to change to landscape view..
http://tips4android.blogspot.in/2012/01/android-tips-how-to-get-screen.html
In my library project I have the following code to initialize the camera, and start previewing.
public class CameraView {
private SurfaceView preview;
private SurfaceHolder previewHolder;
private Camera camera;
private boolean activeCamera;
private boolean cameraConfigured;
private Activity activity;
private final static int NINTY_DEGREES = 90;
public CameraView(Activity activity) {
this.activity = activity;
View rootView;
LayoutInflater inflater = activity.getLayoutInflater();
rootView = inflater.inflate(R.layout.layout_cameraview, null);
preview = (SurfaceView) rootView.findViewById(R.id.surfaceView);
previewHolder = preview.getHolder();
previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
cameraConfigured = false;
}
private void initializeCamera(int w, int h) {
if(camera != null && previewHolder.getSurface() != null) {
try
{
camera.setPreviewDisplay(previewHolder);
}
catch(Exception e)
{
Log.e("Camera: ", e.getMessage());
}
if(!cameraConfigured) {
Camera.Parameters params = camera.getParameters();
Camera.Size size = getBestPreviewSize(w, h, params);
if(size != null) {
params.setPreviewSize(size.width, size.height);
cameraConfigured = true;
}
}
}
}
public void startCamera() {
camera = Camera.open();
previewHolder.addCallback(surfaceCallback);
}
public void stopCamera() {
stopPreviewingOnDisplay();
}
public void takePicture() {
View rootView;
LayoutInflater inflater = activity.getLayoutInflater();
rootView = inflater.inflate(R.layout.layout_cameraview, null);
Button capture = (Button) rootView.findViewById(R.id.capture);
capture.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.e("CameraView: ", "Capture button pressed!");
}
});
}
private void startPreviewingOnDisplay() {
if(camera != null) {
camera.setDisplayOrientation(NINTY_DEGREES);
camera.startPreview();
activeCamera = true;
}
}
private void stopPreviewingOnDisplay() {
if(camera != null && activeCamera) {
camera.stopPreview();
activeCamera = false;
}
}
private SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
initializeCamera(width, height);
startPreviewingOnDisplay();
Log.d("CameraView: ", "SurfaceChanged");
}
};
private Camera.Size getBestPreviewSize(int w, int h, Camera.Parameters params) {
Camera.Size result = null;
for(Camera.Size size : params.getSupportedPreviewSizes()) {
if(size.width < w && size.height <= h) {
if(result == null) {
result = size;
}
else {
int resultArea = result.width * result.height;
int newArea = size.width * size.height;
if(newArea > resultArea)
result = size;
}
}
}
return(result);
}
}
The usage of this class:
public class History extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
......
camera = new CameraView(this);
}
#Override
public void onResume() {
super.onResume();
Log.i("History.class", "onResume called!");
camera.startCamera();
}
#Override
public void onPause() {
super.onPause();
camera.stopCamera();
}
}
I've debugged the code, and I notice that the camera object is being intitalized, but there is nothing appearing on the screen, it should have previewed the camera. Could anyone see whats wrong with this approach?
Thanks.
I try to get orientation on my Android Emulator by SensorManager.getOrientation. Before this i use SensorManager.getRotationMatrix to get rotation matrix, but this always return false.
Here is code of my Activity:
public class MainActivity extends Activity implements SurfaceHolder.Callback, View.OnClickListener{
public final static String DEBUG_TAG = "MainActivity";
private SensorManager sensorManager;
private SurfaceView preview;
private float[] mGravs;
private float[] mGeoMags;
private float[] mRotationM;
private float[] mOrientation;
private Sensor mAccelerometer;
private Sensor mMagneticField;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
preview = (SurfaceView)findViewById(R.id.SurfaceView1);
sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
mAccelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mMagneticField = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
mGravs = new float[3];
mGeoMags = new float[3];
mRotationM = new float[16];
mOrientation = new float[3];
List<Sensor> sensorList = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (int nI = 0; nI < sensorList.size(); nI++) {
Log.d(DEBUG_TAG, sensorList.get(nI).getName());
}
}
private SensorEventListener sensorEventListener = new SensorEventListener() {
#Override
public void onSensorChanged(SensorEvent event)
{
synchronized (this) {
switch (event.sensor.getType()) {
case Sensor.TYPE_ACCELEROMETER:
System.arraycopy(event.values, 0, mGravs, 0, 3);
break;
case Sensor.TYPE_MAGNETIC_FIELD:
System.arraycopy(event.values, 0, mGeoMags, 0, 3);
break;
default:
return;
}
if (mGravs != null && mGeoMags != null) {
boolean bSuccess = SensorManager.getRotationMatrix(mRotationM, null, mGravs, mGeoMags);
if (bSuccess) {
SensorManager.getOrientation(mRotationM, mOrientation);
}
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
};
private boolean openHardware()
{
sensorManager.registerListener(sensorEventListener, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
sensorManager.registerListener(sensorEventListener, mMagneticField, SensorManager.SENSOR_DELAY_NORMAL);
return true;
}
private void closeHardware()
{
sensorManager.unregisterListener(sensorEventListener);
}
#Override
protected void onResume()
{
super.onResume();
openHardware();
}
#Override
protected void onPause()
{
super.onPause();
closeHardware();
}
#Override
protected void onStop()
{
closeHardware();
super.onStop();
}
}
Ok, this problem occur because magnetic field sensor always return [0.0, 0.0, 0.0].
How can i make magnetic field sensor return something else?
I had the same problem. Everything got false
This answer has helped me: https://stackoverflow.com/a/14224122/1549127