How to make a layout for the equalizer? - java

This is my code i use to setup a 5 band Equalizer, but i would like to have a Layout which supports the number of equalizer bands supported by the device.
For now i have hardcoded the size of Equalizer bands because i'm not sure how to create a Layout for a non constant value of equalizer bands.
This is the code i would like to use:
equalizer.getNumberOfBands(); //it tells you the number of equalizer in device.
But what if a device supports +10 equalizer bands, how can i fit those bands on the screen?
Code for creating Equalizer
private void setupEqualizer(){
mEqualizer = new Equalizer(0, mediaPlayer.getAudioSessionId());
final short lowerEqualizerBandLevel = mEqualizer.getBandLevelRange()[0];
final short upperEqualizerBandLevel = mEqualizer.getBandLevelRange()[1];
for (short i = 0; i < 5; i++){
final short equalizerBandIndex = i;
int freq_range = mEqualizer.getCenterFreq(equalizerBandIndex);
verticalSeekbar[i].setMax(upperEqualizerBandLevel - lowerEqualizerBandLevel);
verticalSeekbar[i].setProgress(mEqualizer.getBandLevel(equalizerBandIndex));
verticalSeekbar[i].setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
mEqualizer.setBandLevel(equalizerBandIndex, (short) (progress + lowerEqualizerBandLevel ));
slider_value[equalizerBandIndex].setText(String.valueOf((progress + lowerEqualizerBandLevel) / 100 + " dB"));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
slider_labels[i].setText(formatBandLabel(freq_range));
float scale2 = getResources().getDisplayMetrics().density;
int dpAsPixels2 = (int) (8*scale2 + 0.5f);
}
setupEqSpinner();
}

You need to use Vertical SeekBar as told by Nilesh
equalizer.getNumberOfBands() // it tells the number of equalizer ..
Create a LinearLayout(Horizontal) and add Vertical Seekbar to it in a for loop (numberOfBands)..

Related

how to assign the value of a progressbar in another outerclass variable to perform calculation?

