[Q] Adjusting screen brightness via SeekBar - Java for Android App Development

Such a simple thing but it's literally driving me crazy.
How do I use WindowManager.LayoutParams and SeekBar in conjuction to adjust the brightness within the app (It doesn't have to change system wide settings, although if that's easier why not)

Supovitz said:
Such a simple thing but it's literally driving me crazy.
How do I use WindowManager.LayoutParams and SeekBar in conjuction to adjust the brightness within the app (It doesn't have to change system wide settings, although if that's easier why not)
Click to expand...
Click to collapse
It's very easy.
Basically, you have parameter "screenBrightness" in your LayoutParams object.
It's minimal value is 0.0, and it's maximum value is 1.0.
Let's say you have SeekBar with maximum value of 255.
So, in your OnSeekBarChangeListener you must have something like this:
Code:
[user=439709]@override[/user]
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
mLayoutParams=(float)(progress/seekBar.getMax()); //we need to scale our brightness from SeekBar max value to the value //between 0 and 1.
mWindowManager.updateViewLayout(mView, mLayoutParams);
}
mWindowManager is an instance of WindowManager.
mView is a View which you have to attach to the window. It can be a dummy view with no children, just don't forget to remove it before finishing your app.
Please note that this settings won't persist after you remover your dummy View.

Related

Positioning items on the stage

I am used to work with Flash and if we want to position an item at certain coordinates on the stage we just modify the .x and .y values. But I can't manage to find a way to this to a TextView (or any other item for that matter).
I did manage to get the width and height of the stage using this:
Code:
Display display = getWindowManager().getDefaultDisplay();
stageWidth = display.getWidth();
stageHeight = display.getHeight();
But, if I want for example to position a TextView called tv at the coordinates like this:
tv.x = stageWidth - tv.width - 30
tv.y = stageHeight - tv.height - 30
I don't know how to do it.
Thanks, and sorry if this is a stupid answer...maybe I am to used in working with Flash.

[Q] How to enable/disable auto brightness mode from API

Hi, I want to control the system settings "auto brightness", setting it ON or OFF.
I'm able to control the brightness level but only if AUTO is OFF.
From what I read until now there is a SCREEN_BRIGHTNESS_MODE in Settings.System but only for API level 8 or higher and also not recommended to mess wit it.
But currently my phone has Android 2.1 (API 7) and there are widgets that can control this setting (enable/disable auto brightness and set the level), so I'm sure it is possible.
Tried also with IHardwareService but couldn't find anything about this.
How is this done ? Thanks.
Ok, solved
Could you kindly post your solution so when others find this thread in a search, they don't cuss and throw things when they find out that it doesn't help them at all?
Actually, I it like in API 8, except that you define the strings. It works in API 7, don't know if it's working in lower versions.
private static final String SCREEN_BRIGHTNESS_MODE = "screen_brightness_mode";
private static final int SCREEN_BRIGHTNESS_MODE_MANUAL = 0;
private static final int SCREEN_BRIGHTNESS_MODE_AUTOMATIC = 1;
Settings.System.putInt(resolver,
SCREEN_BRIGHTNESS_MODE, mode);
Settings.System.putInt(resolver,
Settings.System.SCREEN_BRIGHTNESS,
lev);

[Q] How to keep layouts inflated after activity restarts

