How do i detect if + or - buttons were pressed on iOS/Android?
I think it's helpful for iOS..
- (void)viewWillAppear:(BOOL)animated {
AVAudioSession* audioSession = [AVAudioSession sharedInstance];
[audioSession setActive:YES error:nil];
[audioSession addObserver:self
forKeyPath:#"outputVolume"
options:0
context:nil];
}
-(void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([keyPath isEqual:#"outputVolume"]) {
NSLog(#"volume changed");
}
}
And Android.
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
int action = event.getAction();
int keyCode = event.getKeyCode();
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
if (action == KeyEvent.ACTION_DOWN) {
//TODO
}
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
if (action == KeyEvent.ACTION_DOWN) {
//TODO
}
return true;
default:
return super.dispatchKeyEvent(event);
}
}
Related
I got stuck on a project; and unable to understand the error. Kindly help me on that. I am getting Case Expressions Must be Constant Expressions on my every R.id , I am sharing the code here.
I am getting this error on every Case R.id ; kindly suggest
public void onClick(View v) {
int currentBgColor = PreferencesUtils.getBgColor(this);
switch (v.getId()) {
case R.id.btn_home:
if (isShowBgSelect) {
hideBgSelector(false);
isShowBgSelect = false;
}
dismissMainCling(v);
toggle();
break;
case R.id.btn_bookmark:
if (isShowBgSelect) {
hideBgSelector(false);
isShowBgSelect = false;
}
boolean isBookmarked = false;
for (Bookmark bm : mBookmarkList) {
if (bm.partId == mCurrentPart && bm.chapId == mCurrentChap) {
isBookmarked = true;
break;
}
}
if (isBookmarked) {
showUnBookmarkDialog(mCurrentPart, mCurrentChap);
} else {
showSaveBookmarkDialog(mCurrentPart, mCurrentChap);
}
break;
case R.id.btn_bm_list:
if (isShowBgSelect) {
hideBgSelector(false);
isShowBgSelect = false;
}
// toggleSecondary();
break;
case R.id.btn_background:
if (!isShowBgSelect) {
showBgSelector();
isShowBgSelect = true;
} else {
hideBgSelector(true);
isShowBgSelect = false;
}
mBtnBgSelect.setEnabled(false);
mBtnBgSelect.setSelected(true);
break;
case R.id.btn_fullscreen:
if (isShowBgSelect) {
hideBgSelector(false);
isShowBgSelect = false;
}
if (isFullScreen) {
showController();
mFullScreenButton.setEnabled(false);
isFullScreen = false;
} else {
hideController();
isFullScreen = true;
}
break;
case R.id.btn_home_slidingmenu_left:
toggle();
break;
case R.id.btn_home_slidingmenu_right:
// toggleSecondary();
break;
case R.id.btn_bg_white:
if (isShowBgSelect) {
hideBgSelector(false);
isShowBgSelect = false;
}
if (currentBgColor != Constants.BG_COLOR_WHITE) {
PreferencesUtils.saveBgColor(this, Constants.BG_COLOR_WHITE);
loadPart(mCurrentPart, mCurrentChap);
}
break;
case R.id.btn_bg_khaki:
if (isShowBgSelect) {
hideBgSelector(false);
isShowBgSelect = false;
}
if (currentBgColor != Constants.BG_COLOR_KHAKI) {
PreferencesUtils.saveBgColor(this, Constants.BG_COLOR_KHAKI);
loadPart(mCurrentPart, mCurrentChap);
}
break;
case R.id.btn_bg_sepia:
if (isShowBgSelect) {
hideBgSelector(false);
isShowBgSelect = false;
}
if (currentBgColor != Constants.BG_COLOR_SEPIA) {
PreferencesUtils.saveBgColor(this, Constants.BG_COLOR_SEPIA);
loadPart(mCurrentPart, mCurrentChap);
}
break;
case R.id.btn_about:
showAboutDialog();
break;
case R.id.tv_contact_us:
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL, new String[] { getResources()
.getString(R.string.dialog_about_email) });
email.putExtra(Intent.EXTRA_SUBJECT,
getText(R.string.contact_prefix) + " "
+ getText(R.string.app_name));
email.setType("message/rfc822");
startActivity(Intent.createChooser(email,
getText(R.string.contact_chooser)));
break;
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int currentBgColor = PreferencesUtils.getBgColor(this);
switch (item.getItemId()) {
case android.R.id.home:
toggle();
return true;
case R.id.menu_bookmark:
boolean isBookmarked = false;
for (Bookmark bm : mBookmarkList) {
if (bm.partId == mCurrentPart && bm.chapId == mCurrentChap) {
isBookmarked = true;
break;
}
}
if (isBookmarked) {
showUnBookmarkDialog(mCurrentPart, mCurrentChap);
} else {
showSaveBookmarkDialog(mCurrentPart, mCurrentChap);
}
return true;
case R.id.menu_bookmarked_chap:
// toggleSecondary();
return true;
case R.id.menu_bg_white:
if (currentBgColor != Constants.BG_COLOR_WHITE) {
PreferencesUtils.saveBgColor(this, Constants.BG_COLOR_WHITE);
loadPart(mCurrentPart, mCurrentChap);
}
return true;
case R.id.menu_bg_khaki:
if (currentBgColor != Constants.BG_COLOR_KHAKI) {
PreferencesUtils.saveBgColor(this, Constants.BG_COLOR_KHAKI);
loadPart(mCurrentPart, mCurrentChap);
}
return true;
case R.id.menu_bg_sepia:
if (currentBgColor != Constants.BG_COLOR_SEPIA) {
PreferencesUtils.saveBgColor(this, Constants.BG_COLOR_SEPIA);
loadPart(mCurrentPart, mCurrentChap);
}
return true;
case R.id.menu_about:
showAboutDialog();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
if (isShowBgSelect) {
hideBgSelector(false);
isShowBgSelect = false;
}
return super.onPrepareOptionsMenu(menu);
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
int action = event.getAction();
int keyCode = event.getKeyCode();
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
if (action == KeyEvent.ACTION_UP) {
//TODO
}
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
if (action == KeyEvent.ACTION_DOWN) {
//TODO
}
return true;
default:
return super.dispatchKeyEvent(event);
}
}
This code is working when screen is on. But not when screen is locked. Is there a way to get the volume key event when the screen is locked?
The event only trigger when the screen is on..other wise root permission is needed.
Make a BroadcastReceiver extended class
public class YourBoardcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.e("get something", "i dont know what!!");
String intentAction = intent.getAction();
KeyEvent event = null;
if (Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
event = (KeyEvent) intent
.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
}
if (event == null) {
return;
}
int keycode = event.getKeyCode();
int action = event.getAction();
long eventtime = event.getEventTime();
if (keycode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE
|| keycode == KeyEvent.KEYCODE_HEADSETHOOK) {
if (action == KeyEvent.ACTION_DOWN) {
// Start your app here!
// ...
Log.e("event/////", "Trigerd");
if (isOrderedBroadcast()) {
abortBroadcast();
}
}
}
}
}
}
And in your Manifest :
<receiver android:name="YourBoardcastReceiver">
<intent-filter>
<action android:name="android.intent.action.SCREEN_ON" />
</intent-filter>
</receiver>
and Call it like this.
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
mRemoteControlResponder = new ComponentName(getPackageName(),
YourBoardcastReceiver.class.getName());
Here is the code i use for the forward and reverse
// Drive forward
forward_button.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if ((event.getAction() == MotionEvent.ACTION_DOWN) | (event.getAction() == MotionEvent.ACTION_MOVE)) {
forward_button.setPressed(true);
Arduino = (byte) (Arduino | 16);
write(Arduino);
return true;
}else if (event.getAction() == MotionEvent.ACTION_UP) {
forward_button.setPressed(false);
Arduino = (byte) (Arduino & 236);
write(Arduino);
return true;
}
forward_button.setPressed(false);
return false;
}
});
// Back up
reverse_button.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if ((event.getAction() == MotionEvent.ACTION_DOWN) | (event.getAction() == MotionEvent.ACTION_MOVE)) {
reverse_button.setPressed(true);
Arduino = (byte) (Arduino | 32);
write(Arduino);
return true;
}else if (event.getAction() == MotionEvent.ACTION_UP) {
reverse_button.setPressed(false);
Arduino = (byte) (Arduino & 220);
write(Arduino);
return true;
}
reverse_button.setPressed(false);
return false;
}
});
I am thinking of using the same way for the left and right function such as;
left_button.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if ((event.getAction() == MotionEvent.ACTION_DOWN) | (event.getAction() == MotionEvent.ACTION_MOVE)) {
left_button.setPressed(true);
Arduino = (byte) (Arduino | 8);
write(Arduino);
return true;
}else if (event.getAction() == MotionEvent.ACTION_UP) {
left_button.setPressed(false);
Arduino = (byte) (Arduino & 244);
write(Arduino);
return true;
}
left_button.setPressed(false);
return false;
}
});
Is this one way of doing it??
mLButton = (Button) findViewById(R.id.button_l);
mLButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Send a message using content of the edit text widget
String message = "D," + left + "," + stop + "\n";
sendMessage(message);
}
});
});
mRButton = (Button) findViewById(R.id.button_r);
mRButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Send a message using content of the edit text widget
String message = "D," + right + "," + stop + "\r\n";
sendMessage(message);
}
Here is one example.
i am doing an application that needs a special keyboard and i can get the text into a edit text by pressing the keys.
public class SecondActivity extends Activity implements
OnKeyboardActionListener, OnKeyListener {
private static final String TAG = SecondActivity.class.getName();
private EditText editText1, editText2, editText3;
private InputMethodManager imm;
private String mWordSeparators;
private StringBuilder mComposing = new StringBuilder();
private KeyboardView keyboardView;
private Keyboard keyboard;
private Keyboard miKeyboard;
private boolean mCapsLock;
private long mLastShiftTime;
private boolean mCompletionOn;
private long mMetaState;
private CompletionInfo[] mCompletions;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Button button3 = (Button) findViewById(R.id.button3);
button3.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
finish();
Log.d("cambio estado", "onDestroy");
}
});
Button button4 = (Button) findViewById(R.id.button4);
button4.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
finish();
Log.d("cambio estado", "onDestroy");
}
});
editText1 = (EditText) findViewById(R.id.editText1);
editText2 = (EditText) findViewById(R.id.editText2);
editText3 = (EditText) findViewById(R.id.editText3);
imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText1.getWindowToken(), 0);
imm.hideSoftInputFromWindow(editText2.getWindowToken(), 0);
imm.hideSoftInputFromWindow(editText3.getWindowToken(), 0);
mWordSeparators = getResources().getString(R.string.word_separators);
keyboardView = (KeyboardView) findViewById(R.id.keyboardView);
keyboard = new Keyboard(this, R.xml.qwerty);
miKeyboard = new Keyboard(this,R.xml.qwerty);
keyboardView.setKeyboard(keyboard);
keyboardView.setEnabled(true);
keyboardView.setPreviewEnabled(true);
keyboardView.setOnKeyListener(this);
keyboardView.setOnKeyboardActionListener(this);
}
public void onStartInput(EditorInfo attribute, boolean restarting) {
mComposing.setLength(0);
updateCandidates();
if (!restarting) {
mMetaState = 0;
}
mCompletionOn = false;
mCompletions = null;
switch (attribute.inputType & InputType.TYPE_MASK_CLASS) {
case InputType.TYPE_CLASS_NUMBER:
case InputType.TYPE_CLASS_DATETIME:
keyboard = miKeyboard;
break;
case InputType.TYPE_CLASS_PHONE:
keyboard = miKeyboard;
break;
case InputType.TYPE_CLASS_TEXT:
keyboard = miKeyboard;
updateShiftKeyState(attribute);
break;
default:
keyboard = miKeyboard;
updateShiftKeyState(attribute);
}
}
public void onDisplayCompletions(CompletionInfo[] completions) {
if (mCompletionOn) {
if (completions == null) {
return;
}
List<String> stringList = new ArrayList<String>();
for (int i = 0; i < completions.length; i++) {
CompletionInfo ci = completions[i];
if (ci != null) stringList.add(ci.getText().toString());
}
}
}
private boolean translateKeyDown(int keyCode, KeyEvent event) {
mMetaState = MetaKeyKeyListener.handleKeyDown(mMetaState,
keyCode, event);
int c = event.getUnicodeChar(MetaKeyKeyListener.getMetaState(mMetaState));
mMetaState = MetaKeyKeyListener.adjustMetaAfterKeypress(mMetaState);
InputConnection ic = getCurrentInputConnection();
if (c == 0 || ic == null) {
return false;
}
if ((c & KeyCharacterMap.COMBINING_ACCENT) != 0) {
c = c & KeyCharacterMap.COMBINING_ACCENT_MASK;
}
if (mComposing.length() > 0) {
char accent = mComposing.charAt(mComposing.length() -1 );
int composed = KeyEvent.getDeadChar(accent, c);
if (composed != 0) {
c = composed;
mComposing.setLength(mComposing.length()-1);
}
}
onKey(c, null);
return true;
}
private void hideDefaultKeyboard() {
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
private void handleShift() {
checkToggleCapsLock();
keyboardView.setShifted(mCapsLock || !keyboardView.isShifted());
}
private void checkToggleCapsLock() {
long now = System.currentTimeMillis();
if (mLastShiftTime + 800 > now) {
mCapsLock = !mCapsLock;
mLastShiftTime = 0;
} else {
mLastShiftTime = now;
}
}
private void updateCandidates() {
if (!mCompletionOn) {
if (mComposing.length() > 0) {
ArrayList<String> list = new ArrayList<String>();
list.add(mComposing.toString());
}
}
}
private void handleClose() {
commitTyped(getCurrentInputConnection());
keyboardView.closing();
}
private void handleCharacter(int primaryCode, int[] keyCodes) {
if (keyboardView.isShifted()) {
primaryCode = Character.toUpperCase(primaryCode);
}
else {
getCurrentInputConnection().commitText(
String.valueOf((char) primaryCode), 1);
}
}
public void onText(CharSequence text) {
Log.d(TAG, "onText? \"" + text + "\"");
InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
ic.beginBatchEdit();
if (mComposing.length() > 0) {
commitTyped(ic);
}
ic.commitText(text, 0);
ic.endBatchEdit();
updateShiftKeyState((EditorInfo) getCurrentInputEditorInfo());
}
private void updateShiftKeyState(EditorInfo attr) {
if (attr != null
&& keyboardView != null && keyboard == keyboardView.getKeyboard()) {
int caps = 0;
EditorInfo ei = (EditorInfo) getCurrentInputEditorInfo();
if (ei != null && ei.inputType != InputType.TYPE_NULL) {
caps = getCurrentInputConnection().getCursorCapsMode(attr.inputType);
}
keyboardView.setShifted(mCapsLock || caps != 0);
}}
private void commitTyped(InputConnection inputConnection) {
if (mComposing.length() > 0) {
inputConnection.commitText(mComposing, mComposing.length());
mComposing.setLength(0);
updateCandidates();
}
}
private String getWordSeparators() {
return mWordSeparators;
}
public boolean isWordSeparator(int code) {
String separators = getWordSeparators();
return separators.contains(String.valueOf((char)code));
}
private void handleBackspace() {
final int length = mComposing.length();
if (length > 1) {
mComposing.delete(length - 1, length);
getCurrentInputConnection().setComposingText(mComposing, 1);
updateCandidates();
} else if (length > 0) {
mComposing.setLength(0);
getCurrentInputConnection().commitText("", 0);
updateCandidates();
} else {
keyDownUp(KeyEvent.KEYCODE_DEL);
}
updateShiftKeyState(getCurrentInputEditorInfo());
}
private InputConnection getCurrentInputConnection() {
return getCurrentInputConnection();
}
private EditorInfo getCurrentInputEditorInfo() {
return getCurrentInputEditorInfo();
}
#Override
public void swipeUp() {
Log.d(TAG, "swipeUp");
}
#Override
public void swipeRight() {
Log.d(TAG, "swipeRight");
}
#Override
public void swipeLeft() {
Log.d(TAG, "swipeLeft");
handleBackspace();
}
#Override
public void swipeDown() {
Log.d(TAG, "swipeDown");
handleClose();
}
#Override
public void onRelease(int primaryCode) {
Log.d(TAG, "onRelease? primaryCode=" + primaryCode);
}
#Override
public void onPress(int primaryCode) {
Log.d(TAG, "onPress? primaryCode=" + primaryCode);
}
#Override
public void onKey(int primaryCode, int[] keyCodes) {
Log.d(TAG, "onKey? primaryCode=" + primaryCode);
int n1 = 0; // -1 count
for (int keyCode : keyCodes) {
if (keyCode == -1) {
n1++;
continue;
}
Log.v(TAG, "keyCode=" + keyCode);
}
Log.v(TAG, "keyCode=-1 *" + n1);
if (isWordSeparator(primaryCode)) {
if (mComposing.length() > 0) {
commitTyped(getCurrentInputConnection());
}
sendKey(primaryCode);
updateShiftKeyState(getCurrentInputEditorInfo());
} else if (primaryCode == Keyboard.KEYCODE_DELETE) {
handleBackspace();
} else if (primaryCode == Keyboard.KEYCODE_SHIFT) {
handleShift();
} else if (primaryCode == Keyboard.KEYCODE_CANCEL) {
handleClose();
} else if (primaryCode == Keyboard.KEYCODE_MODE_CHANGE
&& keyboardView != null) {
Keyboard current = keyboardView.getKeyboard();
keyboardView.setKeyboard(current);
} else {
handleCharacter(primaryCode, keyCodes);
}
}
private void sendKey(int keyCode) {
switch (keyCode) {
case '\n':
keyDownUp(KeyEvent.KEYCODE_ENTER);
break;
default:
if (keyCode >= '0' && keyCode <= '9') {
keyDownUp(keyCode - '0' + KeyEvent.KEYCODE_0);
} else {
getCurrentInputConnection().commitText(String.valueOf((char) keyCode), 1);
}
break;
}
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (event.getRepeatCount() == 0 && keyboardView != null) {
if (keyboardView.handleBack()) {
return true;
}
}
break;
case KeyEvent.KEYCODE_DEL:
if (mComposing.length() > 0) {
onKey(Keyboard.KEYCODE_DELETE, null);
return true;
}
break;
case KeyEvent.KEYCODE_ENTER:
return false;
default:
if (mCapsLock) {
if (keyCode == KeyEvent.KEYCODE_SPACE
&& (event.getMetaState()&KeyEvent.META_ALT_ON) != 0) {
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
ic.clearMetaKeyStates(KeyEvent.META_ALT_ON);
keyDownUp(KeyEvent.KEYCODE_A);
keyDownUp(KeyEvent.KEYCODE_N);
keyDownUp(KeyEvent.KEYCODE_D);
keyDownUp(KeyEvent.KEYCODE_R);
keyDownUp(KeyEvent.KEYCODE_O);
keyDownUp(KeyEvent.KEYCODE_I);
keyDownUp(KeyEvent.KEYCODE_D);
return true;
}
}
if (translateKeyDown(keyCode, event)) {
return true;
}
}
}
return super.onKeyDown(keyCode, event);
}
private void keyDownUp(int keyEventCode) {
getCurrentInputConnection().sendKeyEvent(
new KeyEvent(KeyEvent.ACTION_DOWN, keyEventCode));
getCurrentInputConnection().sendKeyEvent(
new KeyEvent(KeyEvent.ACTION_UP, keyEventCode));
}
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
hideDefaultKeyboard();
Log.d(TAG, "onKey? keyCode=" + keyCode);
return false;
}
}
In your Xml file, Inside the editText tag you find something like android:inputType attribute. you can specify different types of input types like textEmail, phoneNumber, textPassword.
There are so many types, if you specify the input type attribute, it will show custom keyboard according to input type,
If your editText input type is a phoneNumber, then it will show Num KeyPad
If your editText input type is a textPassword, then it will show Character Keypad
Like this, you can have more custom keypad / keyboard
For Password keypad,
<EditText android:id=..........
android:inputType="textPassword" />
For Numeric Keypad
<EditText android:id=..........
android:inputType="number" />
have you declared it in manifest like
<service
android:name="TamilSoftKeyboard"
android:permission="android.permission.BIND_INPUT_METHOD">
<intent-filter>
<action android:name="android.view.InputMethod" />
</intent-filter>
<meta-data
android:name="android.view.im"
android:resource="#xml/method" />
</service>
I'm trying to understand how to make a button that latches onto a value when it is pressed, when it's pressed again it unlatches.
My method for this is as follows:
boolean r1 = false;
boolean r2 = true;
private boolean flipFlop(boolean read, int i)
{
if(read == true)
{
if (r1 == true && r2 == false)
{
r1 = false;
r2 = true;
}
else if(r1 == false && r2 == true)
{
r1 = true;
r2 = false;
}
}
return r1;
}
flipFlop method is called under onTouch, like so:
public boolean onTouch(View view, MotionEvent motion)
{
boolean pressCheck = false;
switch(motion.getAction())
{
case MotionEvent.ACTION_UP:
{
pressCheck = flipFlop(view.isPressed(), 1);
textView.setText("State is: " + pressCheck);
}
case MotionEvent.ACTION_DOWN:
{
pressCheck = flipFlop(view.isPressed(), 1);
textView.setText("State is: " + pressCheck);
}
}
return false;
}
When clicking once, the state is set to false and doesn't change.
When double-clicking, it flipflops between the two states. Why is that?
Also, when I tried making it with an array to hold the states, it latched to true and Doesn't change when double-tapping:
private boolean[][] latch = {{false, false, false}, {true, true, true}};
public boolean flipFlop(boolean read, int i)
{
if(read == true)
{
if(latch[i][2] == true && latch[i][1] == false)
{
latch[i][1] = true;
latch[i][2] = false;
}
else if(latch[i][2] == false && latch[i][1] == true)
{
latch[i][1] = false;
latch[i][2] = true;
}
}
return latch[i][1];
}