Android Service ("startService & stopService") and Play/Stop Button in One - java

I am developing an Android app and I need to make one button which will be a Play/Stop button for Android Service playing and stopping.
Play button is for startActivity();
Stop button is for stopActivity();
How do I make this?

You just need to declare a flag variable and declare body of onclick() based on flag value like this.
public class ServiceActivity extends Activity {
Button play;
int button_status=1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
play=(Button)findViewById(R.id.button1);
play.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(button_status == 1)//play the service
{
button_status=0;
Intent i=new Intent(ServiceActivity.this,Playing.class);
startService(i);
}
else//stop the service
{
button_status=1;
Intent i=new Intent(ServiceActivity.this,Playing.class);
stopService(i);
}
});
}
}
or you can use ToggleButton for your purose.

boolean isStop = false;
public void startorStop() {
if(isStop) {
// play it
} else {
//stop it
}
isStop = !isStop;
}

Just use a boolean to remember if it's on or off and toggle it
boolean isOn = false;
public void startStopButton() {
if(isOn) {
stopActivity();
isOn = false;
} else {
startActivity();
isOn = true;
}
}
Now whenever your button is pressed, you can call this method.

Related

Keep user logged in but exit android app on double pressing back

I am using Firebase to sign in the user and have implemented the code to exit the app on double click. But the problem is the same screen is popping up again.
I tried a workaround setting a SharedPreference and then checking that in mAuthListner. But it did not work.
Here are the relevant sections of the code:
mAuthListener = new FirebaseAuth.AuthStateListener(){
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
SharedPreferences d= getSharedPreferences("backPressed", Context.MODE_PRIVATE);
Boolean t = d.getBoolean("back",false);
if (firebaseAuth.getCurrentUser() != null && !t) {
startActivity(new Intent(MainActivity.this, Second.class));
}
if (t) {
d.edit().putBoolean("back",false);
}
}
};
Code for back button pressed:
boolean doubleBackToExitPressedOnce = false;
private Handler mHandler = new Handler();
private final Runnable mRunnable = new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce = false;
}
};
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
SharedPreferences d= getSharedPreferences("backPressed",Context.MODE_PRIVATE);
d.edit().putBoolean("back",true);
finish();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
mHandler.postDelayed(mRunnable, 2000);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mHandler != null) { mHandler.removeCallbacks(mRunnable); }
}
How can I exit the app on back pressed twice while keeping the user logged in?
This is not a Firebase issue as Firebase will not log out until you specifically call the "Log Out" method.
You do not need SharedPreferences. Just set an Activity level variable BackOnce to False then set it in the OnBackPressed as necessary.
boolean BackOnce = false;
#Override
public void onBackPressed() {
if (BackOnce) {
finish();
} else {
BackOnce = true;
Snackbar sb = Snackbar.make(myView, "Press back again to close app", Snackbar.LENGTH_SHORT);
sb.addCallback(new Snackbar.Callback() {
#Override
public void onDismissed(Snackbar snackbar, int event) {
super.onDismissed(snackbar, event);
BackOnce = false;
}
});
sb.show();
}
}

How to run an infinate loop in thread in android when a button is pressed?

I want to create a sound by comparing longitude and latitude with a value when value is 0. I tried this with infinite loop without thread. But the program crashed. Then I tried with thread, but it also failed.
public class MainActivity extends Activity
{
Button start,exit;
GPSTracker gps;
MediaPlayer audio1;
Boolean button;
TextView txt1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start=(Button)findViewById(R.id.button1);
exit=(Button)findViewById(R.id.button2);
txt1=(TextView)findViewById(R.id.textView1);
audio1=MediaPlayer.create(MainActivity.this,R.raw.audio);
button=false;
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(button==true)
{
button=false;
start.setText("START");
txt1.setText("Press 'START' to start working");
audio1.pause();
}
else
{
button=true;
start.setText("STOP");
txt1.setText("Press 'STOP' to stop working");
gps= new GPSTracker(MainActivity.this);
if(gps.canGetLoc())
{
double latitude= gps.getLatitude();
double longitude=gps.getLongitude();
if(latitude!=0&&longitude!=0)
{
audio1.start();
}
else
Toast.makeText(getApplicationContext(), "Wait for some seconds...", Toast.LENGTH_SHORT).show();
}
else
{
gps.showSettingsAlert();
}
}
}
});
exit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
audio1.stop();
finish();
}
});
}

Update sharedpreference that uses checkbox