so i have been trying to make this BMI calculator in android studio, where your BMI will instantly get calculated when you drag Progress-bar to any value .
To execute this, what i did was-
inside the the Bundle class,
i directly declared 2 variable and assigned one of them to get the data from the Height progress bar and another to get the data from weight progress bar.
and then i wrote the typical code for the calculation and the text setting.
And it did not work
For myself being a very new to this, i really cant find my mistake here.
so as a result what i got was- a still BMI which was the result for the initial value of the progress-bar that i have set for the height and weight.
i am getting a feeling that i made a very silly mistake somewhere that i still can not notice.
Would you be kind enough to point that out?
the Java code that i have used is below, please check it-
The code for the BMI is at the end. I feel the problem is lying there.
here is the screenshot of the app-
screenshot2
screenshot1
here is my code--
public class MainActivity extends AppCompatActivity {
TextView mheighttext,mweighttext2,mbmitext,mfunnymsg;
SeekBar mbar1, mbar2;
RelativeLayout mweightlayout, mlayout3;
ImageView mgincbtn1,mgincbtn2,mgdecbtn1,mgdecbtn2;
String mbmi, bmitext;
int wt= 45;
String wtwt="45";
int ht= 158;
String htht="158";
float rslt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
mheighttext=findViewById(R.id.heighttext);
mweighttext2=findViewById(R.id.weighttext2);
mbar1= findViewById(R.id.bar1);
mbar2=findViewById(R.id.bar2);
mgincbtn1=findViewById(R.id.gincbtn1);
mgincbtn2=findViewById(R.id.gincbtn2);
mgdecbtn1=findViewById(R.id.gdecbtn1);
mgdecbtn2=findViewById(R.id.gdecbtn2);
mbmitext=findViewById(R.id.bmitext1);
mfunnymsg=findViewById(R.id.funnymsg);
mbar1.setMax(246);
mbar1.setProgress(160);
mbar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
ht=progress;
htht=String.valueOf(ht);
mheighttext.setText(htht);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
mbar2.setMax(244);
mbar2.setProgress(50);
mbar2.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
wt=progress;
wtwt=String.valueOf(wt);
mweighttext2.setText(wtwt);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
mgincbtn1.setOnClickListener(v -> {
ht=ht+1;
if (ht>=0 && ht<247) {
mbar1.setProgress(ht);
htht = String.valueOf(ht);
mheighttext.setText(htht);
}
});
mgdecbtn1.setOnClickListener(v -> {
ht=ht-1;
if (ht>=0 && ht<247) {
mbar1.setProgress(ht);
htht = String.valueOf(ht);
mheighttext.setText(htht);
}
});
mgincbtn2.setOnClickListener(view -> {
wt=wt+1;
if (wt>=0 && wt<244) {
mbar2.setProgress(wt);
wtwt = String.valueOf(wt);
mweighttext2.setText(wtwt);
}
});
mgdecbtn2.setOnClickListener(v -> {
wt=wt-1;
if (wt>=0 && wt<244) {
mbar2.setProgress(wt);
wtwt = String.valueOf(wt);
mweighttext2.setText(wtwt);
}
});
int htt = mbar1.getProgress();
int wtt = mbar2.getProgress();
float httt=htt/100;
rslt= wtt/(httt*httt);
mbmi=Float.toString(rslt);
mbmitext.setText(mbmi);
}
}
}
You would want to put the snippet of code that calculates the BMI (perhaps the last 4 lines of code) in both onProgressChanged() to instantly calculate BMI as height/weight gets changed. Since you're setting global variables for both height and weight, you'll get current values for each of them.
You can also make a function for calculating the BMI like this:
private float calculateBMI(int height, int weight) {
float ht = height / 100;
float result = weight / (ht * ht);
return result;
}
and have this function call in both onProgressChanged() like so (for the weight for example):
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
wt = progress;
mweighttext2.setText(String.valueOf(getBMI(ht, progress)));
}
Move this your code...
int htt = mbar1.getProgress();
int wtt = mbar2.getProgress();
float httt=htt/100;
rslt= wtt/(httt*httt);
mbmi=Float.toString(rslt);
mbmitext.setText(mbmi);
to a method say
public void computeBMI(){
int htt = mbar1.getProgress();
int wtt = mbar2.getProgress();
float httt=htt/100;
rslt= wtt/(httt*httt);
mbmi=Float.toString(rslt);
mbmitext.setText(mbmi);
}
Then add a button in your UI say mCompute. In your oncreate method you can then implement that buttons onClickListener to call computeBMI() above.
That is:
yourButton.setOnclickListener((v)->{
computeBMI();
});

Set color seekbar

