Android Java Implement KEYCODE_VOLUME_UP and DOWN to my code - java

I wonder how to implement KEYCODE_VOLUME_UP and DOWN to my code. So every time when I press the volume up or down key will simultaneously reflect on my Notification Volume Control app.
The method I want to implement is as follows which will make my own app volume up and down when the physical volume up and down button is pressed:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
audio.adjustStreamVolume(AudioManager.STREAM_MUSIC,
AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
audio.adjustStreamVolume(AudioManager.STREAM_MUSIC,
AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
return true;
default:
return false;
}
}
The code I want to implement to is:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
run();
}
public void run()
{
mgr=(AudioManager)getSystemService(Context.AUDIO_SERVICE);
final LayoutInflater inflater =
(LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);
final View ViewLayout = inflater.inflate(R.layout.activity_main,
(ViewGroup)findViewById(R.id.activity_main));
alarm=(SeekBar)ViewLayout.findViewById(R.id.alarm);
music=(SeekBar)ViewLayout.findViewById(R.id.music);
ring=(SeekBar)ViewLayout.findViewById(R.id.ring);
system=(SeekBar)ViewLayout.findViewById(R.id.system);
voice=(SeekBar)ViewLayout.findViewById(R.id.voice);
alarmVol=(TextView)ViewLayout.findViewById(R.id.alarmVol);
musicVol=(TextView)ViewLayout.findViewById(R.id.musicVol);
ringVol=(TextView)ViewLayout.findViewById(R.id.ringVol);
systemVol=(TextView)ViewLayout.findViewById(R.id.systemVol);
voiceVol=(TextView)ViewLayout.findViewById(R.id.voiceVol);
alertDialogBuilder = new AlertDialog.Builder(this);
//alertDialogBuilder.setIcon(R.mipmap.ic_launcher);
//alertDialogBuilder.setTitle("Volume Control");
alertDialogBuilder.setView(ViewLayout);
initBar(alarm, AudioManager.STREAM_ALARM, alarmVol);
initBar(music, AudioManager.STREAM_MUSIC, musicVol);
initBar(ring, AudioManager.STREAM_RING, ringVol);
initBar(system, AudioManager.STREAM_SYSTEM, systemVol);
initBar(voice, AudioManager.STREAM_VOICE_CALL, voiceVol);
alertDialogBuilder.create();
alertDialogBuilder.show();
}
private void initBar(SeekBar bar, final int stream, final TextView textView)
{
final float maxVolume=mgr.getStreamMaxVolume(stream);
float curVol = mgr.getStreamVolume((stream));
bar.setMax((int)maxVolume);
bar.setProgress((int)curVol);
bar.setKeyProgressIncrement(1);
textView.setText(String.valueOf((int)(curVol/maxVolume*100)));
bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar bar, int progress,
boolean fromUser) {
mgr.setStreamVolume(stream, progress,
AudioManager.FLAG_PLAY_SOUND);
textView.setText(String.valueOf((int)
((progress/maxVolume)*100)));
}
public void onStartTrackingTouch(SeekBar bar) {
}
public void onStopTrackingTouch(SeekBar bar) {
}
});
}
}

Related

Why Can't I See The Soft Keyboard When I Inflate A Layout With A WebView?

I have a donation option on my app in the menu. When the user taps on that an AlertDialog.Builder appears that will display a layout with a webviewer on it. The page loads just fine in the WebViewer in the AlertDialog. However, when the webpage loads and there is a editable text view on the webpage the keyboard will not popup to allow users to enter in their dollar amount. Here is what I tried...
AlertDialog.Builder adb = new AlertDialog.Builder(MainActivity.this);
adb.setIcon(R.drawable.ic_baseline_payment_32);
adb.setTitle("Tip Developer");
View v = getLayoutInflater().inflate(R.layout.tip_developer_layout, null);
WebView wv = v.findViewById(R.id.tip_donation_webViewer);
WebSettings ws = wv.getSettings();
ws.setJavaScriptEnabled(true);
wv.loadUrl("");
wv.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
}
public void onPageFinished(WebView view, String url) {
wv.requestFocusFromTouch();
wv.requestFocus(View.FOCUS_DOWN);
}
});
wv.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction())
{
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_UP:
if (!v.hasFocus())
{
v.requestFocus();
}
break;
}
return false;
}
});
adb.setPositiveButton("Close", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
adb.setView(v);
adb.create();
adb.show();
I appreciate the help!
Insert this code.
private void showSoftKeyBoard() {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
Then, implement it in OnCLick.
wv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showSoftKeyBoard();
}
});
Add this line in your EditText.
android:inputType="number"
And insert this code.
#Override
public void onResume() {
super.onResume();
wv.setFocusableInTouchMode(true);
wv.requestFocus();
}