Hi guys,
On a button click I am inflating a layout like so:
Code:
public void plusLayout(View v) {
// inflating layout here:
LinearLayout ll1 = (LinearLayout) findViewById(R.id.main_layout);
// this layout is being inflated:
View newView = getLayoutInflater().inflate(R.layout.layout_to_be_added, null);
// add layout
ll1.addView(newView);
}
But when the activity restarts, the inflated layouts are gone.
I'd like the layouts to stay there.
(The user can click a button to remove the layout by hand).
I must be missing something trivial here right?
Cheers,
Daan
Which way is it restarted?
If the complete app is restarted, a new layout will be set in the onCreate method.
nikwen said:
Which way is it restarted?
If the complete app is restarted, a new layout will be set in the onCreate method.
Click to expand...
Click to collapse
Yeah when you press back button and start the app again or completely kill it.
It also happens on orientation change as the activity get restarted then as well.
But I think you can override that in the manifest somewhere.
DaanJordaan said:
Yeah when you press back button and start the app again or completely kill it.
It also happens on orientation change as the activity get restarted then as well.
But I think you can override that in the manifest somewhere.
Click to expand...
Click to collapse
Ah ok.
The point is: If you open the app or turn your device, the onCreate method is called. There you set a completely new layout. You would need to save that the layout is inflated (you could use a SharedPreferences entry) and inflate it in the onCreate method. If you just want it to appear again after turning the device, use the onSaveInstanceState method and the onRestoreInstanceState method. That would be better practice.
Look at the activity lifecycle.
Just so I'm sure I get this right :
The user launches the app, the layouts are not inflated
He presses a button which calls your plusLayout() method, so the layouts are now inflated
The user quits the activity and restarts it, the layouts are not inflated anymore but you want them to.
Is that correct ?
If it is, 2 ways I can think of :
Overriding savedInstanceState() & onRestoreInstanceState() :
First, declare a private Boolean before the onCreate() of your activity :
Code:
private Boolean isInflated = false;
Then, set it to true in the onClick() of your button, and override savedInstanceState and onRestoreInstanceState like so :
Code:
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Save state changes to the savedInstanceState.
// This bundle will be passed to onCreate if th activity is
// killed and restarted.
savedInstanceState.putBoolean("inflate", isInflated);
}
Code:
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
Boolean myBoolean = savedInstanceState.getBoolean("inflate");
if (myBoolean == true)
plusLayout(myView);
}
Using the sharedPreferences
Same logic, different way to save the boolean :
Before onCreate(), declare a private boolean and a private SharedPreferences :
Code:
private Boolean isInflated = false;
private SharedPreferences prefs = getSharedPreferences("MY_PREFS");
in the onClick of your button :
Code:
isInflated = true;
Editor e = prefs.edit();
e.putBoolean("inflate", isInflated);
e.commit();
Then, in your onCreate(), retrieve the stored value and if it's true, call your plusLayout() method :
Code:
Boolean doInflate = prefs.getBoolean("inflate", false // this is the default value);
if (doInflate == true)
plusLayout(myView);
nikwen said:
Ah ok.
The point is: If you open the app or turn your device, the onCreate method is called. There you set a completely new layout. You would need to save that the layout is inflated (you could use a SharedPreferences entry) and inflate it in the onCreate method. If you just want it to appear again after turning the device, use the onSaveInstanceState method and the onRestoreInstanceState method. That would be better practice.
Look at the activity lifecycle.
Click to expand...
Click to collapse
Okay I'm working on that at the moment.
Whenever a layout is created an (int) "counter" get incremented.
I will save this "counter" in the SharedPreferences.
When the app starts layouts get created "counter" times.
Is this good practice?
It seems so strange that there isn't an easier way to save layout/activity states.
Edit:
Androguide.fr said:
Just so I'm sure I get this right :
The user launches the app, the layouts are not inflated
He presses a button which calls your plusLayout() method, so the layouts are now inflated
The user quits the activity and restarts it, the layouts are not inflated anymore but you want them to.
Is that correct ?
Click to expand...
Click to collapse
That is correct. Big thanks for the examples.
DaanJordaan said:
Okay I'm working on that at the moment.
Whenever a layout is created an (int) "counter" get incremented.
I will save this "counter" in the SharedPreferences.
When the app starts layouts get created "counter" times.
Is this good practice?
It seems so strange that there isn't an easier way to save layout/activity states.
Edit:
That is correct. Big thanks for the examples.
Click to expand...
Click to collapse
I would use his snippets. They are good (as always). Decide which one to use by what I have given above:
Just for turning:
onSaveInstanceState and onRestoreSavedInstanceState
For turning and reopening:
Shared preferences

Display update regularity weirdness @ 1Hz w/video example (code, not NoRefresh issue)

At it's core... a simple clock app. I'm firing off updates scheduled on each second. On each second, I read the time, then display the time. This is not complicated. And it works, just fine, on my phone. Tick, tick, tick and it looks like a clock. Why wouldn't it, right?
Ok, so the same code on the nook doesn't update regularly. Here's an early video:
http://www.youtube.com/watch?v=URRrYhumt1Y
You can see there's a "double beat". It's like every other update gets displayed for maybe 1.5 seconds. So the overall rate doesn't change, it's still two updates in two seconds, and no updates are missed.
These are being done with a regular myView.setText(), no fancy graphics or anything.
Now, here's more interesting data. If I run the updates twice as often, or five times as often, it changes nothing. I assume the screen/OS is internally detecting no pixels have changed, and so it does nothing. However, if I add, to a totally different view on the screen, an area where I'm toggling from some text to no text (from " " to "+", in actuality, so, a blinking plus sign) AND I run everything at five times a second then the seconds area updates with a steady one hertz beat, just like you would expect from a clock.
Additionally, if I run the code so it only updates every other second, it will click along very predictably at every other second. So it's not a "some code problem with every other update".
I wonder if there's some internal timer in the OS watching for screen updates, and managing them? Perhaps "pushing" the display with a toggling update every 200ms keeps it active and within some timeout limit?
Or are there some nook-specific calls on this?
Cheers,
Anders
I believe that some of the super-duper fast-mode or-whatever-you-call-it throws away some screen updates.
Are you using such a thing or a kernel with such a thing?
No, I'm not attempting any speedy-screen stuff in this code. In the video you can see the grey in the bar, so I'm not in any kind of a 1-bit mode. Because really, one update a second should be no problem.
But if it was throwing away an update... why would the update show up half a second later? I would expect it to skip displaying that second entirely, and so jump to the next.
NoRefresh is installed on this device, but not set to start at boot (and honestly, I don't think I've actually gotten NoRefresh working yet, busy with other things). But I'll uninstall it to be sure and retest.
Is it possible some kind of low-power mode / sleep mode is kicking in? It wakes up half a second later, realizes it has an update, stays away for the next half second, makes the NEXT update (on time) then goes back to sleep after a 0.9ish seconds?
Anders
Yep, even after uninstalling NoRefresh, and rebooting, the behavior is the same. So that's definitely not related.
And running the normal updates to the screen at both 2Hz and 5Hz have the same result, so it's not related to the number of times the updates are called.
Anders
Here's an interesting video... watching the ADB output click along at a clean 1Hz, and the screen updates clearly not synced with the actual writes to the screen.
http://www.youtube.com/watch?v=sL299EUH3T0
Again, all on "stock" system, no special video modes / refresh / magic enabled.
Anders
Actually, I have run into this.
There's no documentation on modes or theory of operating a frame buffer for eInk.
I ran into this on the time display on my audio recorder app.
I ended up using a DL region in my app.
I'll have to look closer into how bad it looks without that.
Are those numbers a TextView or an ImageView?
If it isn't a TextView try one to see if it works better.
There may be slowness in caching/using images.
More questions:
Are you using Timer & TimerTask?
Are you using runOnUiThread?
I wrote a demo app that counts.
It works fine by itself on stock 1.2.1
Renate NST said:
Actually, I have run into this.
There's no documentation on modes or theory of operating a frame buffer for eInk.
I ran into this on the time display on my audio recorder app.
I ended up using a DL region in my app.
I'll have to look closer into how bad it looks without that.
Click to expand...
Click to collapse
DL region? Not familiar with the acronym.
Are those numbers a TextView or an ImageView?
Click to expand...
Click to collapse
It's a text view. Just a big blocky TTF font. (Although the same issue is present using stock fonts).
Are you using Timer & TimerTask?
Are you using runOnUiThread?
Click to expand...
Click to collapse
Using scheduled handlers. They are triggering normally, since A] the ADB output is firing at nice one second intervals, and B] the SystemClock.uptimeMillis shows a 1000 count between each wake up. It's off by one or two millis which is understandable given that it's not a hard-realtime system.
But I'm not familiar with Timer and runOnUiThread, so I'll google those and do some reading.
(In the below code, the "nookPing" area is a tiny spot where I just toggle some pixels. If I do this and run the whole thing at faster than 1Hz, the seconds digit updates on schedule. Turn off this toggling, (which is in a totally unrelated textarea) and back to wonky updates, even at the same update rate. )
Code:
// //////////////////////////////////////////////////////////////////////////////////////////////////
// The Tick task itself /////////////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////////////////////////////////
private Handler mHandler = new Handler();
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
Log.d(TAG, "---------------------Tick Called: " +String.valueOf(SystemClock.uptimeMillis()) );
Log.d(TAG, "---------------------");
updateTimeOnScreen();
scheduleNextScreenUpdate();
}
};
// //////////////////////////////////////////////////////////////////////////////////////////////////
// Schedule next update /////////////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////////////////////////////////
private void scheduleNextScreenUpdate()
{
mHandler.removeCallbacks(mUpdateTimeTask);
mHandler.postAtTime(mUpdateTimeTask,UtilitiesTime.calculateNextScreenUpdateTime());
}
// //////////////////////////////////////////////////////////////////////////////////////////////////
// Show the time ////////////////////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////////////////////////////////
static int nookPing=0;
private void updateTimeOnScreen() {
String hhmm;
int militaryhours,hour;
int minutes;
int seconds;
int tenths;
int milliseconds;
Calendar rightNow = Calendar.getInstance();
militaryhours=rightNow.get(Calendar.HOUR_OF_DAY);
hour=rightNow.get(Calendar.HOUR);
minutes=rightNow.get(Calendar.MINUTE);
seconds=rightNow.get(Calendar.SECOND);
milliseconds=rightNow.get(Calendar.MILLISECOND);
tenths=milliseconds/100;
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
if(true==settings.getBoolean("appSettingNookPingActive", false))
{
if(0==nookPing)
{
nookPing=1;
nookPingView.setText(".");
//nookPingView.setText(" ");
}
else{
nookPing=0;
nookPingView.setText(" ");
}
}
else{
nookPingView.setText(" ");
}
if(Configuration.ORIENTATION_PORTRAIT==getScreenOrientation())
{
if(1==MainActivity.appSettingMilitaryTimeFlag)
{
hhmm=String.format(Locale.US,"%02d:%02d",militaryhours, minutes);
}
else{
if(0==hour)
hour=12;
hhmm=String.format("%2d:%02d",hour, minutes);
}
}
else
{
if(1==MainActivity.appSettingMilitaryTimeFlag)
{
hhmm=String.format("%02d\n--\n%02d",militaryhours, minutes);
}
else{
if(0==hour)
hour=12;
hhmm=String.format("%2d\n--\n%02d",hour, minutes);
}
}
int secondsTens=seconds/10;
int secondsOnes=seconds%10;
secondsLeftView.setText(String.format("%d",secondsTens));
secondsRightView.setText(String.format("%d",secondsOnes));
hhmmView.setText(hhmm);
}