I'm creating a small paint android app using android studio java. I create in the menu an icon for changing the color of the drawing. Once the user click on it a new AlertDialog should appear showing 4 seekbars for ARGB colors. I ended with this code but I still don't know why it's not working. Can someone please help me?
private Drawing draws;
private SeekBar alphaSeekBar;
private SeekBar redSeekBar;
private SeekBar greenSeekBar;
private SeekBar blueSeekBar;
private void showColorDialog(){
currentAlertDialog = new AlertDialog.Builder(this);
View view = getLayoutInflater().inflate(R.layout.color_dialog, null);
alphaSeekBar = view.findViewById(R.id.alphaSeekBar);
redSeekBar = view.findViewById(R.id.redSeekBar);
greenSeekBar = view.findViewById(R.id.greenSeekBar);
blueSeekBar = view.findViewById(R.id.blueSeekBar);
colorView = view.findViewById(R.id.colorView);
alphaSeekBar.setOnSeekBarChangeListener(colorSeekBarChanged);
redSeekBar.setOnSeekBarChangeListener(colorSeekBarChanged);
greenSeekBar.setOnSeekBarChangeListener(colorSeekBarChanged);
blueSeekBar.setOnSeekBarChangeListener(colorSeekBarChanged);
int color = draws.getDrawingColor();
alphaSeekBar.setProgress(Color.alpha(color));
redSeekBar.setProgress(Color.red(color));
greenSeekBar.setProgress(Color.green(color));
blueSeekBar.setProgress(Color.blue(color));
Button setColorButton = view.findViewById(R.id.setColorButton);
setColorButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pikassoView.setDrawingColor(Color.argb(
alphaSeekBar.getProgress(),
redSeekBar.getProgress(),
greenSeekBar.getProgress(),
blueSeekBar.getProgress()
));
colorDialog.dismiss();
}
});
currentAlertDialog.setView(view);
currentAlertDialog.setTitle("Choose color");
colorDialog = currentAlertDialog.create();
colorDialog.show();
} private SeekBar.OnSeekBarChangeListener colorSeekBarChanged = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
draws.setBackgroundColor(Color.argb(
alphaSeekBar.getProgress(),
redSeekBar.getProgress(),
greenSeekBar.getProgress(),
blueSeekBar.getProgress()
));
colorView.setBackgroundColor(Color.argb(
alphaSeekBar.getProgress(),
redSeekBar.getProgress(),
greenSeekBar.getProgress(),
blueSeekBar.getProgress()
));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
};
First, this alphaSeekBar.setProgress(Color.alpha(color)); is wrong. setProgress is meant for setting int value to show how much progress seekbar has.
If your seekBar Max is set to 100 (alphaSeekBar.setMax(100);) then this alphaSeekBar.setProgress(50); means seekBar is progressed half way.
Second, to set colors use this:
alphaSeekBar.setProgressTintList(Color.alpha(color));
alphaSeekBar.setThumbTintList(Color.alpha(color));
Or, use this:
alphaSeekBar.getProgressDrawable().setColorFilter(Color.alpha(color), PorterDuff.Mode.MULTIPLY);
try different tint modes in place of PorterDuff.Mode.MULTIPLY to get your desired result
good luck
EDIT:
For setting a custom view to Alert Dialog
currentAlertDialog = new AlertDialog.Builder(this);
// ...Irrelevant code for customizing the buttons and title
View view = getLayoutInflater().inflate(R.layout.color_dialog, null);
currentAlertDialog.setView(view);
then you can get those seekbar references like below:
alphaSeekBar = currentAlertDialog.findViewById(R.id.alphaSeekBar);
redSeekBar = currentAlertDialog.findViewById(R.id.redSeekBar);
greenSeekBar = currentAlertDialog.findViewById(R.id.greenSeekBar);
blueSeekBar = currentAlertDialog.findViewById(R.id.blueSeekBar);
colorView = currentAlertDialog.findViewById(R.id.colorView);

trying to implement dynamic increase of max on android seekbar

I'm implementing a seekbar that allows users to set a price.
I want the seekbar to start out with a max of 100, then if the user moves the seekbar all the way up to 100, the max goes up to 250 and if the user moves the seekbar all the way up to 250 it goes up to 500, finally stopping at 500+ if the user moves the seekbar all the way up to 500.
The code that I've written works, for the most part. The problem is that when the user moves the seekbar up to the max, since the user is holding their finger there, android thinks that it's constantly at the max so it just instantly increases to 500+, so I need to find a way to disable touch after increasing the max until the user lifts their finger.
So...I want to break the user's touch from the seekbar so that it waits until the next NEW touch event so that this won't happen. If anyone knows a way to do this, please let me know asap!! thanks!
What I've already tried is disable and reanabling the seekbar when it reaches the max, in hopes of breaking the touch, but this doesn't work.
The code I have is below:
private class PriceChangeListener implements SeekBar.OnSeekBarChangeListener{
private TextView priceView = (TextView) findViewById(R.id.input_price_label);
private TextView maxPriceView = (TextView) findViewById(R.id.input_price_max_label);
private boolean increaseMax;
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
String textToSet = "About how much will it cost? $" + String.valueOf(progress);
if(progress < 500)
priceView.setText(textToSet);
else
priceView.setText(textToSet + "+");
if(progress == seekBar.getMax() && increaseMax) {
seekBar.setEnabled(false);
switch (progress) {
case 100:
seekBar.setMax(250);
increaseMax = false;
maxPriceView.setText("$" + String.valueOf(seekBar.getMax()));
break;
case 250:
seekBar.setMax(500);
increaseMax = false;
maxPriceView.setText("$" + String.valueOf(seekBar.getMax()));
break;
case 500:
maxPriceView.setText("$500+");
break;
}
seekBar.setEnabled(true);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
increaseMax = true;
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// Do nothing
}
}
Further improving my comment, give this a shot
private boolean newTouch = false;
private int oldProgress;
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
if (newTouch) {
oldProgress = progress;
priceView.setText("About how much will it cost? $" + String.valueOf(progress));
if(progress == seekBar.getMax()) {
newTouch = false;
switch (progress) {
case 100:
seekBar.setMax(250);
seekBar.setProgress(100);
maxPriceView.setText("$" + String.valueOf(seekBar.getMax()));
break;
case 250:
seekBar.setMax(500);
seekBar.setProgress(250);
maxPriceView.setText("$" + String.valueOf(seekBar.getMax()));
break;
case 500:
seekBar.setProgress(250);
maxPriceView.setText("$500+");
break;
}
}
} else {
seekBar.setProgress(oldProgress);
}
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
newTouch = true;
}

