How to set the android app theme in java, - 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;
}
}

Related

How can I get runnable application package name [duplicate]

I used Toast to make notification, but it seems it will appear even its activity is not in the current screen and some other activity has been started.
I want to check this situation, when the activity is not the current one, I'd not send the Toast notification. But how to do ?
When your Activity comes to the foreground, its onResume() method will be invoked. When another Activity comes in front of your Activity, its onPause() method will be invoked. So all you need to do is implement a boolean indicating if your Activity is in the foreground:
private boolean isInFront;
#Override
public void onResume() {
super.onResume();
isInFront = true;
}
#Override
public void onPause() {
super.onPause();
isInFront = false;
}
ArrayList<String> runningactivities = new ArrayList<String>();
ActivityManager activityManager = (ActivityManager)getBaseContext().getSystemService (Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> services = activityManager.getRunningTasks(Integer.MAX_VALUE);
for (int i1 = 0; i1 < services.size(); i1++) {
runningactivities.add(0,services.get(i1).topActivity.toString());
}
if(runningactivities.contains("ComponentInfo{com.app/com.app.main.MyActivity}")==true){
Toast.makeText(getBaseContext(),"Activity is in foreground, active",1000).show();
}
This way you will know if the pointed activity is the current visible activity.
I prefer not to handle the state by myself, so I have implemented a class that does this for me.
package mypackage;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
// Mine extends AppCompatActivity - your's might need to extend Activity, depending on whether
// you use the support library or not.
public class StateTrackingActivity extends AppCompatActivity {
public enum ActivityState {
CREATED, RESUMED, STARTED, PAUSED, STOPPED, DESTROYED
}
private ActivityState _activityState;
protected ActivityState getActivityState() { return _activityState; }
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
_activityState = ActivityState.CREATED;
}
#Override
protected void onResume() {
super.onResume();
_activityState = ActivityState.RESUMED;
}
#Override
protected void onStart() {
super.onStart();
_activityState = ActivityState.STARTED;
}
#Override
protected void onPause() {
super.onPause();
_activityState = ActivityState.PAUSED;
}
#Override
protected void onStop() {
super.onStop();
_activityState = ActivityState.STOPPED;
}
#Override
protected void onDestroy() {
super.onDestroy();
_activityState = ActivityState.DESTROYED;
}
}
Then your activity can extend this one and you can get the state by calling getActivityState().
This is my ultimate isActivityVisible function.
protected boolean isActivityVisible() {
if (this.mActivity != null) {
Class klass = this.mActivity.getClass();
while (klass != null) {
try {
Field field = klass.getDeclaredField("mResumed");
field.setAccessible(true);
Object obj = field.get(this.mActivity);
return (Boolean)obj;
} catch (NoSuchFieldException exception1) {
// Log.e(TAG, exception1.toString());
} catch (IllegalAccessException exception2) {
// Log.e(TAG, exception2.toString());
}
klass = klass.getSuperclass();
}
}
return false;
}
if (BaseActivity.this instanceof Faq)
{
Toast.makeText(BaseActivity.this, "You are in the Same Page", Toast.LENGTH_SHORT).show();
}else {
Intent intent = new Intent(BaseActivity.this, Faq.class);
startActivity(intent);
drawer.closeDrawer(GravityCompat.START);
}
//// here am All my activities are extending on Activity called BaseActivity
There is Activity#isTaskRoot() method
if ( getActivity() instanceof ManageCardActivity){
// your code
}

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

Send info from class to another class getIntent

I have been trying to learn java so I can program for android. I have made an app that has 2 classes, Match and MatchResult. In Match you can push a button and it will add one to a counter. At the bottom of the page i have a button that will bring you to the next class and display the counter in a textview. Im trying to send the info trough a getIntent but its something wrong that I cant find. Here is the code:
Match:
public class Match extends Activity implements OnClickListener {
public final static String EXTRA_MESSAGE_HOME = "com.epstudios.basketballmanager_v1.MATCHRESULT";
public final static String EXTRA_MESSAGE_AWAY = "com.epstudios.basketballmanager_v1.MATCHRESULT";
TextView awayGoals, homeGoals, home, away;
Button homebtn, awaybtn, gotoresult;
int homecount, awaycount;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.match);
baconAndEggs();
homebtn.setOnClickListener(this);
awaybtn.setOnClickListener(this);
gotoresult.setOnClickListener(this);
}
public void sendInfo(View view) {
Intent intent = new Intent(this, MatchResult.class);
intent.putExtra(EXTRA_MESSAGE_AWAY, awaycount);
intent.putExtra(EXTRA_MESSAGE_HOME, homecount);
startActivity(intent);
}
private void baconAndEggs() {
awayGoals = (TextView) findViewById(R.id.Away);
homeGoals = (TextView) findViewById(R.id.Home);
homebtn = (Button) findViewById(R.id.homeBtn);
awaybtn = (Button) findViewById(R.id.awayBtn);
gotoresult = (Button) findViewById(R.id.matchResult);
}
public void counter() {
awaycount = 1;
homecount = 0;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.homeBtn:
homecount++;
homeGoals.setText("Lakers: " + homecount);
break;
case R.id.awayBtn:
awaycount++;
awayGoals.setText("Heat: " + awaycount);
break;
case R.id.matchResult:
Intent result = new Intent(this, MatchResult.class);
startActivity(result);
break;
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
MatchResult:
public class MatchResult extends Activity {
TextView home, away;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.match_result);
resultcounter();
int awayresult = getIntent().getIntExtra(Match.EXTRA_MESSAGE_AWAY, -1);
int homeresult = getIntent().getIntExtra(Match.EXTRA_MESSAGE_HOME, -1);
home.setText(String.valueOf(homeresult));
Log.d("Petter", String.valueOf(homeresult));
away.setText(String.valueOf(awayresult));
}
public void resultcounter() {
// TODO Auto-generated method stub
home = (TextView) findViewById(R.id.homeresult);
away = (TextView) findViewById(R.id.awayresult);
}
}
Hmm, why not try scrapping your sendInfo() function and adding this line under your result intent instead:
result.putExtra(Match.EXTRA_MESSAGE_AWAY, awayCount);
It should work now.
It seems that code having 2 ways to call MatchResult activity hence try to use :
hasExtra() method to check whether that extra is passed with the Intent.
The constructor of Intent should have the context of your class. But in your case this refers View.OnClickListener()! So, just change it as in below.
...
case R.id.matchResult:
Intent result = new Intent(Match.this, MatchResult.class); // Like here
result.putExtra(EXTRA_MESSAGE_AWAY, awaycount);
result.putExtra(EXTRA_MESSAGE_HOME, homecount);
startActivity(result);
break;
}
...
Edit: You have never used sendInfo method. As far as I get, you could remove your sendInfo method and put those codes into switch case.
I would be create a static variable shared between activities.

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

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.

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