Multiple seekbars - set listeneners more efficiently?

I have 12 seekbars in an activity. Each seekbar needs a listener. At the moment I am manually setting a listener for each seekbar, this doesnt seem particularly efficient.
Can anyone recommend a more efficient practice to set the seekbars???
Try something like this:
public class MainActivity extends AppCompatActivity {
SeekBar seekBar1;
SeekBar seekBar2;
SeekBar.OnSeekBarChangeListener mlistener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
seekBar1 = findViewById(R.id.seekBar_1);
seekBar2 = findViewById(R.id.seekBar_2);
mlistener = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
switch (seekBar.getId()) {
case R.id.seekBar_1:
//do something
break;
case R.id.seekBar_2:
//do something else
break;
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
};
seekBar1.setOnSeekBarChangeListener(mlistener);
seekBar2.setOnSeekBarChangeListener(mlistener);
}
If your SeekBars all require different interaction logic then obviously you will need to provide unique code to each of the objects. However, you can re-use listeners if each SeekBar is doing the same thing. For example:
public class SeekBarTest extends Activity{
private Context myContext;
public SeekBarTest(Context c){
myContext = c;
}
private void initialize(){
SeekBar seekbar1 = new SeekBar(myContext);
SeekBar seekbar2 = new SeekBar(myContext);
SeekBar seekbar3 = new SeekBar(myContext);
SeekBar.OnSeekBarChangeListener myListener = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
//logic
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
//logic
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
//logic
}
};
seekbar1.setOnSeekBarChangeListener(myListener);
seekbar2.setOnSeekBarChangeListener(myListener);
seekbar3.setOnSeekBarChangeListener(myListener);
}
}
Instead of creating switch in onProgressChanged method you can send variables to SeekBar initiating method.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_options);
SeekBar volBar = initiateSeekBar(R.id.volume,R.id.volumeValue,0,1,"%");
SeekBar playSpeedBar = initiateSeekBar(R.id.autoPlay,R.id.autoPlayValue,100, 100,"ms");
}
private SeekBar initiateSeekBar(int barId, int textId, final int min, final int step, final String unit) {
SeekBar bar = findViewById(barId);
final TextView text = findViewById(textId);
bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
int value = min + progress * step;
text.setText(value + " " + unit);
autoPlayDelayTime = value;
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
return bar;
}
You can just make a reference equality, like this:
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
seekBar?. let {
if (this.seekBar1 === it) {
...
}
if (this.seekBar2 === it) {
...
}}
...
}
and call outside:
seekBar1.setOnSeekBarChangeListener(this)
seekBar2.setOnSeekBarChangeListener(this)

How do I disable my Seekbar in Android with a Switch?

