MediaPlayer plays double sounds on change orientation - java

I have a big problem with this app. The problem with it is that when the orientation changes to landscape and then change it to portrait the music twice tracks plays at the same time. But when i start the app on portrait i have no problem with it.
package com.phone.sensor;
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
public class sensorActivity extends Activity implements SensorEventListener{
public boolean musStatus = false;
public boolean musDeclare = true;
public MediaPlayer mp = null;
Sensor accelerometer;
SensorManager sm;
TextView acceleration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState == null){
if(mp != null){
mp.stop();
mp.reset();
mp = null;
}
} else {
if(mp != null){
mp.stop();
mp.reset();
mp = null;
}
}
setContentView(R.layout.activity_main);
sm=(SensorManager) getSystemService(SENSOR_SERVICE);
accelerometer=sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sm.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
acceleration=(TextView)findViewById(R.id.acceleration);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
#Override
public void onSaveInstanceState (Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putBoolean("musStatus", musStatus);
outState.putBoolean("musDeclare", musDeclare);
}
public Object onRetainCustomNonConfigurationInstance() {
return this.mp;
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
acceleration.setText("X: "+event.values[0]+
"\nY: "+event.values[1]+
"\nZ: "+event.values[2]);
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
if(y > 8.9) {
if(musDeclare == true)
{
mp = MediaPlayer.create(this, R.raw.alexander);
musDeclare = false;
}
if(musStatus == false)
{
mp.start();
musStatus = true;
}
}
if(y < 5)
{
if(musStatus == true)
{
mp.stop();
mp.reset();
mp = null;
musStatus = false;
musDeclare = true;
}
}
}
}

Try putting this block of code in the OnPause method of your class
if(mp != null && mp.IsPlaying()){
mp.stop();
mp.reset();
mp = null;
}
}

Related

Android game loop thread crash

I am very new to programming and I have a problem with a game which I am trying to make.
Almost every time when I exit the game it was crashing.
After adding: if (canvas != null) beforew canvas.drawColor(Color.CYAN); it does not crash on exit anymore but when I return to the game.
Here is the code: (its not my actual game... there is nothing in OnDraw exept canvas.drawColor(Color.CYAN); that keeps it simple)
GameView.java:
package com.example.test.threadtest;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class GameView extends SurfaceView {
private GameLoopThread theGameLoopThread;
private SurfaceHolder surfaceHolder;
public GameView(Context context) {
super(context);
theGameLoopThread = new GameLoopThread(this);
surfaceHolder = getHolder();
surfaceHolder.addCallback(new SurfaceHolder.Callback() {
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
theGameLoopThread.setRunning(false);
while (retry) {
try {
theGameLoopThread.join();
retry = false;
} catch (InterruptedException e) {
}
}
}
public void surfaceCreated(SurfaceHolder holder) {
theGameLoopThread.setRunning(true);
theGameLoopThread.start();
}
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
// TODO Auto-generated method stub
}
});
}
#Override
protected void onDraw(Canvas canvas) {
if (canvas != null)
canvas.drawColor(Color.CYAN);
}
}
GameLoopThread.java:
package com.example.test.threadtest;
import android.annotation.SuppressLint;
import android.graphics.Canvas;
public class GameLoopThread extends Thread {
static final long FPS = 20;
private GameView theView;
private boolean isRunning = false;
public GameLoopThread(GameView theView) {
this.theView = theView;
}
public void setRunning(boolean run) {
isRunning = run;
}
#SuppressLint("WrongCall") #Override
public void run() {
long TPS = 1000 / FPS;
long startTime, sleepTime;
while (isRunning) {
Canvas theCanvas = null;
startTime = System.currentTimeMillis();
try {
theCanvas = theView.getHolder().lockCanvas();
synchronized (theView.getHolder()) {
theView.onDraw(theCanvas);
}
} finally {
if (theCanvas != null) {
theView.getHolder().unlockCanvasAndPost(theCanvas);
}
}
sleepTime = TPS - (System.currentTimeMillis() - startTime);
try {
if (sleepTime > 0)
sleep(sleepTime);
else
sleep(10);
} catch (Exception e) {
}
}
}
}
MainAcitvity.java:
package com.example.test.threadtest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new GameView(this));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

How can I get the longitude and latitude in my android app?

