Android seek bar save progress values with sharedpreferences - java

I have an issue in save the value of progress of seek bar. I have two seek bar and have an one button and another one EditText widget. on click of button EditText seek bar value will be save in shared preferences, but on clicking it only save the EditTextvalue, not to save the value of seek bar. I try my best but its not working.My code is given below,
Profile2Activity.class
public class Profile2Activity extends Activity {
//TextViews to show details of volume and brightness
private TextView tVBrightness, tVVolume;
//SeekBars to set volume and brightness
private SeekBar sbVolume, sbBrightness;
//AudioManager object, that will get and set volume
private AudioManager audioManager;
//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;
int maxVolume = 1;
EditText e2;
Button b2;
public static final String MyPREFERENCESS = "MyPrefss";
public static final String OFFICEWIFI = "officewifi";
Context context = this;
private AudioManager myAudioManager;
SharedPreferences sharedpreferences;
//Suhas
String mVolume ;
String mBrightness;
public static final String BRIGHTNESS = "brightness";
public static final String VOLUME = "volume";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile2);
//Suggests an audio stream whose volume should be changed by the hardware volume controls.
setVolumeControlStream(AudioManager.STREAM_MUSIC);
// initializeControls2();
myAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
initializeControls2();
e2 = (EditText) findViewById(R.id.ed1);
b2 = (Button) findViewById(R.id.but1);
sharedpreferences = getSharedPreferences(MyPREFERENCESS, Context.MODE_PRIVATE);
final String officewifi = sharedpreferences.getString(OFFICEWIFI, "");
// final int brightnesss = Integer.parseInt(sharedpreferences.getString(BRIGHTNESS, ""));
// final int volumes = Integer.parseInt(sharedpreferences.getString(VOLUME, ""));
e2.setText(officewifi);
//sbVolume.setProgress(brightnesss);
// sbBrightness.setProgress(volumes);
// String str = sharedpreferences.getString(VOLUME, "");
// if(!TextUtils.isEmpty(str)){
// int volumes = Integer.parseInt(str);
// sbVolume.setProgress(volumes);
// }
int volume = sharedpreferences.getInt(VOLUME, 0);
sbVolume.setProgress(volume);
int brightness = sharedpreferences.getInt(BRIGHTNESS, 0);
sbVolume.setProgress(brightness);
// String strr = sharedpreferences.getString(BRIGHTNESS, "");
// if(!TextUtils.isEmpty(strr)){
// int brightnesss = Integer.parseInt(strr);
// sbBrightness.setProgress(brightnesss);
// }
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String officewifi = e2.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(OFFICEWIFI, officewifi);
//Suhas
editor.putInt(BRIGHTNESS, sbBrightness.getProgress());
editor.putInt(VOLUME, sbVolume.getProgress());
editor.commit();
Toast.makeText(Profile2Activity.this, "Thanks", Toast.LENGTH_SHORT).show();
sharedpreferences = getSharedPreferences(MyPREFERENCESS, Context.MODE_PRIVATE);
}
});
////////////////////////////////////////////////////////////////////////////////////
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWifi.isConnected()) {
final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
final WifiInfo con = wifiManager.getConnectionInfo();
//Toast.makeText(MainActivity.this, con.getSSID()+"",Toast.LENGTH_LONG).show();
if (con.getSSID().toString().equalsIgnoreCase("\"" + officewifi + "\"")) {
} else {
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
// Toast.makeText(MainActivity.this, "Now in Ringing Mode", Toast.LENGTH_SHORT).show();
}
} else {
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
// Toast.makeText(MainActivity.this, "Now in Ringing Mode", Toast.LENGTH_SHORT).show();
}
handler.postDelayed(this, 1000);
}
}, 1000);
}
private void initializeControls2() {
//get reference of the UI Controls
sbVolume = (SeekBar) findViewById(R.id.sbVolume);
sbBrightness = (SeekBar) findViewById(R.id.sbBrightness);
tVVolume = (TextView) findViewById(R.id.tVVolume);
tVBrightness = (TextView) findViewById(R.id.tVBrightness);
try {
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
//set max progress according to volume
sbVolume.setMax(audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
//get current volume
sbVolume.setProgress(audioManager.getStreamVolume(AudioManager.STREAM_MUSIC));
//Set the seek bar progress to 1
sbVolume.setKeyProgressIncrement(1);
//get max volume
maxVolume = sbVolume.getMax();
sbVolume.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);
//Calculate the brightness percentage
float perc = (progress / (float) maxVolume) * 100;
//Suhas
mVolume = ""+perc;
//Set the brightness percentage
tVVolume.setText("Volume: " + (int) perc + " %");
}
});
} catch (Exception e) {
}
//Get the content resolver
cResolver = getContentResolver();
//Get the current window
window = getWindow();
//Set the seekbar range between 0 and 255
sbBrightness.setMax(255);
//Set the seek bar progress to 1
sbBrightness.setKeyProgressIncrement(1);
try {
//Get the current system brightness
brightness = System.getInt(cResolver, System.SCREEN_BRIGHTNESS);
} catch (SettingNotFoundException e) {
//Throw an error case it couldn't be retrieved
Log.e("Error", "Cannot access system brightness");
e.printStackTrace();
}
//Set the progress of the seek bar based on the system's brightness
sbBrightness.setProgress(brightness);
//Register OnSeekBarChangeListener, so it can actually change values
sbBrightness.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar seekBar) {
//Set the system brightness using the brightness variable value
System.putInt(cResolver, System.SCREEN_BRIGHTNESS, brightness);
//Get the current window attributes
LayoutParams layoutpars = window.getAttributes();
//Set the brightness of this window
layoutpars.screenBrightness = brightness / (float) 255;
//Apply attribute changes to this window
window.setAttributes(layoutpars);
}
public void onStartTrackingTouch(SeekBar seekBar) {
//Nothing handled here
}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
//Set the minimal brightness level
//if seek bar is 20 or any value below
if (progress <= 20) {
//Set the brightness to 20
brightness = 20;
} else //brightness is greater than 20
{
//Set brightness variable based on the progress bar
brightness = progress;
}
//Calculate the brightness percentage
float perc = (brightness / (float) 255) * 100;
//Suhas
mBrightness = ""+perc;
//Set the brightness percentage
tVBrightness.setText("Brightness: " + (int) perc + " %");
}
});
}

