Proximity Sensor- Silence call application - java

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

Related

MediaPlayer and proximity sensor: toggling between speakerphone and earpiece

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

Android proximityalert app is crashing on button press

I am trying to write a simple app that takes the users current location and notifies them when they come near this location later. In my code I have it set up so that when the app starts it starts requesting location updates. Then when the button is pressed it takes the last known location and creates a proximity alert around that. my problem however is that when i press the button on both the emulator and the real phone it quickly crashes and i cant seem to find a reason why. is there an infinite loop i am some how missing? if there is a way to see the error messages from my phone that would also be very helpful.
Here is my code:
MainActivity.java
package com.YdidApplications.shotgun;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.Toast;
public class MainActivity extends Activity implements LocationListener
{
private ImageButton flagButton;
LocationManager lm;
double lat=0,long1=0; //Defining Latitude & Longitude
float radius=5; //Defining Radius
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lm=(LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(lm.GPS_PROVIDER,
10000, //Update every 10 sec
10, (LocationListener) this);
flagButton = (ImageButton) findViewById(R.id.FLAG);
onFlagPress();
}
public void onFlagPress()
{
flagButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
location();
}
});
}
public void location()
{
lm=(LocationManager) getSystemService(LOCATION_SERVICE);
lm.getLastKnownLocation(LOCATION_SERVICE);
Intent i= new Intent("com.adnan.proximityalert"); //Custom Action
PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), -1, i, 0);
lm.addProximityAlert(lat, long1, radius, -1, pi);
}
#Override
public void onLocationChanged(Location location) {
lat= location.getLatitude();
long1 = location.getLongitude();
Toast.makeText(null, lat+", "+long1, 0);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
ProximityReciever.java
package ProximityReciever;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.LocationManager;
import android.widget.Toast;
/*This is the Reciever for the Brodcast sent, here our app will be notified if the User is
* in the region specified by our proximity alert.You will have to register the reciever
* with the same Intent you broadcasted in the previous Java file
*
* #Author: Adnan A M
*/
public class ProximityReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
// The reciever gets the Context & the Intent that fired the broadcast as arg0 & agr1
String k=LocationManager.KEY_PROXIMITY_ENTERING;
// Key for determining whether user is leaving or entering
boolean state=arg1.getBooleanExtra(k, false);
//Gives whether the user is entering or leaving in boolean form
if(state){
// Call the Notification Service or anything else that you would like to do here
Toast.makeText(arg0, "Welcome to my Area", 600).show();
}else{
//Other custom Notification
Toast.makeText(arg0, "Thank you for visiting my Area,come back again !!", 600).show();
}
}
}
Any advise would be greatly appreciated.
Thanks,
Logan

Can't get android service to work