Android MediaPlayer.OnBufferingUpdateListener - Percentage of buffered content is negative

I have a service that uses MediaPlayer to stream internet radio:
public class MediaPlayerService extends Service implements
MediaPlayer.OnPreparedListener,
MediaPlayer.OnBufferingUpdateListener {
private MediaPlayer mMediaPlayer;
private WifiLock mWifiLock;
public int onStartCommand(Intent intent, int flags, int startId) {
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setOnBufferingUpdateListener(this);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setDataSource(MY_URL);
// Acquire CPU lock and wi-fi lock
mMediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
mWifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE))
.createWifiLock(WifiManager.WIFI_MODE_FULL, "Media Player Wi-Fi Lock");
mWifiLock.acquire();
mMediaPlayer.prepareAsync();
return START_STICKY;
}
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mMediaPlayer.start();
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
Log.d("Buffered " + percent);
}
}
Everything works great except onBufferingUpdate(...) method. It prints this in the log:
Buffered -819200000
Buffered -819200000
Buffered -1228800000
Buffered -1228800000
Buffered -1228800000
Buffered -1228800000
Buffered -1638400000
Buffered -1638400000
Buffered -1638400000
Buffered -1638400000
Buffered -2048000000
Buffered -2048000000
Buffered -2048000000
Buffered -2048000000
Buffered -2147483648 (repeated further on)
Note: -2147483648 is Integer MIN_VALUE
While percent is supposed to be:
The percentage (0-100) of the content that has been buffered or played
thus far
Questions:
Why incorrect values are passed in onBufferingUpdate() percent parameter?
How to fix that?
Is there any other way to get how much data has been buffered? My goal is to show a progress bar to give user an idea of when enough data will be buffered and radio playback will start.
Thank you!
I am not sure why is this happening, I had the same problem, but this code may help you:
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
// TODO Auto-generated method stub
if (percent < 0 || percent > 100) {
//System.out.println("Doing math: (" + (Math.abs(percent)-1)*100.0 + " / " +Integer.MAX_VALUE+ ")" );
percent = (int) Math.round((((Math.abs(percent)-1)*100.0/Integer.MAX_VALUE)));
}
progressBar.setProgress(percent);
Log.i("Buffering! " , " " +percent );
System.out.println("Buffering: " +percent);
}
public void onBufferingUpdate(MediaPlayer mp, int percent)
{
double ratio = percent / 100.0;
bufferingLevel = (int)(mp.getDuration() * ratio);
seekBar.setSecondaryProgress(bufferingLevel);
}
And somewhere upper in OnCreateView OR OnCreate
seekBar.setMax(GET_TOTAL_DURATION_OF_SONG);
The problem is in Android Player Driver, point is in signed/unsigned values. Here is related issue.
To solve it on JVM level you can use this code:
percent &= 0xFF;
// media broadcasts may return values more than 100
if (percent > 100)
percent = 0;

Change the System Brightness Programmatically