Maintain/Remember Changed items position after restarting app (Using ItemTouchHelper)

Hello, I'm having a problem in remembering items position after being changed, I'm using ItemTouchHelper to achieve the drag and drop effect, after being changed, restarting will reset the changes back to the default.
So, What's the way to maintain the changed positions ?
Here's the code :
HTML:
ItemTouchHelper.Callback _ithCallback = new ItemTouchHelper.Callback() {
//and in your imlpementaion of
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
// get the viewHolder's and target's positions in your adapter data, swap them
Collections.swap(AllItems, viewHolder.getAdapterPosition(), target.getAdapterPosition());
// and notify the adapter that its dataset has changed
rcAdapter.notifyItemMoved(viewHolder.getAdapterPosition(), target.getAdapterPosition());
return true;
}
[user=439709]@override[/user]
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
//TODO
}
//defines the enabled move directions in each state (idle, swiping, dragging).
[user=439709]@override[/user]
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
return makeFlag(ItemTouchHelper.ACTION_STATE_DRAG,
ItemTouchHelper.DOWN | ItemTouchHelper.UP | ItemTouchHelper.START | ItemTouchHelper.END);
}
};
Where is the data stored which is displayed in the recyclerView? When the order is changed I recommend saving your data in this new order to your database/etc when the activity is paused.
Sent from my Nexus 5 using Tapatalk
Masrepus said:
Where is the data stored which is displayed in the recyclerView? When the order is changed I recommend saving your data in this new order to your database/etc when the activity is paused.
Sent from my Nexus 5 using Tapatalk
Click to expand...
Click to collapse
Positions are automatically Added, example:
Mylist.item(new item .blablabla);
Mylist.item(new item .blablabla2);
first one will be in position 0, second one in position 1, that's how the positions are added.
abo hani said:
Positions are automatically Added, example:
Mylist.item(new item .blablabla);
Mylist.item(new item .blablabla2);
first one will be in position 0, second one in position 1, that's how the positions are added.
Click to expand...
Click to collapse
Okay but the data is currently not being saved permanently in a database or something comparable, right? I would include a database to cache the list contents when the app is stopped.
Edit:
Alternatively you could also save the data in shared preferences, depending on its size
Sent from my Nexus 5 using Tapatalk

Categories

Resources