I want to disable my Seekbar and buttons with a switch which is Powerswitch
Here is a code snippet:
seekBar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
String sval = String.valueOf(i);
speakerVal.setText(sval);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
// button - Favorite Channel ABC
cabc = (Button) findViewById(R.id.buttonABC);
cabc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Set Favorite
curChannel.setText("007");
}
});
and here is my switch code:
final Switch switch1 = (Switch) findViewById(R.id.switch1);
switch1.setOnCheckedChangeListener(this);
more switch code:
public void onSwitchClicked(View view) {
final TextView PowerSwitch = (TextView) findViewById(R.id.PwrSwitchVal);
Switch sw = (Switch) view;
if (sw.isChecked()) {
PowerSwitch.setText("ON");
pwr = true;
} else {
PowerSwitch.setText("OFF");
pwr = false;
}
}
I know I can use the switch.isChecked(), but when I change the seekba1.setEnabled(false), I can't seem to get it to turn back on.
I haven't even tried to disable the buttons yet.
any help would be appreciated.
In your onSwitchClicked method, you should be calling seekbar.setEnabled in the if checked if-else statement. If checked seekbar.setEnabled(true) else seekbar.setEnabled(false)
try this.
switch1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton arg0,
boolean arg1) {
if (arg1) {
seekbar1.setEnabled(true);
}
else{
seekbar1.setEnabled(false);
}
}
});

Creating DialogFragment with EditText

I'm new to android, started it about a month ago, and now I'm trying to make a "Shopping List" app for the sake of practice. In this app I have a ListView, where user can insert items via EditText above that ListView. When user longClick on item, ContextMenu with "Edit", "Delete" and "Mark" fields appears. I have already made "Delete" button work, but I still have problems with "Edit" function. To make this function work I created DialogFragment class, so when user presses the "Edit" button, this DialogFragment appears. This DF has EditText field, where we enter data we want to change. Here is DialogFragment class code:
public class AlertEdit extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder bd = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
bd.setView(inflater.inflate(R.layout.alert, null))
.setTitle("Edit")
.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((MyActivity)getActivity()).doPositiveClick();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((MyActivity)getActivity()).doNegativeClick();
}
});
return bd.create();
}
as you can see, we have positive button here, which calls doPositiveClick method from MyActivity, which appears to be the main activity.
.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((MyActivity)getActivity()).doPositiveClick();
}
So, here is the MyActivity class code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
lw = (ListView) findViewById(R.id.listView);
edtxt = (EditText) findViewById(R.id.editText);
alertEd = (EditText) findViewById(R.id.alertEdit);
goods = new ArrayList<String>();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, goods);
lw.setAdapter(adapter);
lw.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v,
int position, long id) {
}
});
registerForContextMenu(lw);
edtxt.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction()== KeyEvent.ACTION_DOWN) {
if (keyCode == KeyEvent.KEYCODE_ENTER) {
goods.add(0, edtxt.getText().toString());
adapter.notifyDataSetChanged();
edtxt.setText("");
return true;
}
}
return false;
}
});
}
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo info){
super.onCreateContextMenu(menu, v, info);
getMenuInflater().inflate(R.menu.actions, menu);
}
public boolean onContextItemSelected(MenuItem item) {
position = (int) info.id;
switch (item.getItemId()) {
case R.id.cnt_mnu_delete:
goods.remove(position);
adapter.notifyDataSetChanged();
return true;
case R.id.cnt_mnu_edit:
}
return super.onContextItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void doPositiveClick()
{
}
public void doNegativeClick()
{
}
public void showDialog()
{
DialogFragment frag = new AlertEdit();
frag.show(getFragmentManager(), "edit");
}
}
My problem is that I have no idea how to create that Edit function. I tryied to use AdapterContextMenuInfo, but it works only in onContextItemSelected method, because it requires and Item to work with. Hope you help me and sorry for the possible lack of information, ask me any additional questions please.
P.S. I'm trying to make this dialog for almost two weeks already and I'm really frustrated because of that.
I'm using this method - it's simple and you may adapt it to your needs:
First of all make an interface to handle your result, for example:
public interface OnDialogResultListener {
public void onDialogResult(String result);
}
Then use your dialog with additional view, like this:
public void showDialogAndGetResult(final int title, final String message, final String initialText, final OnDialogResultListener listener) {
// additional View - use appropriate View to your needs:
final EditText editText = new EditText(this);
editText.setText(initialText);
new AlertDialog.Builder(MainActivity.this)//
.setTitle(title)//
.setMessage(message)//
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (listener != null) {
listener.onDialogResult(editText.getText().toString());
}
}
})//
.setNegativeButton(android.R.string.cancel, null)//
.setView(editText)//
.show();
}
At last implement this interface in your activity:
public class YourActivity Extends Activity implements OnDialogResultListener{
...
#Override
public void onDialogResult(String result) {
//do what you need
}
...
}
Edit:
You may replace EditText by any View, including Layouts.
Still you may use the same scheme to return result from your DialogFragment descendant - just pass OnDialogResultListener in constructor or initializing method. I would say AlertDialog is more lightweight and DialogFragment allows more control and you may use both according to your needs.