I want to change the system brightness programmatically. For that purpose I am using this code:
WindowManager.LayoutParams lp = window.getAttributes();
lp.screenBrightness = (255);
window.setAttributes(lp);
because I heard that max value is 255.
but it does nothing. Please suggest any thing that can change the brightness.
Thanks
You can use following:
// Variable to store brightness value
private int brightness;
// Content resolver used as a handle to the system's settings
private ContentResolver cResolver;
// Window object, that will store a reference to the current window
private Window window;
In your onCreate write:
// Get the content resolver
cResolver = getContentResolver();
// Get the current window
window = getWindow();
try {
// To handle the auto
Settings.System.putInt(
cResolver,
Settings.System.SCREEN_BRIGHTNESS_MODE,
Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL
);
// Get the current system brightness
brightness = Settings.System.getInt(
cResolver, Settings.System.SCREEN_BRIGHTNESS
);
} catch (SettingNotFoundException e) {
// Throw an error case it couldn't be retrieved
Log.e("Error", "Cannot access system brightness");
e.printStackTrace();
}
Write the code to monitor the change in brightness.
then you can set the updated brightness as follows:
// Set the system brightness using the brightness variable value
Settings.System.putInt(
cResolver, Settings.System.SCREEN_BRIGHTNESS, brightness
);
// Get the current window attributes
LayoutParams layoutpars = window.getAttributes();
// Set the brightness of this window
layoutpars.screenBrightness = brightness / 255f;
// Apply attribute changes to this window
window.setAttributes(layoutpars);
Permission in manifest:
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
For API >= 23, you need to request the permission through Settings Activity, described here:
Can't get WRITE_SETTINGS permission
You can set the screenBrightness attribute of the window, like so:
WindowManager.LayoutParams layout = getWindow().getAttributes();
layout.screenBrightness = 1F;
getWindow().setAttributes(layout);
This code/technique is adapted from a blog entry by Almond Joseph Mendoza on January 5, 2009, entitled "Changing the Screen Brightness Programatically" (archived on the Wayback Machine).
The screenBrightness attribute is a floating-point value ranging from 0 to 1, where 0.0 is 0% brightness, 0.5 is 50% brightness, and 1.0 is 100% brightness.
Note that this doesn't affect the brightness for the entire system, only for that particular window. However, in most cases, for most applications, this is probably all you need. In particular, it has the advantage of not requiring elevated permissions, which would be required to change a global system setting.
I had the same problem.
Two solutions:
here, brightness =(int) 0 to 100 range as i am using progressbar
1 SOLUTION
float brightness = brightness / (float)255;
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.screenBrightness = brightness;
getWindow().setAttributes(lp);
2 SOLUTION
I just used dummy activity to call when my progress bar stop seeking.
Intent intent = new Intent(getBaseContext(), DummyBrightnessActivity.class);
Log.d("brightend", String.valueOf(brightness / (float)255));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //this is important
//in the next line 'brightness' should be a float number between 0.0 and 1.0
intent.putExtra("brightness value", brightness / (float)255);
getApplication().startActivity(intent);
Now coming to the DummyBrightnessActivity.class
public class DummyBrightnessActivity extends Activity{
private static final int DELAYED_MESSAGE = 1;
private Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handler = new Handler() {
#Override
public void handleMessage(Message msg) {
if(msg.what == DELAYED_MESSAGE) {
DummyBrightnessActivity.this.finish();
}
super.handleMessage(msg);
}
};
Intent brightnessIntent = this.getIntent();
float brightness = brightnessIntent.getFloatExtra("brightness value", 0);
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.screenBrightness = brightness;
getWindow().setAttributes(lp);
Message message = handler.obtainMessage(DELAYED_MESSAGE);
//this next line is very important, you need to finish your activity with slight delay
handler.sendMessageDelayed(message,200);
}
}
don't forget to register DummyBrightnessActivity to manifest.
hope it helps!!
In my case, I only want to light up the screen when I display a Fragment and not change the system wide settings. There is a way to only change the brightness for your Application/Activity/Fragment. I use a LifecycleObserver to adjust the screen brightness for one Fragment:
class ScreenBrightnessLifecycleObserver(private val activity: WeakReference<Activity?>) :
LifecycleObserver {
private var defaultScreenBrightness = 0.5f
init {
activity.get()?.let {
defaultScreenBrightness = it.window.attributes.screenBrightness
}
}
#OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun lightUp() {
adjustScreenBrightness(1f)
}
#OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun lightDown() {
adjustScreenBrightness(defaultScreenBrightness)
}
private fun adjustScreenBrightness(brightness: Float) {
activity.get()?.let {
val attr = it.window.attributes
attr.screenBrightness = brightness
it.window.attributes = attr
}
}
}
And add the LifecycleObserver such as this in your Fragment:
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
// ...
lifecycle.addObserver(ScreenBrightnessLifecycleObserver(WeakReference(activity)))
// ...
return binding.root
}
I tried several solutions that others posted and none of them worked exactly right. The answer from geet is basically correct but has some syntactic errors. I created and used the following function in my application and it worked great. Note this specifically changes the system brightness as asked in the original question.
public void setBrightness(int brightness){
//constrain the value of brightness
if(brightness < 0)
brightness = 0;
else if(brightness > 255)
brightness = 255;
ContentResolver cResolver = this.getApplicationContext().getContentResolver();
Settings.System.putInt(cResolver, Settings.System.SCREEN_BRIGHTNESS, brightness);
}
Complete Answer
I did not wanted to use Window Manager to set brightness. I wanted the brighness to reflect on System level as well as on UI. None of the above answer worked for me. Finally this approach worked for me.
Add Write setting permission in Android Manifest
<uses-permission android:name="android.permission.WRITE_SETTINGS"
tools:ignore="ProtectedPermissions"/>
Write Settings is a Protected settings so request user to allow Writing System settings:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (Settings.System.canWrite(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
intent.setData(Uri.parse("package:" + getPackageName()));
startActivity(intent);
}
}
Now you can set Brightness easily
ContentResolver cResolver = getContentResolver();
Settings.System.putInt(cResolver, Settings.System.SCREEN_BRIGHTNESS, brightness);
brighness value should be in range of 0-255 so if you have aslider with range (0-max) than you can normalize the value in range of (0-255)
private float normalize(float x, float inMin, float inMax, float outMin, float outMax) {
float outRange = outMax - outMin;
float inRange = inMax - inMin;
return (x - inMin) *outRange / inRange + outMin;
}
Finally you can now change Brightness in of 0-100% from 0-255 range like this:
float brightness = normalize(progress, 0, 100, 0.0f, 255.0f);
Hope it will save your time.
this worked for me till kitkat 4.4 but not in android L
private void stopBrightness() {
Settings.System.putInt(this.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS, 0);
}
WindowManager.LayoutParams params = getWindow().getAttributes();
params.screenBrightness = 10; // range from 0 - 255 as per docs
getWindow().setAttributes(params);
getWindow().addFlags(WindowManager.LayoutParams.FLAGS_CHANGED);
This worked for me. No need of a dummy activity. This works only for your current activity.
This is the complete code on how to change system brightness
private SeekBar brightbar;
//Variable to store brightness value
private int brightness;
//Content resolver used as a handle to the system's settings
private ContentResolver Conresolver;
//Window object, that will store a reference to the current window
private Window window;
/** Called when the activity is first created. */
#Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Instantiate seekbar object
brightbar = (SeekBar) findViewById(R.id.ChangeBright);
//Get the content resolver
Conresolver = getContentResolver();
//Get the current window
window = getWindow();
brightbar.setMax(255);
brightbar.setKeyProgressIncrement(1);
try {
brightness = System.getInt(Conresolver, System.SCREEN_BRIGHTNESS);
} catch (SettingNotFoundException e) {
Log.e("Error", "Cannot access system brightness");
e.printStackTrace();
}
brightbar.setProgress(brightness);
brightbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar seekBar) {
System.putInt(Conresolver, System.SCREEN_BRIGHTNESS, brightness);
LayoutParams layoutpars = window.getAttributes();
layoutpars.screenBrightness = brightness / (float) 255;
window.setAttributes(layoutpars);
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (progress <= 20) {
brightness = 20;
} else {
brightness = progress;
}
}
});
}
Or you may check this tutorial for complete code
happy coding:)
<uses-permission android:name="android.permission.WRITE_SETTINGS"
tools:ignore="ProtectedPermissions" />
android.provider.Settings.System.putInt(getContentResolver(),
android.provider.Settings.System.SCREEN_BRIGHTNESS,
progress);
private SeekBar Brighness = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lcd_screen_setting);
initUI();
setBrightness();
}
private void setBrightness() {
Brighness.setMax(255);
float curBrightnessValue = 0;
try {
curBrightnessValue = android.provider.Settings.System.getInt(
getContentResolver(),
android.provider.Settings.System.SCREEN_BRIGHTNESS);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
}
int screen_brightness = (int) curBrightnessValue;
Brighness.setProgress(screen_brightness);
Brighness.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progress = 0;
#Override
public void onProgressChanged(SeekBar seekBar, int progresValue,
boolean fromUser) {
progress = progresValue;
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// Do something here,
// if you want to do anything at the start of
// touching the seekbar
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
android.provider.Settings.System.putInt(getContentResolver(),
android.provider.Settings.System.SCREEN_BRIGHTNESS,
progress);
}
});
}
initUI(){
Brighness = (SeekBar) findViewById(R.id.brightnessbar);
}
Add this in manifest
<uses-permission android:name="android.permission.WRITE_SETTINGS"
tools:ignore="ProtectedPermissions"/>
Please Try this , it's May help you. Worked fine for me
According to my experience
1st method.
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.screenBrightness = 75 / 100.0f;
getWindow().setAttributes(lp);
where the brightness value very according to 1.0f.100f is maximum brightness.
The above mentioned code will increase the brightness of the current window. If we want to increase the brightness of the entire android device this code is not enough, for that we need to use
2nd method.
android.provider.Settings.System.putInt(getContentResolver(),
android.provider.Settings.System.SCREEN_BRIGHTNESS, 192);
Where 192 is the brightness value which very from 1 to 255. The main problem of using 2nd method is it will show the brightness in increased form in android device but actually it will fail to increase android device brightness.This is because it need some refreshing.
That is why I find out the solution by using both codes together.
if(arg2==1)
{
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.screenBrightness = 75 / 100.0f;
getWindow().setAttributes(lp);
android.provider.Settings.System.putInt(getContentResolver(),
android.provider.Settings.System.SCREEN_BRIGHTNESS, 192);
}
It worked properly for me
You need to create the variable:
private WindowManager.LayoutParams mParams;
then override this method (to save your previous params):
#Override
public void onWindowAttributesChanged(WindowManager.LayoutParams params) {
mParams = params;
super.onWindowAttributesChanged(params);
}
than where you wish to change the screen brightness (on the app) just use:
mParams.screenBrightness = 0.01f; //use a value between 0.01f for low brightness and 1f for high brightness
getWindow().setAttributes(mParams);
tested on api version 28.
Was just looking into this for Android 10 and this still works for me on there. But requires getting the calling Activity instance inside the fragment which is less than optimal since we only get the context from onAttach now. Setting it to -1.0f sets it to the system value (the one from brightness settings slider), 0.0f to 1.0f sets brightness values from min to max at your leisure.
WindowManager.LayoutParams lp = myactivity.getWindow().getAttributes();
lp.screenBrightness = brightness;
myactivity.getWindow().setAttributes(lp);
myactivity.getWindow().addFlags(WindowManager.LayoutParams.FLAGS_CHANGED);
I'm using this utils class works for Android 9
public class BrightnessUtil {
public static final int BRIGHTNESS_DEFAULT = 190;
public static final int BRIGHTNESS_MAX = 225;
public static final int BRIGHTNESS_MIN = 0;
public static boolean checkForSettingsPermission(Activity activity) {
if (isNotAllowedWriteSettings(activity)) {
startActivityToAllowWriteSettings(activity);
return false;
}
return true;
}
public static void stopAutoBrightness(Activity activity) {
if (!isNotAllowedWriteSettings(activity)) {
Settings.System.putInt(activity.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS_MODE,
Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
}
}
public static void setBrightness(Activity activity, int brightness) {
if (!isNotAllowedWriteSettings(activity)) {
//constrain the value of brightness
if (brightness < BRIGHTNESS_MIN)
brightness = BRIGHTNESS_MIN;
else if (brightness > BRIGHTNESS_MAX)
brightness = BRIGHTNESS_MAX;
ContentResolver cResolver = activity.getContentResolver();
Settings.System.putInt(cResolver, Settings.System.SCREEN_BRIGHTNESS, brightness);
}
}
private static void startActivityToAllowWriteSettings(Activity activity) {
Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
intent.setData(Uri.parse("package:" + activity.getPackageName()));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(intent);
}
#SuppressLint("ObsoleteSdkInt")
private static boolean isNotAllowedWriteSettings(Activity activity) {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.System.canWrite(activity);
}
}
There you go, short and sweet; Kotlin version.
/**
* This can be used to override the user's preferred brightness of the screen.
* A value of less than 0, the default, means to use the preferred screen brightness.
* 0 to 1 adjusts the brightness from dark to full bright!
*/
fun Fragment.screenBrightness(x: Float) = activity?.screenBrightness(x)
fun Activity.screenBrightness(x: Float) = window?.apply {
attributes = attributes?.apply { screenBrightness = x.coerceIn(-1f..1f) } }
Kdoc'd also!

Categories