I've been trying to get the location for the particular phone for a while now. I have used the following code but instead of showing the location it will just crash when I try and run the app in my emulator.
Once I've got the longitude and latitude I am going to use it to map the current location on a google map!
public class Homescreen extends ActionBarActivity implements LocationListener {
final TextView t = (TextView)findViewById(R.id.textView1);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homescreen);
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.homescreen, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
int latitude = (int) (location.getLatitude());
int longitude = (int) (location.getLongitude());
t.setText(latitude);
// Log.i("Geo_Location", "Latitude: " + latitude + ", Longitude: " + longitude);
}
Use This Activity. I hope it will help you.
package yourPackage;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.infologitech.spotways.constants.SpotwaysSettingsKeys.SettingDefaultValue;
import com.infologitech.spotways.constants.SpotwaysSettingsKeys.SettingKey;
import com.infologitech.spotways.custom.TransactionSupport;
public class GetCurrentLocationActivity extends Activity implements
LocationListener, ConnectionCallbacks, OnConnectionFailedListener {
private Context context = this;
private LocationClient mLocationClient;
private LocationRequest mLocationRequest;
private Location mLocation;
private float minAccuracy = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (checkPlayServices()) {
mLocationClient = new LocationClient(this, this, this);
mLocationClient.connect();
//waitForLocation();
}else finish();
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
}
#Override
public void onConnected(Bundle arg0) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(5 * 1000);
mLocationRequest.setFastestInterval(2 * 1000);
mLocationRequest.setSmallestDisplacement(5f);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationClient.requestLocationUpdates(mLocationRequest, this);
}
#Override
public void onDisconnected() {
}
#Override
public void onLocationChanged(Location loc) {
if (loc != null) {
int latitude = (int) (loc.getLatitude());
int longitude = (int) (loc.getLongitude());
Toast.makeText(this,"Lat "+latitude+", Lng "+longitude);
}
}
#Override
protected void onDestroy() {
stopUpdate();
super.onDestroy();
}
private void stopUpdate() {
try {
mLocationClient.removeLocationUpdates(this);
mLocationClient.disconnect();
} catch (Exception e) {
}
}
public boolean checkPlayServices() {
final int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(
resultCode, context, 3434);
if (dialog != null) {
dialog.show();
dialog.setOnDismissListener(new OnDismissListener() {
public void onDismiss(DialogInterface dialog) {
if (ConnectionResult.SERVICE_INVALID == resultCode) {
}
}
});
return false;
}
}
return false;
}
return true;
}
}

Issue with using Accelerometer and GPS at the same time in Android Studio

I'm pretty new to programming in android studio, and I've been trying to figure this out for a while, but I'm not sure what the problem is. I'm trying to use a combination of the Accelerometer and GPS at the same time to get a more accurate number for the acceleration and speed of the device, but when I try to start the accelerometer it throws this exception:
java.lang.RuntimeException: Unable to start activity ComponentInfo
Caused by: java.lang.IllegalStateException: System services not available to Activities before onCreate()
Here is the MainActivity:
package com.example.accelerometergps;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity implements LocationListener {
private Accelerometer a;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager l = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
l.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
this.onLocationChanged(null);
a = new Accelerometer();
//It works fine if I remove the following line
a.registerListener();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onLocationChanged(Location location) {
TextView tv = (TextView) findViewById(R.id.textView);
if (location == null) {
tv.setText("no GPS");
} else {
double temp = location.getSpeed();
double speed = 2.23694 * temp;
// tv.setText(String.valueOf(speed));
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
Here is the Accelerometer Class:
package com.example.accelerometergps;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
public class Accelerometer extends Activity implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mAccelerometer;
double[] accelerationList = new double[5];
double averageAcceleration;
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void registerListener() {
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
public void unregisterListener() {
mSensorManager.unregisterListener(this);
}
#Override
public void onSensorChanged(SensorEvent event) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
double temp = sumAcceleration(x, y, z);
addToList(temp);
averageAcceleration = accelerationListAverage();
}
public double sumAcceleration(float i, float j, float k) {
float temp = i * i + j * j + k * k;
double linearAcceleration = Math.sqrt(temp) - 9.8;
return linearAcceleration;
}
public double accelerationListAverage() {
double sum = 0;
for (int i = 0; i < 5; i++) {
sum += accelerationList[i];
}
return (sum / 5);
}
public void addToList(double a) {
double b = accelerationList[0];
double c = accelerationList[1];
double d = accelerationList[2];
double e = accelerationList[3];
accelerationList[0] = a;
accelerationList[1] = b;
accelerationList[2] = c;
accelerationList[3] = d;
accelerationList[4] = e;
}
public double getAcceleration() {
return averageAcceleration;
}
}
Any help or suggestions would be greatly appreciated, thank you in advance.
You should NEVER create an activity directly. Your MainActivity is holding an Accelerometer, which is of type Activity. That's just wrong. You need to rearchitect things so Accelerometer is not an Activity. It should be passed in a Context to grab anything it needs from the current Activity.

OnCompletionListener is not working

I'm trying to get videos to play on my Android app back-to-back and only after each video's been watched in its entirety.
I've come up with the following code:
package com.davekelley;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.media.MediaPlayer;
import android.net.Uri;
import android.widget.MediaController;
import android.widget.VideoView;
public class Watch extends Activity {
MediaPlayer player;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_watch);
player = new MediaPlayer();
player.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.stop();
mp.release();
int i = 0;
if (i < 2) {
i++;
String path="http://domain.com/videos/"+i+".mp4";
playVideo(path);
}
else i=0;
}
});
player.start();
}
private void playVideo(String filename) {
try {
player.setDataSource(filename);
player.prepare();
player.start();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.watch, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
But I can't even run it because Eclipse tells me that "The method setOnCompletionListener(MediaPlayer.OnCompletionListener) in the type MediaPlayer is not applicable for the arguments (new OnCompletionListener(){})".
What is causing this? How about the rest of my code...would it achieve what I'm trying to make? Thanks.
copy this lines
String path="http://domain.com/videos/"+i+".mp4";
playVideo(path);
after
player = new MediaPlayer();
Try to play first video and set OnCompletionListener for media player which give you call back when first video completed then try to check for second video with new player instance in your case you never set data source for first video just intialize player instance and set OnCompletionListener which never called becz not set first video data source.
private MediaPlayer player;
private int i = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playVideo("http://domain.com/videos/"+i+".mp4\"");
}
public void playVideo(String path){
try{
player = new MediaPlayer();
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setDataSource(path);
player.prepareAsync();
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
player.release();
player = null;
if(i<2){
playVideo("http://domain.com/videos/"+(++i)+".mp4");
}
}
});
}catch (Exception e){
e.printStackTrace();
}
}