I want to update the changes when I uncheck and check the checkbox in the preference activity but when I press the back button it doesn't work. It only works when I close the activity and then open it
Main activity
public class MainActivity extends ActionBarActivity {
private ToggleButton togle;
private Camera camera;
private boolean isFlashOn;
private boolean hasFlash;
Parameters params;
private ShakeListener mShaker;
MediaPlayer mp;
ImageView anime;
int p=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
anime = (ImageView) findViewById(R.id.Animation);
hasFlash = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!hasFlash) {
// device doesn't support flash
// Show alert message and close the application
AlertDialog alert = new AlertDialog.Builder(MainActivity.this)
.create();
alert.setTitle("Error");
alert.setMessage("Sorry, your device doesn't support flash light!");
alert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// closing the application
finish(); }
});
alert.show();
return;}
getCamera();
togle = (ToggleButton) findViewById(R.id.ToggleButton01);
togle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
boolean checked = ((ToggleButton) v).isChecked();
if (checked){
turnOffFlash();
}
else{
getCamera();
turnOnFlash();
}
}
});
SharedPreferences getprefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean stopshake = getprefs.getBoolean("checkbox", true);
if (stopshake == true ){
mShaker = new ShakeListener(this);
mShaker.setOnShakeListener(new ShakeListener.OnShakeListener () {
public void onShake()
{ if (!isFlashOn) {
Toast.makeText(MainActivity.this, "On" , Toast.LENGTH_SHORT).show();
getCamera();
turnOnFlash();
}
else{
turnOffFlash();
Toast.makeText(MainActivity.this, "Off" , Toast.LENGTH_SHORT).show();
} }
});
}
}
private void getCamera() {
// TODO Auto-generated method stub
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
}
} }
private void turnOnFlash() {
if (!isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
getCamera();
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
anime.setImageResource(R.drawable.anim);
anime.post(new Runnable() {
#Override
public void run() {
AnimationDrawable frameAnimation =
(AnimationDrawable) anime.getDrawable();
frameAnimation.start();
}
});
// changing button/switch image
}
}
private void turnOffFlash() {
if (isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
camera.setPreviewCallback(null);
camera.release();
camera = null;
isFlashOn = false;
anime.setImageResource(R.drawable.off);
// changing button/switch image
}
}
private void playSound() {
// TODO Auto-generated method stub
if(isFlashOn){
mp = MediaPlayer.create(MainActivity.this, R.raw.off1);
}else{
mp = MediaPlayer.create(MainActivity.this, R.raw.on1);
}
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
mp.start();
}
#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) {
Intent intent = new Intent(MainActivity.this, Prefsetting.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
Preference activity
public class Prefsetting extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefset);
}
}
You access SharedPreferences in the onCreate() of your MainActivity, which is only called when that activity is created from scratch (i.e. when you first start your app). As you (presumably) navigate to and from your Prefsetting Activity fairly quickly, MainActivity is likely only in a paused or stopped state when it is resumed. Take a look at the diagram here to see what happens to Activity classes as they move into and out of the foreground.
You have a couple of options. Either place this:
#Override
public void onResume() {
super.onResume();
SharedPreferences getprefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean stopshake = getprefs.getBoolean("checkbox", true);
if (stopshake) {
mShaker = new ShakeListener(this);
mShaker.setOnShakeListener(new ShakeListener.OnShakeListener () {
public void onShake() {
if (!isFlashOn) {
Toast.makeText(MainActivity.this, "On" , Toast.LENGTH_SHORT).show();
getCamera();
turnOnFlash();
} else {
turnOffFlash();
Toast.makeText(MainActivity.this, "Off" , Toast.LENGTH_SHORT).show();
}
}
});
} else {
if (mShaker != null) {
mShaker.setOnShakeListener(null);
mShaker = null;
}
}
}
Into somewhere like onResume().
Or, use an EventBus like LocalBrodcastManager to update your Preferences when onPause() is called in your PreferenceActivity.
From the code snippet it appears that you never actually commit your changes to the SharedPreferences of the application. Somewhere in the code when that boolean is flipped you need to do something like this:
prefs.put("checkbox", currentBooleanState).commit();

How to set the android app theme in java,