How to play audio continuously while orientation going to change in android

I have develop application like media player to use for playing audio file from source but issue when I am change the orientation portrait to landscape button and other widget not working and other that is when I am again change orientation landscape to portrait so same issue button and seek bar is not working
my code is here
public class Aarati_Activity extends Fragment
{
private ImageButton btnplay;
private SeekBar seekbar;
MediaPlayer mp;
private ImageButton btnstop;
private int finalTime = 0;
private int startTime = 0;
private int oneTimeOnly = 0;
Handler handler=new Handler();
public Aarati_Activity() {}
int audiocurrent;
int audiomax;
private int mp_progress;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_aarti_fragment, container, false);
btnplay=(ImageButton)v.findViewById(R.id.btnplay);
btnstop=(ImageButton)v.findViewById(R.id.btnstop);
seekbar=(SeekBar)v.findViewById(R.id.seekbar);
seekbar.setClickable(true);
seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
seekchange();
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
}
});
mp = MediaPlayer.create(getActivity(), R.raw.arti);
audiomax=mp.getDuration();
audiocurrent=mp.getCurrentPosition();
btnstop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mp.isPlaying())
{
mp.stop();
Toast.makeText(getActivity(), "Stop",Toast.LENGTH_LONG).show();
btnplay.setImageResource(R.drawable.ic_action_play);
try
{
mp.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
else
{
Toast.makeText(getActivity(),"Aarti Currently not playing",Toast.LENGTH_SHORT).show();
}
}
});
btnplay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mp.isPlaying())
{
mp.pause();
btnplay.setImageResource(R.drawable.ic_action_play);
Toast.makeText(getActivity(), "Pause",Toast.LENGTH_SHORT).show();
finalTime = mp.getDuration();
startTime = mp.getCurrentPosition();
if(oneTimeOnly == 0)
{
seekbar.setMax((int) finalTime);
oneTimeOnly = 1;
}
seekbar.setProgress((int)startTime);
handler.postDelayed(UpdateSongTime,100);
}
else
{ btnplay.setImageResource(R.drawable.ic_action_pause);
mp.start();
Toast.makeText(getActivity(), "Play",Toast.LENGTH_SHORT).show();
finalTime = mp.getDuration();
startTime = mp.getCurrentPosition();
if(oneTimeOnly == 0)
{
seekbar.setMax((int) finalTime);
oneTimeOnly = 1;
}
seekbar.setProgress((int)startTime);
handler.postDelayed(UpdateSongTime,100);
}
}
});
return v;
}
#SuppressLint("NewApi")
public void seekchange()
{
mp_progress=seekbar.getProgress();
mp.seekTo(mp_progress);
}
private Runnable UpdateSongTime = new Runnable()
{
public void run()
{
startTime = mp.getCurrentPosition();
seekbar.setProgress((int)startTime);
handler.postDelayed(this, 100);
}
};
}
You need to use Service to play song. It will allow you to play song even when app is in background
Tutorial
Basically, from the MVC (Model-View-Controller) viewpoint, an Activity is a Controller, the view hierarchy is the View, and the View and Controller get re-created each time the orientation changes. Meanwhile, song playing belongs to the Model.
Note that an activity has the methods onSaveInstanceState(Bundle) and onCreate(Bundle), and if the bundle passed to onCreate() is not null, it contains the information previously stored by onSaveInstanceState().
And there's also onRetainNonConfigurationInstance(). When the screen turns, the old activity is destroyed and a new activity is created, and these methods let the old activity pass important data to the new one.
Even after you create a service, you have to keep this MVC stuff in mind.

Categories

Resources