MediaPlayer and proximity sensor: toggling between speakerphone and earpiece - java

I'm new to Android! I'm programming a simple Media Player and I want to toggle between speakerphone and earpiece when the audio is playing. I set up a proximity sensor and when the device is close to the ear I want it to play through the earpiece and vice versa. At the moment I wrote this code:
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements SensorEventListener{
TextView proxText;
SensorManager sm;
Sensor proxSensor;
MediaPlayer mp;
AudioManager am;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mp = MediaPlayer.create(this, R.raw.audio);
mp.start();
am =(AudioManager)getSystemService(Context.AUDIO_SERVICE);
sm = (SensorManager) getSystemService(SENSOR_SERVICE);
proxSensor = sm.getDefaultSensor(Sensor.TYPE_PROXIMITY);
proxText = (TextView) findViewById(R.id.proximityTextView);
sm.registerListener(this,proxSensor, SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
public void onSensorChanged(SensorEvent event) {
if(event.values[0]<event.sensor.getMaximumRange()){
proxText.setText("close");
mp.setAudioStreamType(am.STREAM_VOICE_CALL);
}
else
proxText.setText("far");
mp.setAudioStreamType(am.STREAM_MUSIC);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
but it doesn't work... I think I didn't set up correctly either the MediaPlayer and the AudioManager.
Could you please help me? Thank you in advance! ;-)

Related

Android Studio Java MediaPlayer plays only the first second of audio and then stops

I'm trying to have MediaPlayer play a roughly two minute long mp3 audio, however only the first second is played then the player stops. I've tired both mp3 and wav formats. Here's my code:
package com.pi.audiodemo;
import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MediaPlayer mediaPlayer = (MediaPlayer) MediaPlayer.create(this, R.raw.dumb);
mediaPlayer.start();
}
}
You create MediaPlayer within the onCreate function. So it will be deleted right after function returns. Try the following code:
package com.pi.audiodemo;
import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mediaPlayer = (MediaPlayer) MediaPlayer.create(this, R.raw.dumb);
mediaPlayer.start();
}
}

How to use new class wiith media player in main activity?

I'm trying to create new class, becouse I will have there many of sound file, but I don't know how to use it in main ativity. Here is my example code of sound.java:
package app.damian.komunikat_v1;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
public class sound extends MainActivity{
final MediaPlayer sound1 = MediaPlayer.create(this,R.raw.miau);
final MediaPlayer sound2 = MediaPlayer.create(this,R.raw.lol);
}
And now i'm trying to use sound1.start(); in main activity, but i don't know how. Any suggestions?
EDIT:
This is my MainActivity.java:
this is my MainActivity.java:
package app.damian.komunikat_v1;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button guzik = findViewById(R.id.button);
final MediaPlayer sound1 = MediaPlayer.create(this,R.raw.miau);
guzik.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sound1.start();
};
});
}
}
I found a different solution. Instead of creating new class with list of sound file, I had created an array of sounds in main activity class.

I can't get my scan results to display in android

When I run my app on a rooted device the ListView is blank and I am not sure why?
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.content.Context;
import android.content.BroadcastReceiver;
import android.content.Intent;
import java.util.List;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.widget.Toast;
This is my main class:
public class Network_List extends AppCompatActivity {
WifiManager wifiM;
WifiScanReciever wifiR;
ListView networklist;
String wifis[];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_network__list);
Search box for searching networks (not yet implemented so don't worry about it)
EditText searchNet = (EditText) findViewById(R.id.networkEditText);
This is the main list to display the network information
networklist = (ListView) findViewById(R.id.networkList);
Search button for the EditText (This is for future development)
Button networkButton = (Button) findViewById(R.id.searchButton);
scanButton is a button that starts the scan
Button scanButton = (Button) findViewById(R.id.buttonScan);
Declares wifiM as wifi manager and gets service
wifiM = (WifiManager) getSystemService(Context.WIFI_SERVICE);
Declares wifiR as WifiScanReciever
wifiR = new WifiScanReciever();
Button for starting the scan
scanButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
wifiM.startScan();
}
});
}
protected void onPause(){
unregisterReceiver(wifiR);
super.onPause();
}
protected void onResume(){
registerReceiver(wifiR, new IntentFilter(wifiM.SCAN_RESULTS_AVAILABLE_ACTION));
super.onResume();
}
This receives the scan results and puts it an array called wifis. onReceive captures scan results and sets the size of the array wifis.
private class WifiScanReciever extends BroadcastReceiver{
public void onReceive(Context c, Intent intent){
List<ScanResult> wifiSList = wifiM.getScanResults();
wifis = new String[wifiSList.size()];
for (int x = 0; x<wifiSList.size(); x++){
wifis[x] = ((wifiSList.get(x)).toString());
}
networklist.setAdapter(new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,wifis));
}
}
}