I want to allow the user change the theme from the entire app by clicking a button,
So I want to know if there is a way to change the app theme within java code.
You can use the setTheme() method on a Context.
Be sure to pay attention to the note in the documentation- you need to call setTheme() before you instantiate any Views.
If you change themes while your application is open, you will need to recreate your Activity for the changes to show.
public class ThemeSwitcher extends Activity implements OnClickListener {
private boolean isThemeSwitch = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
if (isDefault() == false) {// Default theme defined in Style file.
setTheme(android.R.style.Theme_Light);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.theme_switcher);
findViewById(R.id.switchTheme).setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.switchTheme) {
switchTheme();
isThemeSwitch = true;
finish();
}
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
if (isThemeSwitch) {
Intent intent = new Intent(this, ThemeSwitcher.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
private SharedPreferences getPreference() {
return getSharedPreferences("theme", 0);
}
private void switchTheme() {
if (isDefault()) {
getPreference().edit().putBoolean("theme", false).commit();
}
else {
getPreference().edit().putBoolean("theme", true).commit();
}
}
private boolean isDefault() {
boolean isDef = true;
isDef = getPreference().getBoolean("theme", false);
return isDef;
}
}

How to stop service in background with toggle button in Android?

I'm implementing running the service in background and service will be stop and start click on toggle button.Service is start in 1st activity and stop the service in another activity when click on toggle button.When i run the application service is automatically start in 1st activity which i start in onCreate() method in 1st activity and another activity toggle button status is already on status but when i toggle button is going to off service stop but when i back to 1st activity service is again start.Please can any one help me.Here is my code
public class MyService extends Service
{
private static final String TAG = "MyService";
MediaPlayer player;
private final String StrMyService="myservice";
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
player = MediaPlayer.create(this, R.raw.braincandy);
player.setLooping(false); // Set looping
}
#Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
player.stop();
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
player.start();
}
}
public class Service_Demo extends Activity implements OnClickListener
{
private static final String TAG = "ServicesDemo";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
System.out.println("In OnCreate(");
startService(new Intent(this, MyService.class));
}
}
public class Toggle_Activity extends Activity
{
ToggleButton tgButton;
private boolean isService=false;
private String strService;
public final String service_Prefs="servicePrefs";
private static final String StrMyService = "zdf";
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.toggle);
final SharedPreferences servicePrefs=this.getSharedPreferences("Service_Prefs",MODE_WORLD_READABLE);
strService=servicePrefs.getString(StrMyService , "myservice");
Log.e("",""+strService);
final boolean mBool = servicePrefs.getBoolean("myservice", true);
Log.e("Boolean Value mBool","="+mBool);
Boolean b = mBool;
Log.e("Update pref", b.toString());
tgButton = (ToggleButton)findViewById(R.id.toggleButton);
tgButton.setChecked(mBool);
final boolean mBool1 = servicePrefs.getBoolean("myservice", false);
final Boolean c = mBool1;
Log.e("Update pref", c.toString());
tgButton=(ToggleButton)findViewById(R.id.toggleButton);
tgButton.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
if(tgButton.isChecked())
{
startService(new Intent(Toggle_Activity.this , MyService.class));
System.out.println("Service is started in togglr button");
}
else
{
stopService(new Intent(Toggle_Activity.this,MyService.class));
System.out.println("Service is stopped in togglr button");
}
}
});
}
}
in the first activity, you'd put startService(new Intent(this, MyService.class)) in onresume
from oncreate
I figured this out the best way possible. I basically linked my toggle button and my service together using a shared preference and listeners. I called this shared preference "service_running" and then implemented my listeners in the activity onCreate() method the toggle button is present in (in this case, MainActivity.
In my onCreate() heres what I did:
// set toggle button based on service running
final ToggleButton toggle = (ToggleButton)findViewById(R.id.toggleButton);
toggle.setChecked(serviceRunning(SendService.class));
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged (CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
startSendService();
}
else {
stopSendService();
}
}
});
// set shared pref listener for toggle
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.OnSharedPreferenceChangeListener myPrefListner = new SharedPreferences.OnSharedPreferenceChangeListener(){
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (key.equals("service_running")) {
toggle.setChecked(prefs.getBoolean("service_running", false));
}
}
};
prefs.registerOnSharedPreferenceChangeListener(myPrefListner);
startSendService() and stopSendService() simply start or stop my service depending on if it is running and has the correct app permissions or not.
Heres the method which checks if a service is running (credit to #geekQ in this thread):
private boolean serviceRunning (Class<?> serviceClass) {
// check if a service class is currently running
ActivityManager manager = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
And then in my service, in the onStartCommand() I just changed the shared preference to true, and in the onDestroy() I changed it to false.
The only caveat with this is that you have to hide this shared preference from your preference screen, which can be done with:
getPreferenceScreen().removePreference(findPreference("service_running"));

Categories

Resources