So im trying to make something like this https://play.google.com/store/apps/details?id=pt.bbarao.nightmode . I added transparrent background at first before layout and when the imagebutton is clicked, then the blackish screen filter is applied, but for some reason, the button is not working and i cant even move the seekbar around. Help is much appriciated, thank you! Heres the code:
public class Nightmode extends AppCompatActivity {
private boolean nightmodeOnOff;
public ImageButton modeOnOffButton;
private int brightness;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
setContentView(R.layout.activity_nightmode);
modeOnOffButton = (ImageButton) findViewById(R.id.nightmodeOnOffButton);
nightmodeOnOff = false;
int prog;
//Seekbar
SeekBar skbar = (SeekBar) findViewById(R.id.nightModeBar);
skbar.setMax(255);
skbar.setKeyProgressIncrement(127);
try {
brightness = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
} catch (Exception e) {
e.printStackTrace();
}
skbar.setProgress(brightness);
skbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
if (progress <= 25) {
brightness = 25;
} else {
brightness = progress;
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
android.provider.Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, brightness);
WindowManager.LayoutParams lpp = getWindow().getAttributes();
lpp.screenBrightness = brightness/(float)255;
getWindow().setAttributes(lpp);
}
});
}
public void nightmodeButtonClicked(View view) {
try {
if (nightmodeOnOff) {
nightmodeOnOff = false;
turnNightOff();
} else {
nightmodeOnOff = true;
turnNightOn();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void turnNightOn() {
try {
modeOnOffButton.setImageResource(R.drawable.nightmodeonbutton);
findViewById(R.id.activity_nightmode).setBackgroundColor(0x66000000);
} catch (Exception e) {
e.printStackTrace();
}
}
private void turnNightOff() {
try {
modeOnOffButton.setImageResource(R.drawable.nightmodeonoffbutton);
findViewById(R.id.activity_nightmode).setBackgroundColor(33000000);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onResume() {
super.onResume();
turnNightOff();
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
turnNightOff();
}
#Override
protected void onDestroy() {
super.onDestroy();
turnNightOff();
}
#Override
protected void onPause() {
super.onPause();
turnNightOn();
}
}
Related
I want to change the brightness using seekBar it changes but the notification brightness bar progress is not the same as the progress value.
public class MainActivity extends AppCompatActivity {
private SeekBar seekBright;
private TextView txtProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
seekBright=findViewById(R.id.seekBright);
txtProgress=findViewById(R.id.txtProgress);
if(Build.VERSION.SDK_INT> Build.VERSION_CODES.M) {
boolean canWriteSettings = Settings.System.canWrite(this);
if (!canWriteSettings) {
Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
startActivity(intent);
}
}
seekBright.setMax(255);
seekBright.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
setScreenBrightness(MainActivity.this,i);
txtProgress.setText(i+"/"+seekBar.getMax
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
// finally use the below method to set the brightness
new LoadApplications().execute();
}
public void setScreenBrightness(Context mContext, int brightnessValue){
// Make sure brightness value between 0 to 255
if(brightnessValue >= 0 && brightnessValue <= 255){
Settings.System.putInt(
mContext.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS,
brightnessValue
);
}
}
}
This Output of my code
When set to 0 progress is displayed anywhere.
when set to 1 it displays proper
** Screenshot emulator version I SDK-33**
I had this problem too. I did a lot of searches and built it together:
public class Brightness extends AppCompatActivity {
SeekBar seekBar;
TextView br_value;
Handler handler = new Handler();
Runnable refresh;
public static int CODE_WRITE_SETTINGS_PERMISSION = 42;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_brightness);
seekBar = findViewById(R.id.seekBar);
br_value = findViewById(R.id.brightness_status_info);
int brightness = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, 0);
seekBar.setMax(getMaxBrightness(getApplicationContext(), brightness));
seekBar.setProgress(brightness);
int br_in_perc = seekBar.getProgress();
br_value.setText(String.valueOf(100*br_in_perc/seekBar.getMax())+" %");
writeSettings();
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
Context context = getApplicationContext();
boolean canWrite = Settings.System.canWrite(context);
if (canWrite) {
int sBrightness = seekBar.getMax()-(seekBar.getMax()-progress);
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, sBrightness);
refresh = new Runnable() {
#SuppressLint("SetTextI18n")
public void run() {
int br_in_perc = seekBar.getProgress();
br_value.setText(String.valueOf(100*br_in_perc/seekBar.getMax())+" %");
handler.postDelayed(refresh, 100);
}
};
handler.post(refresh);
} else {
br_value.setText(R.string.write_settings_not_allowed);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
public int getMaxBrightness(Context context, int defaultValue){
PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
if(powerManager != null) {
Field[] fields = powerManager.getClass().getDeclaredFields();
for (Field field: fields) {
//https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/os/PowerManager.java
if(field.getName().equals("BRIGHTNESS_ON")) {
field.setAccessible(true);
try {
return (int) field.get(powerManager);
} catch (IllegalAccessException e) {
return defaultValue;
}
}
}
}
return defaultValue;
}
public void writeSettings() {
boolean canWrite = Settings.System.canWrite(getApplicationContext());
if (!canWrite) {
AlertDialog.Builder writeSettingsDialog = new AlertDialog.Builder(Brightness.this, R.style.AlertDialog);
writeSettingsDialog.setTitle(R.string.bright_alert_title)
.setMessage(R.string.bright_alert_text)
.setCancelable(false)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
startActivity(intent);
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
Toast.makeText(Brightness.this, R.string.settings_cancelled, Toast.LENGTH_SHORT).show();
}
});
AlertDialog alertDialog = writeSettingsDialog.create();
alertDialog.show();
alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.black));
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.black));
}
}
}
At the end of the code is AlertDialog which checks for permission to write settings.
Hope it helps ๐๐
I am trying to create a flashlight app with a strobe effect. My goal is that I can turn ON/OFF the flashlight with a switch Btn and increase the strobe frequency with a seekbar. If the seekbar value is 0 and the switch Btn is ON the flashlight should be ON (without any strobe). But right now it is still blinking (strobe effect ON) if the seekbar value is 0. Do you know how I can change that?
Here is some of the code which I think is important (I really can't find the part which keeps the stobe effect still on:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mySwitch = (Switch) findViewById(R.id.mySwitch);
//listener to check changes in state
mySwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
turnOnOff(isChecked);
}
});
skBar = (SeekBar) findViewById(R.id.seekBar);
skBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
freq = progress;
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
#Override
protected void onResume() {
super.onResume();
try {
cam = Camera.open();
camParams = cam.getParameters();
cam.startPreview();
hasCam = true;
}catch(Exception e){
}
}
private void turnOnOff(boolean on){
if(on) {
if(freq != 0){
sr = new StroboRunner();
t = new Thread(sr);
t.start();
return;
}else{
camParams.setFlashMode(Parameters.FLASH_MODE_TORCH);
}
}else if(!on){
if(t != null){
sr.stopRunning = true;
t =null;
return;
}else{
camParams.setFlashMode(Parameters.FLASH_MODE_OFF);
}
}
cam.setParameters(camParams);
cam.startPreview();
}
private class StroboRunner implements Runnable {
boolean stopRunning = false;
#Override
public void run() {
Camera.Parameters paramsOn = cam.getParameters();
Camera.Parameters paramsOff = camParams;
paramsOn.setFlashMode(Parameters.FLASH_MODE_TORCH);
paramsOff.setFlashMode(Parameters.FLASH_MODE_OFF);
try {
while (!stopRunning) {
cam.setParameters(paramsOn);
cam.startPreview();
Thread.sleep(100 - freq);
cam.setParameters(paramsOff);
cam.startPreview();
Thread.sleep(100 - freq);
}
}catch(Exception e){
}
}
}
}
i want to reset the seekbar to start position once the music is played and button showing "play"...The problem with the code is that the seek bar stays at the end position after its done playing the music and button still shows "pause"...
Here's my code
ekdanta.java
public class ekdanta extends AppCompatActivity implements Runnable, View.OnClickListener,SeekBar.OnSeekBarChangeListener {
TextView tv4;
Button b9, b10,but19;
int count = 0;
MediaPlayer play;
SeekBar seek_bar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ekdanta);
tv4 = (TextView) findViewById(R.id.textView9);
tv4.setTextSize((float)21.5);
tv4.setText(Html.fromHtml(getString(R.string.thirteen)));
b9 = (Button) findViewById(R.id.b9);
b10 = (Button) findViewById(R.id.b10);
seek_bar = (SeekBar) findViewById(R.id.seekBar);
seek_bar.setOnSeekBarChangeListener(this);
seek_bar.setEnabled(false);
but19 = (Button) findViewById(R.id.button19);
but19.setOnClickListener(this);
}
public void run() {
int currentPosition= play.getCurrentPosition();
int total = play.getDuration();
while (play!=null && currentPosition<total) {
try {
Thread.sleep(1000);
currentPosition= play.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seek_bar.setProgress(currentPosition);
}
}
public void onClick(View v) {
if (v.equals(but19)) {
if (play == null) {
play = MediaPlayer.create(getApplicationContext(), R.raw.ekadanta);
seek_bar.setEnabled(true);
}
if (play.isPlaying()) {
play.pause();
but19.setText("Play");
} else {
play.start();
but19.setText("Pause");
seek_bar.setMax(play.getDuration());
new Thread(this).start();
}
}
}
#Override
protected void onPause() {
if(play!=null){
play.stop();
}
super.onPause();
}
public void increase(View inc) {
count++;
if (count == 1) {
tv4.setTextSize(25);
} else if (count == 2) {
tv4.setTextSize(30);
} else if (count >= 3) {
count = 3;
tv4.setTextSize(40);
}
}
public void decrease(View dec) {
count--;
if (count <= 0) {
tv4.setTextSize((float)21.5);
count = 0;
}
if (count == 1) {
tv4.setTextSize(25);
} else if (count == 2) {
tv4.setTextSize(30);
} else if (count == 3) {
tv4.setTextSize(40);
}
}
#Override
public void onProgressChanged(SeekBar seek_bar, int progress, boolean fromUser) {
try{
if(play.isPlaying()||play!=null){
if (fromUser)
play.seekTo(progress);
}
else if(play==null){
Toast.makeText(getApplicationContext(),"First Play", Toast.LENGTH_SHORT).show();
seek_bar.setProgress(0);
}
}
catch(Exception e){
Log.e("seek bar",""+e);
seek_bar.setEnabled(false);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
MediaPlayer has got onCompletionListener(), you can use that. Your code with handlers is not too reliable, it would be better to refactor it.
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// do whatever you want
}
});
I have a thread named runner. I want to stop this thread onBackPressed but this is not happening. Here is the code:
public class StrobeLightConfig extends Activity {
Camera cam;
StrobeRunner runner;
Thread bw;
CheckBox strobe;
private boolean isFlashOn;
private boolean hasFlash;
private Parameters params;
private MediaPlayer mp;
VerticalSeekBar skbar, skbaroff;
ToggleButton togglebutton;
public final Handler mHandler = new Handler();
public final Runnable mShowToastRunnable = new Runnable() {
public void run() {
showMessage();
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
skbar = (VerticalSeekBar) findViewById(R.id.SeekBar01);
strobe = (CheckBox) findViewById(R.id.checkBox1);
togglebutton = (ToggleButton) findViewById(R.id.ToggleButton01);
skbaroff = (VerticalSeekBar) findViewById(R.id.SeekBar02);
hasFlash = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
turnOnFlash();
strobe.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (buttonView.isChecked()) {
cam.release();
Toast.makeText(getApplicationContext(), "Released 1", 0)
.show();
} else {
cam.release();
Toast.makeText(getApplicationContext(), "Released 2", 0)
.show();
}
}
});
runner = StrobeRunner.getInstance();
runner.controller = this;
if (runner.isRunning) {
} else {
try {
if (cam == null) {
cam = Camera.open();
}
} catch (RuntimeException ex) {
togglebutton.setEnabled(false);
TextView t = (TextView) findViewById(R.id.TextViewHW2);
t.setText(R.string.nocamera);
Toast.makeText(getApplicationContext(),
"Error connecting to camera flash.", Toast.LENGTH_LONG)
.show();
return;
}
}
togglebutton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Perform action on clicks
if (strobe.isChecked()) {
if (togglebutton.isChecked()) {
turnOnStrobe();
} else {
turnOffStrobe();
}
} else {
if (isFlashOn) {
// turn off flash
turnOffFlash();
} else {
----------------- runner.requeststop working here---------------------
turnOnFlash();
}
}
}
});
skbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
runner.delay = progress;
}
});
skbaroff.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
runner.delayoff = progress;
}
});
}
private void getCamera() {
if (cam == null) {
try {
cam = Camera.open();
params = cam.getParameters();
} catch (RuntimeException e) {
Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
}
}
}
/*
* Turning On flash
*/
private void turnOnFlash() {
if (!isFlashOn) {
togglebutton.setChecked(true);
cam = Camera.open();
params = cam.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
cam.setParameters(params);
cam.startPreview();
isFlashOn = true;
strobe.setEnabled(false);
}
}
private void turnOffFlash() {
if (isFlashOn) {
togglebutton.setChecked(false);
params = cam.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
cam.setParameters(params);
cam.stopPreview();
cam.release();
isFlashOn = false;
strobe.setEnabled(true);
}
}
private void turnOnStrobe() {
if (!isFlashOn) {
strobe.setEnabled(false);
bw = new Thread(runner);
bw.start();
}
}
private void turnOffStrobe() {
if (isFlashOn) {
runner.requestStop = true;
strobe.setEnabled(true);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onRestart() {
super.onRestart();
}
public void showMessage() {
String err = runner.errorMessage;
runner.errorMessage = "";
if (!err.equals("")) {
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, err, duration);
toast.show();
}
ToggleButton togglebutton = (ToggleButton) findViewById(R.id.ToggleButton01);
togglebutton.setChecked(false);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
if (strobe.isChecked()) {
turnOffStrobe();
} else {
if (isFlashOn) {
----------------- runner.requeststop needs to work here---------------------
turnOffFlash();
finish();
moveTaskToBack(true);
}
}
}
}
However if I write
runner.requestStop = true;
strobe.setEnabled(true);
at the place of TurnoffStrobe in the oncreate (not onBackPressed), its working. What can I do to have runner.requeststop working outside onCreate.?
Try
your_thread.isInterrupted(); inside onBackpress()
I have this code in my Android application:
private void showMyViews() {
mAnimation.cancel();
mAnimation.reset();
mAnimateionView.clearAnimation();
mAnimationView.setVisibility(View.GONE);
mOtherViewToHide.setVisibility(View.GONE);
mFirstViewToShow.setVisibility(View.VISIBLE);
mSecondViewToShow.setVisibility(View.VISIBLE);
}
But sometimes mSecondViewToShow appears a little bit before mFirstViewToShow. How could I easily force these Views to appear at the same time?
Some of the code is:
public class mFragment extends Fragment implements OnClickListener, com.squareup.picasso.Callback {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.mFragment, null);
mFirstViewToShow = (RelativeLayout) view
.findViewById(R.id.mFirstViewToShow);
mSecondViewToShow = (RelativeLayout) view
.findViewById(R.id.mSecondViewToShow);
...
...
...
if (isConnected()) {
animateMagnifier();
updateUserLocation();
} else {
}
}
private void animateMagnifier() {
Thread mThread = new Thread(new Runnable() {
#Override
public void run() {
AppLog.Log(TAG, "ver si la lupa sirve");
if (getActivity() != null) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
mAnimationView.setVisibility(View.VISIBLE);
animeMagnifier = AnimationUtils
.loadAnimation(getActivity(),
R.anim.translate_center_amim);
mAnimationView.startAnimation(animeMagnifier);
// Code use to repeat the animation
// See
// http://stackoverflow.com/questions/4480652/android-animation-does-not-repeat
animeMagnifier
.setAnimationListener(new AnimationListener() {
#Override
public void onAnimationStart(
Animation animation) {
}
#Override
public void onAnimationRepeat(
Animation animation) {
}
#Override
public void onAnimationEnd(
Animation animation) {
animeMagnifier = AnimationUtils
.loadAnimation(
getActivity(),
R.anim.translate_center_amim);
animeMagnifier
.setAnimationListener(this);
mAnimationView
.startAnimation(animeMagnifier);
}
});
}
});
}
}
});
mThread.start();
try {
mThread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void updateUserLocation() {
...
...
...
sendDataToServer();
}
private void sendDataToServer() {
...
...
...
findPerson();
}
private void findPerson() {
new BackGroundTaskForFindPerson().execute();
}
private class BackGroundTaskForFindMatch extends
AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
try {
findPeopleResponse = mServices.makeHttpRequest(
Constant.find_people, Constant.methodeName,
findPeopleValuePairList);
Gson gson = new Gson();
...
...
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
try {
if (success) {
if (mFindPeople.getErrNum() == 2) {
// no one found
mFirstViewToShow.setVisibility(View.GONE);
mSecondViewToShow.setVisibility(View.GONE);
messageTextView.setText(R.string.no_one_near);
} else if (mFindPeople.getErrNum == 3) {
...
} else {
....
}
} else {
messageTextView.setText(R.string.no_one_new);
}
} catch (Exception e) {
....
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
}
Set them to INVISIBLE instead of GONE that way they will be attached to your layout but hidden.
At the moment they must be added to your view hierarchy before they are revealed, that's probably what's causing your delay.