What I want is that when my app is in background and I shake the phone the app should start and come on foreground!
To achieve this I have used broadcast receiver as follows :
public class BootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
mSensorManager = (SensorManager) arg0.getSystemService(arg0.SENSOR_SERVICE);
mSensorManager.registerListener( mSensorIntentListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
}
}
I have registered it also as follows :
<receiver
android:name=".BootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
Now for shake event I am using this code as given below :
private final SensorEventListener mSensorIntentListener = new SensorEventListener() {
public void onSensorChanged(SensorEvent se) {
float x = se.values[0];
float y = se.values[1];
float z = se.values[2];
mAccelLast = mAccelCurrent;
mAccelCurrent = (float) Math.sqrt((double) (x*x + y*y + z*z));
float delta = mAccelCurrent - mAccelLast;
mAccel = mAccel * 0.9f + delta; // perform low-cut filter
if (mAccel > 12) {
Toast.makeText(getApplicationContext(), "Device has shaken.", Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(), MainActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
};
Now when I try to run the app and put it on background and shake it doesn't works !
So what is the logical error and how to make my app come foreground on shake ?
One more thing I am using nested classes concept so all classes are in MainActivity class !
code full !
:
package com.example.sensorlist;
public class MainActivity extends ActionBarActivity {
TextView tv1=null;
static File file = null;
private String outputFile = null;
private float mAccel; // acceleration apart from gravity
private float mAccelCurrent; // current acceleration including gravity
private float mAccelLast; // last acceleration including gravity
Button play,stop,record;
MediaRecorder myAudioRecorder;
public SensorManager mSensorManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play=(Button)findViewById(R.id.button3);
stop=(Button)findViewById(R.id.button2);
record=(Button)findViewById(R.id.button);
stop.setEnabled(false);
play.setEnabled(false);
final File path =
Environment.getExternalStoragePublicDirectory
(
//Environment.DIRECTORY_PICTURES
//Environment.DIRECTORY_DCIM
Environment.DIRECTORY_DCIM + "/Utkarshrecord/"
);
// Make sure the sound directory exists.
if(!path.exists())
{
path.mkdirs();
}
try {
file= File.createTempFile("sound", ".3gp", path);
myAudioRecorder=new MediaRecorder();
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setOutputFile(file.getAbsolutePath());
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
if( mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)!=null){
Toast.makeText(getBaseContext(), "Yes it is there ", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getBaseContext(), "Sry no accelerometer", Toast.LENGTH_LONG).show();
}
mSensorManager.registerListener(mSensorListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
mAccel = 0.00f;
mAccelCurrent = SensorManager.GRAVITY_EARTH;
mAccelLast = SensorManager.GRAVITY_EARTH;
record.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
myAudioRecorder.prepare();
myAudioRecorder.start();
}
catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
record.setEnabled(false);
stop.setEnabled(true);
Toast.makeText(getApplicationContext(), "Recording started", Toast.LENGTH_LONG).show();
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) throws IllegalArgumentException,SecurityException,IllegalStateException {
try{
myAudioRecorder.stop();
myAudioRecorder.release();
myAudioRecorder = null;
}catch(Exception e){
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Audio recorded successfully",Toast.LENGTH_LONG).show();
stop.setEnabled(false);
play.setEnabled(true);
}
});
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) throws IllegalArgumentException,SecurityException,IllegalStateException {
MediaPlayer m = new MediaPlayer();
try {
m.setDataSource(file.getAbsolutePath());
m.prepare();
}
catch (IOException e) {
e.printStackTrace();
}
m.start();
Toast.makeText(getApplicationContext(), "Playing audio", Toast.LENGTH_LONG).show();
}
});
}
private final SensorEventListener mSensorListener = new SensorEventListener() {
public void onSensorChanged(SensorEvent se) {
float x = se.values[0];
float y = se.values[1];
float z = se.values[2];
mAccelLast = mAccelCurrent;
mAccelCurrent = (float) Math.sqrt((double) (x*x + y*y + z*z));
float delta = mAccelCurrent - mAccelLast;
mAccel = mAccel * 0.9f + delta; // perform low-cut filter
if (mAccel > 12) {
Toast.makeText(getApplicationContext(), "Device has shaken.", Toast.LENGTH_LONG).show();
try {
myAudioRecorder.prepare();
myAudioRecorder.start();
record.setEnabled(false);
stop.setEnabled(true);
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(getBaseContext(), "recording has started", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
};
private final SensorEventListener mSensorIntentListener = new SensorEventListener() {
public void onSensorChanged(SensorEvent se) {
float x = se.values[0];
float y = se.values[1];
float z = se.values[2];
mAccelLast = mAccelCurrent;
mAccelCurrent = (float) Math.sqrt((double) (x*x + y*y + z*z));
float delta = mAccelCurrent - mAccelLast;
mAccel = mAccel * 0.9f + delta; // perform low-cut filter
if (mAccel > 12) {
Toast.makeText(getApplicationContext(), "Device has shaken.", Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(), MainActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
};
#Override
protected void onPause() {
mSensorManager.unregisterListener(mSensorListener);
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(mSensorListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), 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.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public class ShakeRec extends Service{
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
return super.onStartCommand(intent, flags, startId);
}
}
public class BootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
mSensorManager = (SensorManager) arg0.getSystemService(arg0.SENSOR_SERVICE);
mSensorManager.registerListener( mSensorIntentListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
}
}
}
Your <receiver> element will not work. If you were to look at LogCat on a reboot, you would see warnings or errors from Android, saying that it cannot find your BootReceiver class. A manifest-registered receiver cannot be a nested class inside of an activity.
Get rid of the <receiver> element. Get rid of BootReceiver. Register your SensorEventListener in onCreate() of your activity. So long as your process is running (which may not be very long), and so long as the device is turned on, you should receive sensor events.
To capture shakes you should use always-on low power sensors, registered in a wakelocked sticky service. To reach a great amount of devices, your app should find what of that low power sensors are available in the phone. And then use the best combination, minimizing battery power drain. You will need also to ensure your app is whitelisted for battery optimization, so your app can survive in background.
Related
I'm trying to write the codes for my project that's to play a music when WiFi connection is disconnected and also whenever user clicks 'test' button it display the current connection strength. I've tried the following code:
Main activity part (for the test button and call out the class AlarmManagerBroadcastReceiver :
public class MainActivity extends FragmentActivity {
public static final String TAG = "Final Year Project";
private static boolean wifiConnected = false;
private static boolean mobileConnected = false;
private LogFragment mLogFragment;
private AlarmManagerBroadcastReceiver alarm ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sample_main);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
registerReceiver(alarm, intentFilter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// When the user clicks TEST, display the connection status.
case R.id.test_action:
checkNetworkStrengh();
return true;
// Clear the log view fragment.
case R.id.clear_action:
mLogFragment.getLogView().setText("");
return true;
}
return false;
}
private void checkNetworkStrengh() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo Info = cm.getActiveNetworkInfo();
if (Info == null || !Info.isConnectedOrConnecting()) {
Log.i(TAG, "No connection");
} else {
int netType = Info.getType();
int netSubtype = Info.getSubtype();
if (netType == ConnectivityManager.TYPE_WIFI) {
Log.i(TAG, "Wifi connection");
WifiManager wifiManager = (WifiManager) getApplication().getSystemService(Context.WIFI_SERVICE);
List<ScanResult> scanResult = wifiManager.getScanResults();
for (int i = 0; i < scanResult.size();) {
Log.d("scanResult", "Speed of wifi" + scanResult.get(i).level);//The db level of signal //
// its okay now thanks guys //
}
} else if (netType == ConnectivityManager.TYPE_MOBILE) {
Log.i(TAG, "GPRS/3G connection");
// Need to get differentiate between 3G/GPRS
}
}
}
}
AlarmManagerBroadcastReceiver part (created in order to scan the current network connectivity all the time):
public class AlarmManagerBroadcastReceiver extends BroadcastReceiver {
private static boolean wifiConnected = false;
private static boolean mobileConnected = false;
#Override
public void onReceive(Context context, Intent intent) {
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
NetworkInfo networkInfo =
intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if (networkInfo.isConnected()) {
// Wifi is connected
Intent in = new Intent(context, RingService.class);
context.stopService(in);
} else {
Intent in = new Intent(context, RingService.class);
context.startService(in);
}
}
}
and the MusicService part(created in order to play a music whenever the class AlarmMAnagerBroadcastReceiver triggered the specific condition):
public class MusicService extends Service{
private MediaPlayer mp;
#SuppressWarnings("deprecation")
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
mp.start();
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
try {
mp.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
mp.setOnErrorListener(new MediaPlayer.OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
try {
mp.release();
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
});
super.onStart(intent, startId);
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
try {
mp = new MediaPlayer();
mp = MediaPlayer.create(MusicService.this, R.raw.ly);
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.onCreate();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
mp.stop();
mp.release();
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
Manifest file
<service
android:name="com.example.android.basicnetworking.RingService"
android:exported="true"
android:process=":remote" >
</service>
<receiver android:name=".AlarmManagerBroadcastReceiver" >
<intent-filter android:priority="100" android:enabled="true"
android:label="ConnectivityActionReceiver">
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.STATE_CHANGE" />
</intent-filter>
</receiver>
Can someone who's professional in android programming helps me in the code cause i'm new in android and java programming) to get return to checkConnectivity class in the AlarmManagerBroadcastReceiver part, and also to play a music when the wifi connection is lost.
Edit: thanks for the helps. I have figured it out. If anyone need the codes you can inbox me or I will upload the complete coding once everything is ok.
Edit: updated some code
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
int numberOfLevels = 5;
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int level = WifiManager.calculateSignalLevel(wifiInfo.getRssi(), numberOfLevels);
When you try to play the music AGAIN, then you need to prepare it again, so every time before start call prepare as well:
add this to AlarmManagerBroadcastReceiver:
void play(int musicId) {
MediaPlayer mp = MediaPlayer.create(getContext(), musicId);
mp.prepare();
mp.start();
}
and in checkConnectivity where you want to play music:
play(R.raw.ly); // or use other resource instead of ly
play sound on disconnection... try this:
public class NetworkReceiver extends BroadcastReceiver {
static boolean isConnect = false;
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "network changed");
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
if (activeNetwork != null) { // connected to the internet
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
Log.d(TAG, "network type wifi"); // connected on wifi
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
Log.d(TAG, "network type mobile"); // connected on mobile (3g/4g)
}
} else {
isConnect = false;
Log.d(TAG, "no connection"); // DISCONNECTED
playMySound(); // <- your play sound function
}
}
public void playMySound() {
MediaPlayer sound = MediaPlayer.create(context, R.raw.song);
sound.start();
}
}
im trying to implement the SensorEventListener but for some reason nothing happend.
ive tired to created a separate class for the listener but its still not working.
the service is running in a separate thread.(in the manifest android:process=":myproces")
public class Servicee extends Service {
private SensorManager sensorManager;
private long lastUpdate;
SensorEventListener listen;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
sensorManager = (SensorManager) getApplicationContext()
.getSystemService(SENSOR_SERVICE);
lastUpdate = System.currentTimeMillis();
listen = new SensorListen();
return START_STICKY;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Started", 1000).show();
super.onCreate();
}
private void getAccelerometer(SensorEvent event) {
float[] values = event.values;
// Movement
float x = values[0];
float y = values[1];
float z = values[2];
float accelationSquareRoot = (x * x + y * y + z * z)
/ (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH);
long actualTime = System.currentTimeMillis();
if (accelationSquareRoot >= 7) //
{
if (actualTime - lastUpdate < 2000) {
return;
}
lastUpdate = actualTime;
Toast.makeText(this,
"Device was shuffed _ " + accelationSquareRoot,
Toast.LENGTH_SHORT).show();
Vibrator v = (Vibrator) getApplicationContext().getSystemService(VIBRATOR_SERVICE);
v.vibrate(1000);
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
}
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
sensorManager.unregisterListener(listen);
Toast.makeText(this, "Destroy", Toast.LENGTH_SHORT).show();
super.onDestroy();
}
public class SensorListen implements SensorEventListener{
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
getAccelerometer(event);
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
}
what could possibly be wrong with it?
I believe the problem, at least with the code presented is that you never register to receive accelerometer events.
You need code to get the accelerometer sensor and to register; this should go in onStartCommand() right before the return.
Sensor accel = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(listen, accel, SensorManager.SENSOR_DELAY_NORMAL);
I want to get the values of the gyroscope and accelerometer in the phone.
The following is my code
public class MainActivity extends Activity implements SensorEventListener{
private SensorManager sensorManager;
private long lastUpdate;
private GPSTracker gpss;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
lastUpdate = System.currentTimeMillis();
}
#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 onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER && event.sensor.getType() == Sensor.TYPE_GRAVITY) {
getAccelerometer(event);
}
}
private void getAccelerometer(SensorEvent event) {
// TODO Auto-generated method stub
float[] values = event.values;
// Movement
float x = values[0];
float y = values[1];
float z = values[2];
float accelationSquareRoot = (x * x + y * y + z * z)
/ (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH);
long actualTime = System.currentTimeMillis();
if (accelationSquareRoot >= 10) //
{
if (actualTime - lastUpdate < 200) {
return;
}
lastUpdate = actualTime;
gpss = new GPSTracker(MainActivity.this);
if(gpss.canGetLocation()){
double latitude = gpss.getLatitude();
double longitude = gpss.getLongitude();
// \n is for new line
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gpss.showSettingsAlert();
}
}
}
#Override
protected void onResume() {
super.onResume();
// register this class as a listener for the orientation and
// accelerometer sensors
Sensor gsensor = sensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);
Sensor asensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(this,
gsensor,
SensorManager.SENSOR_DELAY_NORMAL);
sensorManager.registerListener(this,
asensor,
SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onPause() {
// unregister listener
super.onPause();
sensorManager.unregisterListener(this);
}
}
The code works fine if I use
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
getAccelerometer(event);
}
}
But when I include the *TYPE_GRAVITY* it doesn't work. I think I am making the mistake in the getType() function. Could someone tell me the correct syntax to detect two events simultaneously?
In your code here:
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER
&& event.sensor.getType() == Sensor.TYPE_GRAVITY) {
getAccelerometer(event);
}
}
You're getting the value for the event's type and asking if it's two different things at once. It's no different than having:
int a = 1;
if (a == 1 && a == 2) { ... }
Every SensorEvent is going to have exactly one type. If you want to call your method in either case, use || instead of && in your conditional.
If you want to act independently then you need to have two checks. switch() is a good way to go:
#Override
public void onSensorChanged(SensorEvent event) {
switch(event.sensor.getType()) {
case Sensor.TYPE_ACCELEROMETER:
getAccelerometer(event);
break;
case Sensor.TYPE_GRAVITY:
doSomethingDifferent();
break;
}
}
}
I've got a service that starts when i click a toggle button. It works well but when i click again the toggle i would expect the service stops but doesn't work. The service still go. This is the button(I'm using the preferences to save the state of the button):
check = (ToggleButton)v.findViewById(R.id.check1);
final SharedPreferences preferences = getActivity().getPreferences(Context.MODE_PRIVATE);
boolean tgprefshake = preferences.getBoolean("tgprefshake", false); //default is true
check.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){ //do this}
Log.d("Service", "onClick: starting srvice");
myService = new Intent(getActivity(), shakeService.class);
//getActivity().startService(new Intent(getActivity(), shakeService.class));
getActivity().startService(myService);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("tgprefshake", true); // value to store
editor.commit();
} else {
Log.d("Service", "onClick: stopping srvice");
//getActivity().stopService(new Intent(getActivity(), shakeService.class));
getActivity().stopService(myService);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("tgprefshake", false); // value to store
editor.commit();
}
}
});
if (tgprefshake) //if (tgpref) may be enough, not sure
{
check.setChecked(true);
}
else
{
check.setChecked(false);
}
And the service:
public class shakeService extends Service implements SensorEventListener{
// Sensors
public SensorManager sensorManager;
private long lastUpdate;
public ToggleButton check ;
public Sensor mAccelerometer;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public void onCreate()
{
Log.d("", "onCreate");
super.onCreate();
}
public void onDestroy() {
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
Log.d("Service", "onDestroy");
}
public void onStart(Intent intent, int startId)
{
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
lastUpdate = System.currentTimeMillis();
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
getWifiVibrating(event);
}
}
private void getWifiVibrating(SensorEvent event) {
//myVib.vibrate(50);
final WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
float[] values = event.values;
// Movement
float x = values[0];
float y = values[1];
float z = values[2];
float accelationSquareRoot = (x * x + y * y + z * z)
/ (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH);
long actualTime = System.currentTimeMillis();
if (accelationSquareRoot >= 3) {
if (actualTime - lastUpdate < 600) {
return;
}
lastUpdate = actualTime;
wifiManager.setWifiEnabled(true);
Toast.makeText(this, "Wi-fi On", Toast.LENGTH_SHORT)
.show();
}
}
public void onResume() {
// register this class as a listener for the orientation and
// accelerometer sensors
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
}
public void onPause() {
// unregister listener
sensorManager.unregisterListener(this);
}
Where is the error? It shows me "Service Stopped" when i turn off the toggle but still the service still works.
Call super.onDestroy() in the end of the service's onDestroy() impementation.
Have U think about memory leak? Every time onResume, U register the service as listener.
stopService() can not stop Service right now in android. The system will stop it completely in a proper time.
I'm developing an application. When i exit from the application, it will be opened again (The first activity is called again and again). So i couldn't able to exit from it.
In some other activities I use EXIT button and proper code to exit. Even when I click the EXIT button on those activities, it will start login activity. (login page is opened)
In my application, I use
1) Main
2) ScreenActivity
3) Login
flow: (from main->screenActivity->login)
The start page (1st activity) is posted below
public class main extends Activity {
static ConnectivityManager conMgr;
BackgroundThread backgroundThread;
TextView myText;
boolean myTextOn = true;
Cursor cursor;
String response="";
public SQLiteAdapter mySQLiteAdapter;
private SQLiteDatabase sqLiteDatabase;
SimpleCursorAdapter cursorAdapter;
public class BackgroundThread extends Thread {
boolean running = false;
void setRunning(boolean b){
running = b;
}
#Override
public void run() {
// TODO Auto-generated method stub
//super.run();
while(running){
try {
sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(Exception e)
{
}
handler.sendMessage(handler.obtainMessage());
}
}
}
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
//super.handleMessage(msg);
if (myTextOn){
myTextOn = false;
myText.setVisibility(View.GONE);
}
else{
myTextOn = true;
myText.setVisibility(View.VISIBLE);
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.thread);
myText = (TextView)findViewById(R.id.mytext);
}
#Override
protected void onStart() {
conMgr = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
// TODO Auto-generated method stub
super.onStart();
if(isInternetAvailable())
{
Toast.makeText(this, "online", Toast.LENGTH_LONG).show();
startActivity(new Intent(main.this, ScreenActivity.class));
}
else{
startActivity(new Intent(main.this, splashscreen.class));
Toast.makeText(this, "offline", Toast.LENGTH_LONG).show();
}
backgroundThread = new BackgroundThread();
backgroundThread.setRunning(true);
backgroundThread.start();
}
private boolean isInternetAvailable() {
ConnectivityManager cm=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
boolean retry = true;
backgroundThread.setRunning(false);
while(retry){
try {
backgroundThread.join();
retry = false;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(Exception e)
{
}
}
}
public void onDEstroy()
{
super.onDestroy();
}
}
ScreenActivity:
public class ScreenActivity extends Activity implements AnimationListener {
private TextView animatedView3;
//ImageView image;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
/* Animation animation1 = AnimationUtils.loadAnimation(this,
R.anim.anima);
animation1.setAnimationListener(this);
View animatedView1 = findViewById(R.id.aet1);
animatedView1.startAnimation(animation1);
/** set time to splash out */
final int welcomeScreenDisplay = 9000;
/** create a thread to show splash up to splash time */
Thread welcomeThread = new Thread() {
int wait = 0;
#Override
public void run() {
try {
super.run();
/**
* use while to get the splash time. Use sleep() to increase
* the wait variable for every 100L.
*/
while (wait < welcomeScreenDisplay) {
sleep(100);
wait += 100;
}
} catch (Exception e) {
System.out.println("EXc=" + e);
} finally {
/**
* Called after splash times up. Do some action after splash
* times up. Here we moved to another main activity class
*/
startActivity(new Intent(ScreenActivity.this,
login.class));
}
}
};
welcomeThread.start();
}
public void onAnimationStart(Animation animation) {
}
public void onAnimationEnd(Animation animation) {
//Toast.makeText(this, "Animation ended", Toast.LENGTH_SHORT).show();
if (animatedView3.getVisibility() == View.VISIBLE) {
animatedView3.setVisibility(View.INVISIBLE);
} else {
animatedView3.setVisibility(View.VISIBLE);
}
}
public void onAnimationRepeat(Animation animation) {
// Toast.makeText(this, "Animation rep", Toast.LENGTH_SHORT).show();
}
}
Please can anyone explain about the problem and how to solve it? I didn't understand.
Place finish() in your loginActivity and for other Activities as well else stack will store the list of visited Activities.