I'm very new to android. I want to create an application that turns off all sounds at the selected time. I created a service with some code and in Eclipse there's no errors, but when I press the button nothing happens. I can see in Application Manager that my program and the service SilentHours are running. Here's my code:
MainActivity.java
package com.example.silencecontrol;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
public final static String EXTRA_NAME = "sending silentHour value to service SilenceHours";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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;
}
public void setSilenceHours(View view) {
EditText editText1 = (EditText)findViewById(R.id.editText1);
TextView textView1 = (TextView)findViewById(R.id.textView1);
if(editText1.length() > 0) {
Intent intent = new Intent(this, SilentHours.class);
String editText1String = editText1.getText().toString();
int silentHour = Integer.parseInt(editText1String);
intent.putExtra(EXTRA_NAME, silentHour);
this.startService(intent);
} else {
textView1.setText("Please enter the silence hour. ");
}
}
}
SilentHours.java
package com.example.silencecontrol;
import java.util.Calendar;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.IBinder;
public class SilentHours extends Service {
public SilentHours() {
}
protected void onHandleIntent(Intent intent) {
int silentHour = Integer.parseInt(intent.getStringExtra(MainActivity.EXTRA_NAME));
Calendar calendar = Calendar.getInstance();
int currentTime = calendar.get(Calendar.HOUR_OF_DAY);
if(currentTime >= silentHour) {
AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamVolume(AudioManager.STREAM_RING, 0, 0);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
And by the way I can't #Override the onHandleIntent method. If I put the #Override annotation I get error:
The method onHandleIntent(Intent) of type SilentHours must override or implement a supertype method.
Is that annotation necessary?
The method you are looking for is named onStartCommand, not onHandleIntent.
And no, it's not necessary to add this annotation to an overriden method, it's just a very good practice as you can get sure that you respected the signature of the super class.
Let you IDE help you when you code. Simply type "on" then ask for completion to see which method you can override.

createAppView cannot be resolved or is not a field

I'm attempting to implement Google Analytics into my Android application however I'm following the example and it's giving me createAppView cannot be resolved or is not a field. I presume this is because it is not defined - but shouldn't it be defined in the example from google? I wouldn't expect them to make this kind of mistake and I have a feeling I'm doing something wrong on my end.
To see the example I'm using have a look under "complete example" here:
https://developers.google.com/analytics/devguides/collection/android/v3/advanced
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.graphics.drawable.AnimationDrawable;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.analytics.tracking.android.Fields;
import com.google.analytics.tracking.android.GAServiceManager;
import com.google.analytics.tracking.android.GoogleAnalytics;
import com.google.analytics.tracking.android.Logger.LogLevel;
import com.google.analytics.tracking.android.MapBuilder;
import com.google.analytics.tracking.android.Tracker;
import android.app.Application;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
#SuppressWarnings("unused")
public class StartActivity extends Activity {
private AnimationDrawable mGoButtonAnimation;
Context c;
boolean isAirPlaneMode;
int simState;
TelephonyManager tm;
boolean NetworkConnection = false;
AlertDialog mConfirmAlert = null;
private static GoogleAnalytics mGa;
private static Tracker mTracker;
private static final String GA_LABEL = "Google Analytics";
/*
* Google Analytics configuration values.
*/
// Placeholder property ID.
private static final String GA_PROPERTY_ID = "UA-XXXX-Y";
// Dispatch period in seconds.
private static final int GA_DISPATCH_PERIOD = 30;
// Prevent hits from being sent to reports, i.e. during testing.
private static final boolean GA_IS_DRY_RUN = false;
// GA Logger verbosity.
private static final LogLevel GA_LOG_VERBOSITY = LogLevel.INFO;
// Key used to store a user's tracking preferences in SharedPreferences.
private static final String TRACKING_PREF_KEY = "trackingPreference";
/*
* Method to handle basic Google Analytics initialization. This call will
* not block as all Google Analytics work occurs off the main thread.
*/
private void initializeGa() {
mGa = GoogleAnalytics.getInstance(this);
mTracker = mGa.getTracker(GA_PROPERTY_ID);
// Set dispatch period.
GAServiceManager.getInstance().setLocalDispatchPeriod(
GA_DISPATCH_PERIOD);
// Set dryRun flag.
mGa.setDryRun(GA_IS_DRY_RUN);
// Set Logger verbosity.
mGa.getLogger().setLogLevel(GA_LOG_VERBOSITY);
// Set the opt out flag when user updates a tracking preference.
SharedPreferences userPrefs = PreferenceManager
.getDefaultSharedPreferences(this);
userPrefs
.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(
SharedPreferences sharedPreferences, String key) {
if (key.equals(TRACKING_PREF_KEY)) {
GoogleAnalytics
.getInstance(getApplicationContext())
.setAppOptOut(
sharedPreferences.getBoolean(key,
false));
}
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start);
initializeGa();
StartActivity.getGaTracker().set(Fields.SCREEN_NAME, GA_LABEL);
tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
simState = tm.getSimState();
System.out.println("Sim State" + simState);
Button goButton = (Button) findViewById(R.id.go_button);
// Set GO button to drawable animation
goButton.setBackgroundResource(R.drawable.go_button_animation);
mGoButtonAnimation = (AnimationDrawable) goButton.getBackground();
// check network availability
NetworkConnection = CheckNetworkAvailability
.CheckNetworkAvailability(StartActivity.this);
if (!NetworkConnection) {
showAlert("Network Connection is not Available");
}
isAirPlaneMode = isAirplaneModeOn(StartActivity.this);
goButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Start UpdateActivity
if (simState == TelephonyManager.SIM_STATE_ABSENT) {
showAlert("Sim Card is absent, Please insert a Net10 Sim Card");
} else if (isAirPlaneMode != false) {
showAlert("Please Insert a Net10 Sim Card or Turn on the AirPlane Mode and Re-Run the app");
} else if (simState == TelephonyManager.SIM_STATE_NETWORK_LOCKED
|| simState == TelephonyManager.SIM_STATE_PIN_REQUIRED
|| simState == TelephonyManager.SIM_STATE_PUK_REQUIRED
|| simState == TelephonyManager.SIM_STATE_UNKNOWN) {
showAlert("Sim Card is absent, Please insert a Net10 Sim Card");
} else if (simState == TelephonyManager.SIM_STATE_READY) {
Intent i = new Intent(StartActivity.this,
UpdateActivity.class);
startActivity(i);
finish();
}
}
});
}
#Override
public void onStart() {
super.onStart();
// Send a screen view when the Activity is displayed to the user.
StartActivity.getGaTracker().send(MapBuilder.createAppView.build());
}
/*
* Returns the Google Analytics tracker.
*/
public static Tracker getGaTracker() {
return mTracker;
}
/*
* Returns the Google Analytics instance.
*/
public static GoogleAnalytics getGaInstance() {
return mGa;
}
/**
* * Gets the state of Airplane Mode. * * #param context * #return true if
* enabled.
*/
public static boolean isAirplaneModeOn(Context context) {
return Settings.System.getInt(context.getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, 0) != 0;
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
// Animate GO button when corresponding window is in focus
mGoButtonAnimation.start();
}
private void showAlert(String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message).setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
StartActivity.this.finish();
}
});
mConfirmAlert = builder.create();
mConfirmAlert.show();
}
}
It's a typo within the example provided by Google. Actually, createAppView is a method and not variable, then:
StartActivity.getGaTracker().send(MapBuilder.createAppView.build());
should be:
StartActivity.getGaTracker().send(MapBuilder.createAppView().build());
Instead of MapBuilder.createAppView, it should be HitBuilders.ScreenViewBuilder() in Google Analytics API v4
replace
StartActivity.getGaTracker().send(MapBuilder.createAppView().build());
to
StartActivity.getGaTracker().send(HitBuilders.ScreenViewBuilder().build());

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.

Categories