Replace your code with this code:
public class Profile2Activity extends Activity {
//TextViews to show details of volume and brightness
private TextView tVBrightness, tVVolume;
//SeekBars to set volume and brightness
private SeekBar sbVolume, sbBrightness;
//AudioManager object, that will get and set volume
private AudioManager audioManager;
//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;
int maxVolume = 1;
EditText e2;
Button b2;
public static final String MyPREFERENCESS = "MyPrefss";
public static final String OFFICEWIFI = "officewifi";
Context context = this;
private AudioManager myAudioManager;
SharedPreferences sharedpreferences;
public static final String BRIGHTNESS = "brightness";
public static final String VOLUME = "volume";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile2);
//Suggests an audio stream whose volume should be changed by the hardware volume controls.
setVolumeControlStream(AudioManager.STREAM_MUSIC);
// initializeControls2();
myAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
e2 = (EditText) findViewById(R.id.ed1);
b2 = (Button) findViewById(R.id.but1);
sbVolume = (SeekBar) findViewById(R.id.sbVolume);
sbBrightness = (SeekBar) findViewById(R.id.sbBrightness);
tVVolume = (TextView) findViewById(R.id.tVVolume);
tVBrightness = (TextView) findViewById(R.id.tVBrightness);
sharedpreferences = getSharedPreferences(MyPREFERENCESS, Context.MODE_PRIVATE);
final String officewifi = sharedpreferences.getString(OFFICEWIFI, "");
e2.setText(officewifi);
Log.d("VOLUME", "" + sharedpreferences.getInt(VOLUME, 0));
Log.d("BRIGHTNESS", "" + sharedpreferences.getInt(BRIGHTNESS, 0));
sbVolume.setProgress(sharedpreferences.getInt(VOLUME, 0));
sbBrightness.setProgress(sharedpreferences.getInt(BRIGHTNESS, 0));
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String officewifi = e2.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(OFFICEWIFI, officewifi);
//Suhas
editor.putInt(BRIGHTNESS, sbBrightness.getProgress());
editor.putInt(VOLUME, sbVolume.getProgress());
editor.commit();
Toast.makeText(Profile2Activity.this, "Thanks", Toast.LENGTH_SHORT).show();
}
});
////////////////////////////////////////////////////////////////////////////////////
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWifi.isConnected()) {
final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
final WifiInfo con = wifiManager.getConnectionInfo();
//Toast.makeText(MainActivity.this, con.getSSID()+"",Toast.LENGTH_LONG).show();
if (con.getSSID().toString().equalsIgnoreCase("\"" + officewifi + "\"")) {
initializeControls2();
} else {
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
// Toast.makeText(MainActivity.this, "Now in Ringing Mode", Toast.LENGTH_SHORT).show();
}
} else {
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
// Toast.makeText(MainActivity.this, "Now in Ringing Mode", Toast.LENGTH_SHORT).show();
}
handler.postDelayed(this, 1000);
}
}, 1000);
}
private void initializeControls2() {
//get reference of the UI Controls
try {
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
//set max progress according to volume
sbVolume.setMax(audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
//get current volume
sbVolume.setProgress(audioManager.getStreamVolume(AudioManager.STREAM_MUSIC));
//Set the seek bar progress to 1
sbVolume.setKeyProgressIncrement(1);
//get max volume
maxVolume = sbVolume.getMax();
sbVolume.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);
float perc = (progress / (float) maxVolume) * 100;
//Set the brightness percentage
tVVolume.setText("Volume: " + (int) perc + " %");
}
});
} catch (Exception e) {
}
//Get the content resolver
cResolver = getContentResolver();
//Get the current window
window = getWindow();
//Set the seekbar range between 0 and 255
sbBrightness.setMax(255);
//Set the seek bar progress to 1
sbBrightness.setKeyProgressIncrement(1);
try {
//Get the current system brightness
brightness = System.getInt(cResolver, System.SCREEN_BRIGHTNESS);
} catch (SettingNotFoundException e) {
//Throw an error case it couldn't be retrieved
Log.e("Error", "Cannot access system brightness");
e.printStackTrace();
}
//Set the progress of the seek bar based on the system's brightness
sbBrightness.setProgress(brightness);
//Register OnSeekBarChangeListener, so it can actually change values
sbBrightness.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar seekBar) {
//Set the system brightness using the brightness variable value
System.putInt(cResolver, System.SCREEN_BRIGHTNESS, brightness);
//Get the current window attributes
LayoutParams layoutpars = window.getAttributes();
//Set the brightness of this window
layoutpars.screenBrightness = brightness / (float) 255;
//Apply attribute changes to this window
window.setAttributes(layoutpars);
}
public void onStartTrackingTouch(SeekBar seekBar) {
//Nothing handled here
}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
//Set the minimal brightness level
//if seek bar is 20 or any value below
if (progress <= 20) {
//Set the brightness to 20
brightness = 20;
} else //brightness is greater than 20
{
//Set brightness variable based on the progress bar
brightness = progress;
}
//Calculate the brightness percentage
float perc = (brightness / (float) 255) * 100;
//Set the brightness percentage
tVBrightness.setText("Brightness: " + (int) perc + " %");
}
});
}
}