TYPE_ROTATION_VECTOR not working on certain devices

i have made a program that uses TYPE_ROTATION_VECTOR to get orientation of the mobile phone.. the program works on certain samsung galaxy s phone but not on sony xperia neo v.. all phones have android version with api >= 9.. what could be the problem ?
package com.example.sensortest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity implements SensorEventListener{
TextView t1,t2,t3;
private SensorManager mSensorManager;
private Sensor mRotVectSensor;
private float[] orientationVals=new float[3];
private float[] mRotationMatrix=new float[16];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1=(TextView)findViewById(R.id.TextView1);
t2=(TextView)findViewById(R.id.TextView2);
t3=(TextView)findViewById(R.id.TextView3);
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mRotVectSensor=mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
}
#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;
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
public void onSensorChanged(SensorEvent event)
{
if(event.sensor.getType()==Sensor.TYPE_ROTATION_VECTOR)
{
SensorManager.getRotationMatrixFromVector(mRotationMatrix,event.values);
SensorManager.remapCoordinateSystem(mRotationMatrix,SensorManager.AXIS_X, SensorManager.AXIS_Z, mRotationMatrix);
SensorManager.getOrientation(mRotationMatrix, orientationVals);
orientationVals[0]=(float)Math.toDegrees(orientationVals[0]);
orientationVals[1]=(float)Math.toDegrees(orientationVals[1]);
orientationVals[2]=(float)Math.toDegrees(orientationVals[2]);
t1.setText(String.valueOf(orientationVals[0]));
t2.setText(String.valueOf(orientationVals[1]));
t3.setText(String.valueOf(orientationVals[2]));
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
protected void onResume() {
super.onResume();
// register this class as a listener for the orientation and
// accelerometer sensors
mSensorManager.registerListener(this,
mRotVectSensor,
10000);
}
#Override
protected void onPause() {
// unregister listener
super.onPause();
mSensorManager.unregisterListener(this);
}
}
You have to check mRotVectSensor for null value. For Sensor.TYPE_ROTATION_VECTOR the device has to have a gyroscope.
I may not solve your problem, but make sure you're using different matrices in SensorManager.remapCoordinateSystem (see Documentation). There it says: (Parameter) outR- the transformed rotation matrix. inR and outR should not be the same array.

Proximity Sensor- Silence call application

I am trying to build an android application that silences a call when a person waves his/her hand over the phone as it starts ringing/vibrating using the Proximity sensor.
I am new to android development.
I have tried to make the application check if the phone is in State-Rining. If it is, then the app checks if the value of the proximity sensor ==0 (near value). If the value for proximity sensor is 0, it implies that the sensor was cover during the ringing ad hence it should mute the call.
But it is still in ringing state.
I think the problem is that the ServiceReceiver only checks for the value of the proximity sensor just as the phone starts to ring. If the sensor value is not zero at that instant, the phone doesn't get silenced.
So how can I make it check for a change in value of proximity sensor throughout the ringing or incoming call such that as soon as the sensor value turns to zero, call is silenced
The first class "mainactivity" contains the code for proximity sensor.
package example.ringcheck;
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.media.AudioManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity implements SensorEventListener {
static TextView proxText;
SensorManager sm;
Sensor proxSensor;
static float proxValue = 8;
// static boolean muteCall = false;
private AudioManager amanager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sm = (SensorManager) getSystemService(SENSOR_SERVICE);
proxSensor = sm.getDefaultSensor(Sensor.TYPE_PROXIMITY);
proxText = (TextView) findViewById(R.id.ProximityTextView);
sm.registerListener(this, proxSensor, SensorManager.SENSOR_DELAY_NORMAL);
}
#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 void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
proxText.setText(String.valueOf(event.values[0]));
proxValue = event.values[0];
Log.d("SENSOR VALUE", "********" + proxValue + "*******");
}
}
The second class "ServiceReceiver" contains the code for proximity sensor.
package example.ringcheck;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.telephony.TelephonyManager
import android.util.Log;
public class ServiceReceiver extends BroadcastReceiver {
private AudioManager amanager;
// static boolean isRinging = false;
public void onReceive(Context context, Intent intent) {
if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_RINGING)) {
// isRinging = true;
if (MainActivity.proxValue == 0) {
amanager = (AudioManager) context
.getSystemService(Context.AUDIO_SERVICE);
amanager.setRingerMode(0x00000000);
// isRinging = false;
}
Log.d("MPR", "Its Ringing");
}
}
}
Thanks in advance :-)
Instead of
amanager.setRingerMode(0x00000000);
Try
amanager.setStreamMute(AudioManager.STREAM_RING, true);

Categories