Android - GMapsV2 - Why is my activity not drawing the polyline?

I'm trying to get a red polyline to draw whenever the user moves. Here is the following code I have:
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.LocationSource;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.PolylineOptions;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements LocationSource, LocationListener {
final int RQS_GooglePlayServices = 1;
private GoogleMap myMap;
TextView tvLocInfo;
LocationManager myLocationManager = null;
OnLocationChangedListener myLocationListener = null;
Criteria myCriteria;
Location lastLocationloc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvLocInfo = (TextView)findViewById(R.id.locinfo);
FragmentManager myFragmentManager = getFragmentManager();
MapFragment myMapFragment
= (MapFragment)myFragmentManager.findFragmentById(R.id.map);
myMap = myMapFragment.getMap();
myMap.setMyLocationEnabled(true);
myMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
myCriteria = new Criteria();
myCriteria.setAccuracy(Criteria.ACCURACY_FINE);
myLocationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_legalnotices:
String LicenseInfo = GooglePlayServicesUtil.getOpenSourceSoftwareLicenseInfo(
getApplicationContext());
AlertDialog.Builder LicenseDialog = new AlertDialog.Builder(MainActivity.this);
LicenseDialog.setTitle("Legal Notices");
LicenseDialog.setMessage(LicenseInfo);
LicenseDialog.show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
if (resultCode == ConnectionResult.SUCCESS){
Toast.makeText(getApplicationContext(),
"isGooglePlayServicesAvailable SUCCESS",
Toast.LENGTH_LONG).show();
//Register for location updates using a Criteria, and a callback on the specified looper thread.
myLocationManager.requestLocationUpdates(
0L, //minTime
0.0f, //minDistance
myCriteria, //criteria
this, //listener
null); //looper
//Replaces the location source of the my-location layer.
myMap.setLocationSource(this);
}else{
GooglePlayServicesUtil.getErrorDialog(resultCode, this, RQS_GooglePlayServices);
}
}
#Override
protected void onPause() {
myMap.setLocationSource(null);
myLocationManager.removeUpdates(this);
super.onPause();
}
#Override
public void activate(OnLocationChangedListener listener) {
myLocationListener = listener;
}
#Override
public void deactivate() {
myLocationListener = null;
}
/*#Override
public void onLocationChanged(Location location) {
if (myLocationListener != null) {
myLocationListener.onLocationChanged(location);
double lat = location.getLatitude();
double lon = location.getLongitude();
tvLocInfo.setText(
"lat: " + lat + "\n" +
"lon: " + lon);
}
}*/
#Override
public void onLocationChanged(Location location) {
if (lastLocationloc == null) {
lastLocationloc = location;
}
LatLng lastLatLng = locationToLatLng(lastLocationloc);
LatLng thisLatLng = locationToLatLng(location);
//Log.e(TAG, "Last LatLng is :"+lastLatLng);
//Log.e(TAG, "Last LatLng is :"+thisLatLng);
myMap.addPolyline(new PolylineOptions().add(lastLatLng).add(thisLatLng).width(3).color(Color.RED));
lastLocationloc = location;
}
public static LatLng locationToLatLng(Location loc) {
if (loc != null)
return new LatLng(loc.getLatitude(), loc.getLongitude());
return null;
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
When I go to run application on an actual device nothing happens. No polyline appears. What am I doing wrong?

Categories