Related

how to show a dialog after 1 or 2 min after opning app for first time

I want to show a custom XML dialog dialogue that will appear after a specific time in the first run, let's say after a min
how can I do it
but I'm confused about what should I do in a situation like below
if the user open the app for the first time and just spent 30 sec and just pause the app(screen lock or in onPause) or just close the app completely
Just as a note - I have already implemented a one time show dialog(directly in main activity without any layout file ) when the app runs for the first time already
Code
To view the already implemented dialog(shows up on the first run) please
go to the // Caution dialog (showDialog method)
MainActivity.java
public class MainActivity extends AppCompatActivity {
MediaPlayer player1;
MediaPlayer player2;
SeekBar seekBar1;
SeekBar seekBar2;
TextView elapsedTimeLable1;
TextView elapsedTimeLable2;
TextView remainingTimeLable1;
TextView remainingTimeLable2;
ImageView play1;
ImageView play2;
int totalTime1;
#SuppressLint("HandlerLeak")
private final Handler handler1 = new Handler() {
#SuppressLint("SetTextI18n")
#Override
public void handleMessage(#NonNull Message msg) {
int currentPosition1 = msg.what;
//Update SeekBar
seekBar1.setProgress(currentPosition1);
// Update Timelable
String elapsedTime1 = createTimerLable1(currentPosition1);
elapsedTimeLable1.setText(elapsedTime1);
String remainingTime1 = createTimerLable1(totalTime1 - currentPosition1);
remainingTimeLable1.setText("- " + remainingTime1);
}
};
int totalTime2;
#SuppressLint("HandlerLeak")
private final Handler handler2 = new Handler() {
#SuppressLint("SetTextI18n")
#Override
public void handleMessage(#NonNull Message msg) {
int currentPosition2 = msg.what;
// Update SeekBar
seekBar2.setProgress(currentPosition2);
// Update Timelable
String elapsedTime2 = createTimerLable2(currentPosition2);
elapsedTimeLable2.setText(elapsedTime2);
String remainingTime2 = createTimerLable2(totalTime2 - currentPosition2);
remainingTimeLable2.setText("- " + remainingTime2);
}
};
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#SuppressLint("ObsoleteSdkInt")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Window w = getWindow();
// clear FLAG_TRANSLUCENT_STATUS flag:
w.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// add FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS flag to the window
w.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
// finally change the color
w.setStatusBarColor(ContextCompat.getColor(this, R.color.Card_Elevation_Color));
}
// PlayButton * The ButtonClick is in the last if you want to jump directly there *
play1 = findViewById(R.id.playbtn1);
play2 = findViewById(R.id.playbtn2);
// TimeLables
elapsedTimeLable1 = findViewById(R.id.cTime1);
elapsedTimeLable2 = findViewById(R.id.cTime2);
remainingTimeLable1 = findViewById(R.id.tTime1);
remainingTimeLable2 = findViewById(R.id.tTime2);
// MediaPlayer
player1 = MediaPlayer.create(this, R.raw.dog_howl);
player1.setLooping(true);
player1.seekTo(0);
totalTime1 = player1.getDuration();
player2 = MediaPlayer.create(this, R.raw.dog_bark);
player2.setLooping(true);
player2.seekTo(0);
totalTime2 = player2.getDuration();
//SeekBar
seekBar1 = findViewById(R.id.seekbar1);
seekBar2 = findViewById(R.id.seekbar2);
seekBar1.setMax(totalTime1);
seekBar2.setMax(totalTime2);
seekBar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress1, boolean fromUser1) {
if (fromUser1) {
player1.seekTo(progress1);
seekBar1.setProgress(progress1);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
seekBar2.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress2, boolean fromUser2) {
if (fromUser2) {
player2.seekTo(progress2);
seekBar2.setProgress(progress2);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
// Thread (Update SeekBar & TimeLabel)
new Thread(() -> {
while (player1 != null) {
try {
Message msg = new Message();
msg.what = player1.getCurrentPosition();
handler1.sendMessage(msg);
Thread.sleep(1000);
} catch (InterruptedException ignored) {
}
}
}).start();
new Thread(() -> {
while (player2 != null) {
try {
Message msg = new Message();
msg.what = player2.getCurrentPosition();
handler2.sendMessage(msg);
Thread.sleep(1000);
} catch (InterruptedException ignored) {
}
}
}).start();
// Admob Banner Ad
MobileAds.initialize(this, initializationStatus -> {
});
AdView mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
// Caution dialog
SharedPreferences preferences = getSharedPreferences("prefs", MODE_PRIVATE);
boolean firstStart = preferences.getBoolean("firstStart", true);
if (firstStart) {
showDialog();
}
}
// Caution dialog
private void showDialog() {
new AlertDialog.Builder(this)
.setTitle("Caution!")
.setMessage("In case you're wearing any kind of headphones please remove it before playing the ' Howl ' audio")
.setPositiveButton("ok", (dialogInterface, i) -> dialogInterface.dismiss())
.create().show();
SharedPreferences preferences = getSharedPreferences("prefs", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("firstStart", false);
editor.apply();
}
public String createTimerLable1(int duration) {
String timerLabel1 = "";
int min = duration / 1000 / 60;
int sec = duration / 1000 % 60;
timerLabel1 += min + ":";
if (sec < 10) timerLabel1 += "0";
timerLabel1 += sec;
return timerLabel1;
}
public String createTimerLable2(int duration) {
String timerLabel2 = "";
int min = duration / 1000 / 60;
int sec = duration / 1000 % 60;
timerLabel2 += min + ":";
if (sec < 10) timerLabel2 += "0";
timerLabel2 += sec;
return timerLabel2;
}
public void playBtnClick1(View view) {
if (player2.isPlaying()) {
player2.pause();
play2.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
}
if (!player1.isPlaying()) {
// Stoping
player1.start();
play1.setImageResource(R.drawable.ic_baseline_pause_circle_filled_24);
} else {
// Playing
player1.pause();
play1.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
}
}
public void playBtnClick2(View view) {
if (player1.isPlaying()) {
player1.pause();
play1.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
}
if (!player2.isPlaying()) {
// Stoping
player2.start();
play2.setImageResource(R.drawable.ic_baseline_pause_circle_filled_24);
} else {
// Playing
player2.pause();
play2.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
}
}
#Override
protected void onPause() {
super.onPause();
if (player1 != null) {
player1.pause();
play1.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
}
if (player2 != null) {
player2.pause();
play2.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
}
}
}
but I'm confused about what should I do in a situation like below
if the user open the app for the first time and just spent 30 sec and just pause the app(screen lock or in onPause) or just close the
app completely
This is impossible to do if your app is closed.My suggestion would be to create a service on another process that does this dialog such that even if the app process is closed,the service process will still be running unless it is stopped explicitly.
Defining a Process of a Service
The android:process field defines the name of the process where the
service is to run. Normally, all components of an application run in
the default process created for the application. However, a component
can override the default with its own process attribute, allowing you
to spread your application across multiple processes.
If the name assigned to this attribute begins with a colon (':'), the
service will run in its own separate process.
<service android:name="com.example.appName" android:process=":externalProcess" />
This is of course in the manifest file .
You might also need to show a system dialog thus you will need a system Alert Window permission i your manifest and request for the permision on runtime.
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
Then on runtime request like this:
public static void openOverlaySettings(Activity activity) {
final Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + activity.getPackageName()));
try {
activity.startActivityForResult(intent, 6);
} catch (ActivityNotFoundException e) {
Log.e("Drawers permission :", e.getMessage());
}
}
To check if granted use :
if(!Settings.canDrawOverlays(context)) {
openOverlaySettings(context);
ok=false;
}
Then in your service you should create the dialog like below
View aldv= LayoutInflater.from(act).inflate(R.layout.your_layout,null);
ald=new AlertDialog.Builder(act,R.style.AppTheme)
.setView(aldv)
.setCancelable(true)
.create();
ald.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);

Java code to show action on x amount of presses?

I have an iOS app that I worked on some time ago, and the function it uses I like, and would like to somehow get it to work on some Android code I have.
At the top of my MainActivity I have
SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "nShownLobby";
on my onCreate I have
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
And I am calling this method
changeTextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
long nb_shown_lobby = PreferenceManager.getDefaultSharedPreferences(MainActivity.this).getLong("nShownLobby", 0);
++nb_shown_lobby;
if ((nb_shown_lobby % 20) == 0) {
this.turnAround();
}
int random = (int) (Math.random() * manyDifferentStrings.length);
if (random == oldVaue) {
random = (int) (Math.random() * manyDifferentStrings.length);
}
changingText.setText(manyDifferentStrings[random]);
oldVaue = random;
try {
mySound.start();
} catch (NullPointerException e) {
mySound = MediaPlayer.create(MainActivity.this, R.raw.sound);
}
}
private void turnAround() {
//Do something here
Log.i("Do Something ", "");
}
});
The intention is that after every 20 presses, the turnAround() method is called but it does not... It just gets ignored - I am guessing I have missed something?
**According to your question your code should be like this**
private SharedPreferences sharedpreferences;
private SharedPreferences.Editor editor;
private static final String MyPREFERENCES = "nShownLobby";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
editor = sharedpreferences.edit();
changeTextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
int nb_shown_lobby = sharedpreferences.getInt("nShownLobby", 0);
if ((nb_shown_lobby % 20) == 0) {
turnAround();
}
nb_shown_lobby += 1;
editor.putInt("nShownLobby", nb_shown_lobby);
editor.commit();
int random = (int) (Math.random() * manyDifferentStrings.length);
if (random == oldVaue) {
random = (int) (Math.random() * manyDifferentStrings.length);
}
changingText.setText(manyDifferentStrings[random]);
oldVaue = random;
try {
mySound.start();
} catch (NullPointerException e) {
mySound = MediaPlayer.create(MainActivity.this, R.raw.sound);
}
}
});
}
//created this in activity, not in the button onclick
private void turnAround() {
//Do something here
Log.i("Do Something ", "");
}

How to make the vibrate different according to the significant light value?

I want the app to vibrate accordingly to the light value detected. For example, when the value is higher then the vibration is stronger. But this code seems not working, anyone can help to see where is my mistake? It can detect the light value correctly and the vibration is working but the vibration is not vibrating according to the light value.
public class LightDetection extends AppCompatActivity {
TextView textLight, textOn, textOff;
Button btnStart, btnStop;
float x;
long ambientValue = 16;
long floor_delay = 500;
long ceiling_delay = 80;
long vibrate = 100;
long vibrate_delay;
Vibrator sensorVibrator;
SensorManager sensorManager;
Sensor sensor;
private Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_light_detection);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
textLight = (TextView) findViewById(R.id.textView);
textOn = (TextView) findViewById(R.id.textView2);
textOff = (TextView) findViewById(R.id.textView3);
btnStart = (Button) findViewById(R.id.button3);
btnStop = (Button) findViewById(R.id.button4);
final SensorEventListener lightListener = new SensorEventListener() {
public void onAccuracyChanged(Sensor sensor, int acc) {
}
#SuppressLint("SetTextI18n")
public void onSensorChanged(SensorEvent event) {
float x = event.values[0];
Log.i("IE LightDetect.", "Light value: " + x);
textLight.setText((int) x + " lux");
}
};
btnStart.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
public void onClick(View view) {
sensorManager.registerListener(lightListener, sensor,
SensorManager.SENSOR_DELAY_FASTEST);
handler.postDelayed(runnable, vibrate_delay);
textOn.setText("LIGHT DETECTION MODE: ON");
}
});
btnStop.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
public void onClick(View view) {
textOn.setText("LIGHT DETECTION MODE: OFF");
sensorManager.unregisterListener(lightListener);
sensorVibrator.cancel();
handler.removeCallbacks(runnable);
}
});
}
private Runnable runnable = new Runnable() {
#Override
public void run() {
/* do what you need to do */
long luxValue = (long) x;
//Correction Ratio - Ceiling Delay/Most Likely Max Lux
long ratio = 950 / 300;
if (luxValue < ambientValue) {
vibrate = 100;
vibrate_delay = floor_delay + (ratio * luxValue);
} else {
vibrate = 100;
vibrate_delay = floor_delay - (ratio * luxValue);
}
if (vibrate_delay < ceiling_delay) {
long[] pattern = {0, vibrate, ceiling_delay};
sensorVibrator.vibrate(pattern, 1);
} else {
long[] pattern = {0, vibrate, vibrate_delay};
sensorVibrator.vibrate(pattern, 1);
}
Log.i("IE LightDetect.", "Lux: " + luxValue);
handler.postDelayed(this, vibrate_delay);
}
};
}`
After getting the light value in onSensorChanged() you are not saving the value globally, there u r using float x = event.values[0] which is just creating a local variable inside the function, and not the global one..try ditching the float from there, use x = event.values[0] instead of float x = event.values[0]..the it will save the value in the global variable and that you will use where you calculating vibration..

shared preference editor mixing up values

in my text to speech style app I can set the speed and pitch of the voice, and also 2 variables for ultrasound pitch settings. If I set the speed and pitch and exit the settings menu everything is fine, The problem is that if I press the finish button and the frequency analyzer runs and sets the ultrasound variables the variables get saved in the preference editor in the wrong spot, causing the speed and pitch to be set at the ultrasound values, I have been trying for 2 days to fix it but nothing works, below is the relevant code, if you need more please ask, can anyone see what I'm doing wrong?
EDIT: here is an apk showing the problem, go to settings menu (from toolbar upper right) set the speed and pitch, press finish, close app, open app, go to settings and you will see the ridiculous values set as speed and pitch
Canine Remote apk
Relevant initialized variables at start of class:
public SharedPreferences appPreferences;
boolean settingUp=false;
int result = 0;
int remote = 0;
int settingLanguage=0;
private float progress = (float) 1.0;
private float progress2 = (float) 1.0;
private static final String LSTYLE = "usa";//language
private static final String MYPITCH = "1.0";//normal use voice pitch
private static final String MYSPEED = "1.0";//normal use voice speed
private static final String ULTRADOG = "1.0";//22000 +/- user pitch khz
private static final String ULTRACAT = "1.0";//48000 +/- user pitch khz
private static final String HUMANDOGCAT = "0";//human=0, dog=1, cat=2
private static final String REMOTE = "0";//speak through device=0, speak
//through remote bluetooth speaker=1
private TextView edit;
private TextView edit2;
private Button edit3;
private Button edit4;
private Button edit5;
private Button edit6;
private TextView edit7;
private ImageButton edit8;
private Button edit9;
private CheckBox ckultra;
private CheckBox cklocal;
private CheckBox ckultra2;
private SeekBar cpitch;
private SeekBar cspeed;
AudioRecord mAudioRecord;
int freq = 11025;
int Nb;
int N;
int running=0;
double FreqMin = 0;
double FreqMax = 2300;
int muestras = 1000;
double PI2n = 2 * Math.PI/muestras;
double FreqMuestras=freq/muestras;
int indMin = (int) (FreqMin/FreqMuestras);
int indMax = (int) (FreqMax/FreqMuestras);
double newFrequency = 170;
double freakMin=170;
double freakMax=170;
double mean=170;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_canine_start);
appPreferences = PreferenceManager.getDefaultSharedPreferences(this);
This button sets the pitch in the preference editor
edit3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Globals g = (Globals) getApplication();
SharedPreferences.Editor editor = appPreferences.edit();
float pitch = g.getData2();
if (pitch < 0.1) pitch = (float) 0.1;
editor.putFloat(MYPITCH, pitch);
editor.commit();
tts.setPitch(pitch);
}
});
This button sets the speed in the preference editor, also I've included the slider bars and check boxes codes here if you need to see them
edit4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Globals g = (Globals) getApplication();
SharedPreferences.Editor editor2 = appPreferences.edit();
float speed=g.getData3();
if (speed < 0.1) speed = (float) 0.1;
editor2.putFloat(MYSPEED, speed);
editor2.commit();
tts.setSpeechRate(speed);
}
});
//slider bars to get pitch and speed
cpitch.setProgress(1);
edit.setText("Adjust voice Pitch: " + cpitch.getProgress());
cpitch.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
Globals g = (Globals) getApplication();
#Override
public void onProgressChanged(SeekBar cpitch, int progresValue, boolean fromUser) {
progress = (float) (progresValue * 0.1);
edit.setText("Adjust voice pitch: " + progress);
}
#Override
public void onStartTrackingTouch(SeekBar cpitch) {
}
#Override
public void onStopTrackingTouch(SeekBar cpitch) {
edit.setText("Adjust voice pitch: " + progress);
g.setData2(progress);
}
});
cspeed.setProgress(1);
edit2.setText("Adjust voice speed: " + cspeed.getProgress());
cspeed.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
Globals g = (Globals) getApplication();
#Override
public void onProgressChanged(SeekBar cspeed, int progresValue2, boolean fromUser2) {
progress2 = (float) (progresValue2 * 0.1);
edit2.setText("Adjust voice speed: " + progress2);
}
#Override
public void onStartTrackingTouch(SeekBar cspeed) {
}
#Override
public void onStopTrackingTouch(SeekBar cspeed) {
edit2.setText("Adjust voice speed: " + progress2);
g.setData3(progress2);
}
});
}
//check boxes
class clicker implements CheckBox.OnCheckedChangeListener {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
SharedPreferences.Editor editor5 = appPreferences.edit();
if (isChecked) {
if (buttonView == ckultra) {
editor5.putInt(HUMANDOGCAT, 1).commit();
ckultra2.setChecked(false);
}
if (buttonView == ckultra2) {
editor5.putInt(HUMANDOGCAT, 2).commit();
ckultra.setChecked(false);
}
if (buttonView == cklocal) {
editor5.putInt(REMOTE, 1).commit();
}
}
if (!isChecked) {
if (buttonView == ckultra) {
editor5.putInt(HUMANDOGCAT, 0).commit();
}
if (buttonView == ckultra2) {
editor5.putInt(HUMANDOGCAT, 0).commit();
}
if (buttonView == cklocal) {
editor5.putInt(REMOTE, 0).commit();
}
}
}
}
This button is the start of the code causing the error
edit6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
edit7.setVisibility(View.VISIBLE);
edit8.setVisibility(View.VISIBLE);
edit9.setVisibility(View.VISIBLE);
edit.setVisibility(View.GONE);
edit2.setVisibility(View.GONE);
edit3.setVisibility(View.GONE);
edit4.setVisibility(View.GONE);
edit5.setVisibility(View.GONE);
edit6.setVisibility(View.GONE);
cpitch.setVisibility(View.GONE);
cspeed.setVisibility(View.GONE);
ckultra.setVisibility(View.GONE);
ckultra2.setVisibility(View.GONE);
cklocal.setVisibility(View.GONE);
speakIT("Completed.");
Spectrometer_Start();
}
});
//analyze pitch to set ultrasound variables
public void Spectrometer_Start() {
try {
Nb = AudioRecord.getMinBufferSize(freq, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT) * 4;
N = Nb * Byte.SIZE / Short.SIZE;
mAudioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, freq, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, Nb);
mAudioRecord.startRecording();
running=1;
analizer();
} catch (IllegalArgumentException i) {
}
}
This method saves the ultrasound settings in the wrong place in the preference editor
public void analizer() {
int a=10;
while(tts.isSpeaking())
{
a-=1;
if(a==0)
{
short[] data= new short[muestras];
try {
mAudioRecord.read(data, 0, muestras-1);
Dft(data);
} catch (Exception e) {
e.printStackTrace();
}
a=10;
}
}
mAudioRecord.stop();
mAudioRecord.release();
Globals g = (Globals) getApplication();
running=0;
mean=((freakMax-freakMin)*0.5)+freakMin;
float calcDog = (float) (22000 / mean);
float calcCat = (float) (48000 / mean);
g.setData4(calcDog);
g.setData5(calcCat);
SharedPreferences.Editor editor7 = appPreferences.edit();
editor7.putFloat(ULTRADOG, calcDog);
editor7.putFloat(ULTRACAT, calcCat);
editor7.commit();
}
public void Dft(short[] inreal) {
for (int k = indMin; k < indMax; k++)
{
float sumreal = 0;
float sumimag = 0;
float PI2kn= (float) (PI2n * k);
for (int t = 0; t < muestras; t++) {
double angle = t*PI2kn;
sumreal += inreal[t] * Math.cos(angle);
sumimag += inreal[t] * Math.sin(angle);
}
newFrequency = (Math.sqrt(sumreal * sumreal + sumimag * sumimag));
if (newFrequency < freakMin && newFrequency >= 85) {
freakMin = newFrequency;
}
if (newFrequency > freakMax && newFrequency <= 255) {
freakMax = newFrequency;
}
}
}
This button starts the speech entered, and receives the wrong values from the preference editor
edit9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String sendComands= edit7.getText().toString();
if (!sendComands.equals("") && settingLanguage == 0){
float NPITCH = appPreferences.getFloat(MYPITCH, (float) 1.0);
float NSPEED = appPreferences.getFloat(MYSPEED, (float) 1.0);
float UDOG = appPreferences.getFloat(ULTRADOG, (float) 1.0);
float UCAT = appPreferences.getFloat(ULTRACAT, (float) 1.0);
int HDC = appPreferences.getInt(HUMANDOGCAT, 0);
switch (HDC) {
case 0:
tts.setPitch(NPITCH);
break;
case 1:
tts.setPitch(UDOG);
break;
case 2:
tts.setPitch(UCAT);
break;
}
tts.setSpeechRate(NSPEED);
speakIT(sendComands);
edit7.setHint("Enter text to send");
settingUp=false;
}
if (settingLanguage == 1) {
countryC(sendComands);
settingLanguage=0;
edit7.setHint("Enter text to send");
edit9.setText("Send");
edit7.setVisibility(View.GONE);
edit9.setVisibility(View.GONE);
}
}
});
My settings menu in the toolbar with comment so you know which objects do what
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.canine_start, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Globals g = (Globals) getApplication();
int id = item.getItemId();
if (id == R.id.action_settings) {
edit.setVisibility(View.VISIBLE);//pitch slider text
edit2.setVisibility(View.VISIBLE);//speed slider text
edit3.setVisibility(View.VISIBLE);//button - set pitch
edit4.setVisibility(View.VISIBLE);//button - set speed
edit5.setVisibility(View.VISIBLE);//button - test speak
edit6.setVisibility(View.VISIBLE);//button - finished with settings
edit7.setVisibility(View.GONE);//edit text - text to speech
edit8.setVisibility(View.GONE);//image button - speech recognition start
edit9.setVisibility(View.GONE);//button - speak edit7 text
cpitch.setVisibility(View.VISIBLE);//slider - adjust voice pitch
cspeed.setVisibility(View.VISIBLE);//slider - adjust voice speed
ckultra.setVisibility(View.VISIBLE);//checkbox - ultrasound dog on/off
ckultra2.setVisibility(View.VISIBLE);//checkbox - ultrasound cat on/off
cklocal.setVisibility(View.VISIBLE);//checkbox - send to bluetooth/local device
settingUp=true;
return true;
}
Your are using invalid keys to stores your values in sharedPreferences:
These values are used as keys:
private static final String MYPITCH = "1.0";
private static final String MYSPEED = "1.0";
private static final String ULTRADOG = "1.0";
private static final String ULTRACAT = "1.0";
Here to store values
editor.putFloat(MYPITCH, pitch);
editor2.putFloat(MYSPEED, speed);
editor7.putFloat(ULTRADOG, calcDog);
editor7.putFloat(ULTRACAT, calcCat);
And here to get values
float NPITCH = appPreferences.getFloat(MYPITCH, (float) 1.0);
float NSPEED = appPreferences.getFloat(MYSPEED, (float) 1.0);
float UDOG = appPreferences.getFloat(ULTRADOG, (float) 1.0);
float UCAT = appPreferences.getFloat(ULTRACAT, (float) 1.0);
You should instead use unique and meaningful keys:
private static final String MYPITCH = "my_pitch";
private static final String MYSPEED = "my_speed";
private static final String ULTRADOG = "ultra_dog";
private static final String ULTRACAT = "ultra_cat";

Monitoring Voice in my android app

Iam making an android app which monitor voice in which when the voice loudness exceed a user defined threshold the app dial a specific number .
i done making voice monitoring and compared the highest value with the threshold then dialling the number .everything goes right except when the app returned after the call i find the monitoring isnt right , as the mic sensitivity is very week (measurement is very low ) i have to restart the app to obtain the right measurement , the second question here i make the comparison of the threshold and the last value of sound in the handler at the bottom , is this the right way ? thanks in advanceThis is the App image
Below is The Main activity
public class MainActivity extends AppCompatActivity {
private static final int sampleRate = 11025;
private static final int bufferSizeFactor = 10;
private Button Stop;
private ProgressBar On;
private Button Start;
private AudioRecord audio;
private int bufferSize;
private ProgressBar level;
private TextView textView;
volatile int threshold;
TextView testtextview;
private boolean clicked ;
private Handler handler = new Handler();
private int lastLevel = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
threshold = 20000;
//progressbar detect voice
level = (ProgressBar) findViewById(R.id.progressbar_level);
level.setMax(32676);
//text displaying progress par value
textView = (TextView) findViewById(R.id.textView1);
testtextview = (TextView) findViewById(R.id.textViewtest);
if (audio != null) {
audio.stop();
audio.release();
audio = null;
handler.removeCallbacks(update);
} else {
bufferSize = AudioRecord.getMinBufferSize(sampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT) * bufferSizeFactor;
audio = new AudioRecord(MediaRecorder.AudioSource.MIC, sampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize);
audio.startRecording();
Thread thread = new Thread(new Runnable() {
public void run() {
readAudioBuffer();
}
});
thread.setPriority(Thread.currentThread().getThreadGroup().getMaxPriority());
thread.start();
handler.removeCallbacks(update);
handler.postDelayed(update, 25);
}
//seekbar let user choose threshhold
SeekBar mSeekBar = (SeekBar) findViewById(R.id.seekBar);
//text displayin user choice
final TextView textViewuser = (TextView) findViewById(R.id.textView3);
mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
textViewuser.setText("" + i + "/32676");
threshold = i ;
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
Stop = (Button) findViewById(R.id.dummy_buttonstop);
On = (ProgressBar) findViewById(R.id.progressBar11);
Start = (Button) findViewById(R.id.dummy_button);
Start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Start.setVisibility(View.GONE);
On.setVisibility(View.VISIBLE);
clicked = true;
}
});
Stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Start.setVisibility(View.VISIBLE);
On.setVisibility(View.GONE);
clicked = false;
}
});
}
private void readAudioBuffer() {
try {
short[] buffer = new short[bufferSize];
int bufferReadResult;
do {
bufferReadResult = audio.read(buffer, 0, bufferSize);
for (int i = 0; i < bufferReadResult; i++) {
if (buffer[i] > lastLevel) {
lastLevel = buffer[i];
}
}
}
while (bufferReadResult > 0 && audio.getRecordingState() == AudioRecord.RECORDSTATE_RECORDING);
if (audio != null) {
audio.release();
audio = null;
handler.removeCallbacks(update);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private Runnable update = new Runnable() {
public void run() {
MainActivity.this.level.setProgress(lastLevel);
textView.setText(lastLevel + "/" + level.getMax());
if (clicked) {
if (lastLevel > threshold) {
clicked=false;
Start.setVisibility(View.VISIBLE);
On.setVisibility(View.GONE);
String url = "tel:01224271138";
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(url));
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
//recreate();
}
}
lastLevel *= .5;
handler.postAtTime(this, SystemClock.uptimeMillis() + 500);
}
};

Categories