[Q] How to trigger a onKeyShortCut event - Android Q&A, Help & Troubleshooting

I find that there is a function onKeyShortCut in every View Component, but when I read the SDK document, I find that the function can only be trigger by the function setShortcut in menuitem component, is there any other way to trigger this event, for example, through send a keyEvent.

Solution to the keyShortcut
cuibuaa said:
I find that there is a function onKeyShortCut in every View Component, but when I read the SDK document, I find that the function can only be trigger by the function setShortcut in menuitem component, is there any other way to trigger this event, for example, through send a keyEvent.
Click to expand...
Click to collapse
After I check the souce code of the android platform, I find that when a keyEvent happened, the event passed to ViewRoot before to the windows, and then the windows pass it to the child component in the, and finally to the Activity. From the code in ViewRootImpl.java, I find the condition to trigger this event.
if (event.getAction() == KeyEvent.ACTION_DOWN
&& event.isCtrlPressed()
&& event.getRepeatCount() == 0
&& !KeyEvent.isModifierKey(event.getKeyCode())) {
if (mView.dispatchKeyShortcutEvent(event)) {
finishInputEvent(q, true);
return;
}
}
It means if a KeyEvent includes Ctrl keycode, repeatCount = 0, and no other function keys, it will deliver it to the View component. So I make a KeyEvent like the following
KeyEvent keyevent_parse = new KeyEvent(System.currentTimeMillis(),System.currentTimeMillis(),KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_V,0,KeyEvent.META_CTRL_MASK);
Then it works, you can use this to release a parse function to any textView component.

Related

[Q] OnClickListener vs. android:OnClick

I'm looking at both a book and the beginning projects on developers.android.com and have a question. Google is utilizing the android:nClick to handle the click event which then points to a public method for execution....but the book is setting up click listeners by setting a View with the buttons ID and then executing the setOnClickListener. OnClickListenver has one method called OnClick which is then executed.
//book
public class MyGame extends Activity implements OnClickListener {
View continueButton = findViewById(R.id.continue_button);
continueButton.setOnClickListener(this);
View newButton = findViewById(R.id.new_button);
newButton.setOnClickListener(this);
View aboutButton = findViewById(R.id.about_button);
aboutButton.setOnClickListener(this);
View exitButton = findViewById(R.id.exit_button);
exitButton.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.about_button:
Intent i = new Intent(this, About.class);
startActivity(i);
break;
}
}
My question. Which is the better way to handle the Button Click? In looking at what google does in the XML, it seems a helluva lot cleaner....but curious on what the advantage is for the other way (and I cannot think of any). Search of the site didn't yield anything.
I dunno if the methods have advantages between them, however, I prefer the androidnClick method since the code looks clearer
You usually want to use the onClick method, as there is no benefit to implementing the OnClickListener (only more effort and possible performance loss).
If you want things like long clicks or other events, you will have to implement that (or define an inline listener), as there is no xml tag for those.
I think the OnClickListener is actually only there for consistency with these other classes

Ruby script

I am in an introduction to programming class and have some questions on a script I am working on. Anyone familiar with the Ruby
(.rb) language. Thanks
Sent from my Nexus 7 using xda app-developers app
Not really sure why this is in the Rezound QA...
I'm not familiar with Ruby (other than just looking at some code a few times)... but what's the issue you're having exactly?
lol I figured I would get that exact response, but it seemed like a good place to ask to be honest. I have this set of code here, Im not cut out for programming and was looking for help this is the pseudocode for the project I am working on.
MAXLINELENGTH = 40
codes = ['.-', '-...', '-.-.', '-..', '.', '..-.',
'--.', '....', '..', '.---', '-.-', '.-..',
'--', '-.', '---', '.--.', '--.-', '.-.',
'...', '-', '..-', '...-', '.--', '-..-',
'-.--', '--..','.----', '..---', '...--',
'....-', '.....', '-....', '--...', '---..',
'----.', '-----']
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
f1 = File.open("index.txt", "w")
f2 = File.open("index.txt", "r")
Initialize line_length = 0
while character = fin.getc
if index = chars.index(character.upcase)
code.getc
Print code to fout
Print " " to fout
line_length = line_length + code.length + 2
end
elsif character == " "
Print " " to. fout
line_length += code.lenght + 4
end
if line_length >= MAXLINELENGTH
Print new line character to fout.print "\n"
Reset line_length to 0
end
end
fout.close
fin.close
Basically the goal is to print letters and numbers to a documnet labeled idex.txt but the user input characters would be translated in morse code in the txt document
zkrp5108 said:
lol I figured I would get that exact response, but it seemed like a good place to ask to be honest. I have this set of code here, Im not cut out for programming and was looking for help this is the pseudocode for the project I am working on.
MAXLINELENGTH = 40
codes = ['.-', '-...', '-.-.', '-..', '.', '..-.',
'--.', '....', '..', '.---', '-.-', '.-..',
'--', '-.', '---', '.--.', '--.-', '.-.',
'...', '-', '..-', '...-', '.--', '-..-',
'-.--', '--..','.----', '..---', '...--',
'....-', '.....', '-....', '--...', '---..',
'----.', '-----']
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
f1 = File.open("index.txt", "w")
f2 = File.open("index.txt", "r")
Initialize line_length = 0
while character = fin.getc
if index = chars.index(character.upcase)
code.getc
Print code to fout
Print " " to fout
line_length = line_length + code.length + 2
end
elsif character == " "
Print " " to. fout
line_length += code.lenght + 4
end
if line_length >= MAXLINELENGTH
Print new line character to fout.print "\n"
Reset line_length to 0
end
end
fout.close
fin.close
Basically the goal is to print letters and numbers to a documnet labeled idex.txt but the user input characters would be translated in morse code in the txt document
Click to expand...
Click to collapse
So your taking input and converting to Morse code then logging it to a text document? Never tried that language but it looks similar to visual basic.
If so, I don't see a loop set up to parse through the input string. You will need to iterate through each character, then I'm assuming there is a separate class (or function?) that will return the Morse code for each character.
Sorry I've only ever used c++ and java
Sent from my ADR6425LVW using xda app-developers app
Squirrel1620 said:
So your taking input and converting to Morse code then logging it to a text document? Never tried that language but it looks similar to visual basic.
If so, I don't see a loop set up to parse through the input string. You will need to iterate through each character, then I'm assuming there is a separate class (or function?) that will return the Morse code for each character.
Sorry I've only ever used c++ and java
Sent from my ADR6425LVW using xda app-developers app
Click to expand...
Click to collapse
Yea Im really bad at this, I was super excited to learn it but its not going well. I cant think in a rules and order kinda thing, I'm just more free thinking I need to be able to change stuff to however I want. So I just don't understand what I am looking at lol.
zkrp5108 said:
Yea Im really bad at this, I was super excited to learn it but its not going well. I cant think in a rules and order kinda thing, I'm just more free thinking I need to be able to change stuff to however I want. So I just don't understand what I am looking at lol.
Click to expand...
Click to collapse
Well I'm self taught I guess it's just a personality thing lol. Basically think of coding like this : write this program : make a pb+j sandwich, literally write down EVERY step you need to do in order to make it... Kinda weird analogy, but depending on how deep you go that could end up being tens of thousands of lines of code.
So in your case write down on paper EVERY step you need to do to get morse code from the input and write it to a text file. That will be your pseudocode now you need to translate that into code. Remember Google is your friend when you need to find the syntax needed to do what you want.
Wish I had more free time and experience in ruby to help
Sent from my ADR6425LVW using xda app-developers app
Easiest thing to do, will be to loop through the entire input string and parse each letter at a time. Had to do a morse-code conversion program in several older languages (Pascal, Fortran, Ada, C, C++) for my Programming Languages course last semester. Pseudocode was something like:
Get input from user (or parse an input file).
Store input into a string (or a string array if multiple lines).
Loop through string and check each letter individually and look up what the morse-code equivalent is.
Store the morse code equivalent in a new string inside the loop.
When you hit the end of the string (end of the loop), save the morse string to a file.
In the loop, checking each individual letter, a case statement (or if else-if else's) will be the easiest (more typing, but easier logic).
So, for example, here's a C++ version that I wrote for my class last semester:
Code:
#include <cstdlib>
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
string search(char character);
int main()
{
string encryptionString = "";
string morseString = "";
cout << "Enter a sentence, containing only letters and blanks \nand ending with a period, to convert to morse code: " << endl;
getline(cin, encryptionString);
//remove ending period, if it exists
if(encryptionString[encryptionString.length() - 1] == '.')
{
encryptionString.erase(encryptionString.length() - 1);
}//if
for(int i = 0; i < encryptionString.length(); i++)
{
encryptionString[i] = toupper(encryptionString[i]);
}//for
int index = 0;
while(index < encryptionString.length())
{
if(encryptionString[index] != ' ' || encryptionString[index] != '\n')
{
cout << " ";
morseString = search(encryptionString[index]);
cout << morseString;
}
else
{
cout << endl;
morseString = "";
}
index++;
}//while
cin.ignore();
cout << "\n\nPress enter to exit...";
cin.get();
return 0;
}//main
string search(char character)
{
string returnString = "";
if(character >= 65 || character <= 90 )
{
switch(character)
{
case 'A':
returnString = ".-";
break;
case 'B':
returnString = "-...";
break;
case 'C':
returnString = "-.-.";
break;
case 'D':
returnString = "-..";
break;
case 'E':
returnString = ".";
break;
case 'F':
returnString = "..-.";
break;
case 'G':
returnString = "--.";
break;
case 'H':
returnString = "....";
break;
case 'I':
returnString = "..";
break;
case 'J':
returnString = ".---";
break;
case 'K':
returnString = "-.-";
break;
case 'L':
returnString = ".-..";
break;
case 'M':
returnString = "--";
break;
case 'N':
returnString = "-.";
break;
case 'O':
returnString = "---";
break;
case 'P':
returnString = ".--.";
break;
case 'Q':
returnString = "--.-";
break;
case 'R':
returnString = ".-.";
break;
case 'S':
returnString = "...";
break;
case 'T':
returnString = "-";
break;
case 'U':
returnString = "..-";
break;
case 'V':
returnString = "...-";
break;
case 'W':
returnString = ".--";
break;
case 'X':
returnString = "-..-";
break;
case 'Y':
returnString = "-.--";
break;
case 'Z':
returnString = "--..";
break;
}//switch
}//if
return returnString;
}//search
For you, you would instead print to a file instead of print to screen. You'll need to look up the exact syntax for Ruby, but should be easy.

[GUIDE] Customizing Sony W. Button behaviour

I recently got an SONY NWZ-F806 Walkman with Android. I bought it to listen to Spotify and everything works fine but the fact that you cannot control Spotify with the the dedicated W. button on the side of the device.
So I googled and found a solution where you had to redirect the W. button to the search button which was not satisfying to me. So I decided to investigate deeper into this and with a little help of adb and dumpsys I found the Intent that was fired when the W. button is pressed "com.sony.walkman.intent.action.WALKMAN_BUTTON". Than I found the service which was responsible for the default behavior "W.control".
So to redirect the W. button to Spotify I had to do the following things:
1) Disable the default W. behavior
To do this you simply have to deactivate the W.control service
Systemsettings > Apps > All > W.control > Disable
2) To listen to the W. button a BroadcastReceiver has to be implemented which receives to the Intent "com.sony.walkman.intent.action.WALKMAN_BUTTON" and sends a Intent to Spotify
AndroidManifest.xml
Code:
<application>
<receiver android:name=".WDotReceiver" >
<intent-filter>
<action android:name="com.sony.walkman.intent.action.WALKMAN_BUTTON" />
</intent-filter>
</receiver>
</application>
WDotReceiver.java
Code:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
public class WDotReceiver extends BroadcastReceiver {
private static final String KEY_EVENT_KEY = "android.intent.extra.KEY_EVENT";
private static final String SPOTIFY_PLAY_KEY = "com.spotify.mobile.android.ui.widget.PLAY";
private static final String SPOTIFY_NEXT_KEY = "com.spotify.mobile.android.ui.widget.NEXT";
@Override
public void onReceive(Context arg0, Intent arg1) {
Bundle extrasBundle = arg1.getExtras();
if(extrasBundle != null)
{
if(extrasBundle.containsKey(KEY_EVENT_KEY))
{
KeyEvent keyEvent = extrasBundle.getParcelable(KEY_EVENT_KEY);
if(keyEvent.getAction() == KeyEvent.ACTION_DOWN && keyEvent.getRepeatCount() == 0)
{
arg0.sendBroadcast(new Intent(SPOTIFY_PLAY_KEY));
}
else if(keyEvent.getAction() == KeyEvent.ACTION_DOWN && keyEvent.getRepeatCount() == 1)
{
arg0.sendBroadcast(new Intent(SPOTIFY_NEXT_KEY));
}
}
}
}
}
If you press the W. button for a short time a Play/Pause Intent is send and if you press the button longer Spotify will skip to the next track.
To me this increases the usability of the device tremendously.
Kind regards
Mathias
wrong forum bro

Need help with voice recognition application dev

I'm developing an augmentative communication application for use on Kindle Fire. I'm using Fire HD 6 as my test device. I'm working in Xamarin, C#.
I know there is a speech recognizer on the device as the microphone icon appears on the keyboard and I can use it to populate the search window. However, my andoid speech recognizer code is not working. I get the "recognizer not present" error. Here is the code that I'm working with:
public class VoiceRecognition : Activity
{
private static String TAG = "VoiceRecognition";
private const int VOICE_RECOGNITION_REQUEST_CODE = 1234;
private ListView mList;
public Handler mHandler;
private Spinner mSupportedLanguageView;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
mHandler = new Handler();
SetContentView(Resource.Layout.Main);
Button speakButton = FindViewById<Button>(Resource.Id.btnRecord);
// Check to see if a recognition activity is present
PackageManager pm = PackageManager;
IList<ResolveInfo> activities = pm.QueryIntentActivities(new Intent(RecognizerIntent.ActionRecognizeSpeech), 0);
if (activities.Count != 0)
speakButton.Click += speakButton_Click;
else
{
speakButton.Enabled = false;
speakButton.Text = "Recognizer not present";
}
}
Click to expand...
Click to collapse
This code is obviously not going to work, but I don't know where to go from here. How can I access the voice recognizer on this device?
Thanks!

Several Easy Steps to Integrate the Fundamental Capability SDK of Video Editor Kit

The launch of HMS Core Video Editor Kit 6.2.0 has brought two notable highlights: various AI-empowered capabilities and flexible integration methods. One method is to integrate the fundamental capability SDK, which is described below.
Preparations​For details, please check the official document.
Code Development​Configuring a Video Editing Project
1. Set the authentication information for your app through an API key or access token.
Use the setAccessToken method to set an access token when the app is started. The access token needs to be set only once.
Code:
MediaApplication.getInstance().setAccessToken("your access token");
Use the setApiKey method to set an API key when the app is started. The API key needs to be set only once.
Code:
MediaApplication.getInstance().setApiKey("your ApiKey");
2. Set a License ID.
This ID is used to manage your usage quotas, so ensure that the ID is unique.
Code:
MediaApplication.getInstance().setLicenseId("License ID");
3. Initialize the running environment for HuaweiVideoEditor.
When creating a video editing project, first create a HuaweiVideoEditor object and initialize its running environment. When exiting a video editing project, release the HuaweiVideoEditor object.
Create a HuaweiVideoEditor object.
Code:
HuaweiVideoEditor editor = HuaweiVideoEditor.create(getApplicationContext());
Specify the position for the preview area.
This area renders video images, which is implemented by creating SurfaceView in the fundamental capability SDK. Ensure that the preview area position on your app is specified before creating this area.
Code:
<LinearLayout
android:id="@+id/video_content_layout"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="@color/video_edit_main_bg_color"
android:gravity="center"
android:orientation="vertical" />
// Specify the preview area position.
LinearLayout mSdkPreviewContainer = view.findViewById(R.id.video_content_layout);
// Set the layout of the preview area.
editor.setDisplay(mSdkPreviewContainer);
Initialize the running environment. If the license verification fails, LicenseException will be thrown.
After the HuaweiVideoEditor object is created, it has not occupied any system resource. You need to manually set the time for initializing the running environment of the object. Then, necessary threads and timers will be created in the fundamental capability SDK.
Code:
try {
editor.initEnvironment();
} catch (LicenseException error) {
SmartLog.e(TAG, "initEnvironment failed: " + error.getErrorMsg());
finish();
return;
}
4. Add a video or image.
Create a video lane and add a video or image to the lane using the file path.
Code:
// Obtain the HVETimeLine object.
HVETimeLine timeline = editor.getTimeLine();
// Create a video lane.
HVEVideoLane videoLane = timeline.appendVideoLane();
// Add a video to the end of the video lane.
HVEVideoAsset videoAsset = videoLane.appendVideoAsset("test.mp4");
// Add an image to the end of the video lane.
HVEImageAsset imageAsset = videoLane.appendImageAsset("test.jpg");
5. Add audio.
Create an audio lane and add audio to the lane using the file path.
Code:
// Create an audio lane.
HVEAudioLane audioLane = timeline.appendAudioLane();
// Add an audio asset to the end of the audio lane.
HVEAudioAsset audioAsset = audioLane.appendAudioAsset("test.mp3");
6. Add a sticker and text.
Create a sticker lane and add a sticker and text to the lane. A sticker needs to be added using its file path, while the text needs to be added by specifying its content.
Code:
// Create a sticker lane.
HVEStickerLane stickerLane = timeline.appendStickerLane();
// Add a sticker to the end of the lane.
HVEStickerAsset stickerAsset = stickerLane.appendStickerAsset("test.png");
// Add text to the end of the lane.
HVEWordAsset wordAsset = stickerLane.appendWord("Input text",0,3000);
7. Add a special effect.
Special effects are classified into the external special effect and embedded special effect.
Add an external special effect to an effect lane. This special effect can be applied to multiple assets, and its duration can be adjusted.
Code:
// Create an effect lane.
HVEEffectLane effectLane = timeline.appendEffectLane();
// Create a color adjustment effect with a duration of 3000 ms. Add it to the 0 ms playback position of the lane.
HVEEffect effect = effectLane.appendEffect(new HVEEffect.Options(HVEEffect.EFFECT_COLORADJUST, "", ""), 0, 3000);
Add an embedded special effect to an asset. Such a special effect can be applied to a single asset. The special effect's duration is the same as that of the asset and cannot be adjusted.
Code:
// Create an embedded special effect of color adjustment.
HVEEffect effect = videoAsset.appendEffectUniqueOfType(new HVEEffect.Options(HVEEffect.EFFECT_COLORADJUST, "", ""), ADJUST);
8. Play a timeline.
To play a timeline, specify its start time and end time. The timeline will play from its start time to end time at a fixed frame rate, and the image and sound in the preview will play simultaneously. You can obtain the playback progress, playback pause, payback completion, and playback failure via the registered callback.
Code:
// Register the playback progress callback.
editor.setPlayCallback(callback);
// Play the complete timeline.
editor.playTimeLine(timeline.getStartTime(), timeline.getEndTime());
9. Export a video.
After the editing is complete, export a new video using the assets in the timeline via the export API. Set the export callback to listen to the export progress, export completion, or export failure, and specify the frame rate, resolution, and path for the video to be exported.
Code:
// Path for the video to be exported.
String outputPath =
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
+ File.separator + Constant.LOCAL_VIDEO_SAVE_PATH
+ File.separator + VideoExportActivity.getTime() + ".mp4";
// Resolution for the video to be exported.
HVEVideoProperty videoProperty = new HVEVideoProperty(1920, 1080);
// Export the video.
HVEExportManager.exportVideo(targetEditor, callback, videoProperty, outputPath);
Managing Materials
After allocating materials, use APIs provided in the on-cloud material management module to query and download a specified material. For details, please refer to the description in the official document.
Integrating an AI-Empowered Capability
The fundamental capability SDK of Video Editor Kit provides multiple AI-empowered capabilities including AI filter, track person, moving picture, and AI color, for integration into your app. For more details, please refer to the instruction in this document.
AI Filter
Lets users flexibly customize and apply a filter to their imported videos and images.
Code:
// Create an AI algorithm engine for AI filter.
HVEExclusiveFilter filterEngine = new HVEExclusiveFilter();
// Initialize the engine.
mFilterEngine.initExclusiveFilterEngine(new HVEAIInitialCallback() {
@Override
public void onProgress(int progress) {
// Initialization progress.
}
@Override
public void onSuccess() {
// The initialization is successful.
}
@Override
public void onError(int errorCode, String errorMessage) {
// The initialization failed.
}
});
// Create an AI filter of the extract type from an image, by specifying the image bitmap and filter name.
// The filter ID is returned. Using the ID, you can query all information about the filter in the database.
String effectId = mFilterEngine.createExclusiveEffect(bitmap, "AI filter 01");
// Add the filter for the first 3000 ms segment of the effect lane.
effectLane.appendEffect(new HVEEffect.Options(
HVEEffect.CUSTOM_FILTER + mSelectName, effectId, ""), 0, 3000);
Color Hair
Changes the hair color of one or more persons detected in the imported image, in just a tap. The color strength is adjustable.
Code:
// Initialize the AI algorithm for the color hair effect.
asset.initHairDyeingEngine(new HVEAIInitialCallback() {
@Override
public void onProgress(int progress) {
// Initialization progress.
}
@Override
public void onSuccess() {
// The initialization is successful.
}
@Override
public void onError(int errorCode, String errorMessage) {
// The initialization failed.
}
});
// Add the color hair effect by specifying a color and the default strength.
asset.addHairDyeingEffect(new HVEAIProcessCallback() {
@Override
public void onProgress(int progress) {
// Handling progress.
}
@Override
public void onSuccess() {
// The handling is successful.
}
@Override
public void onError(int errorCode, String errorMessage) {
// The handling failed.
}
}, colorPath, defaultStrength);
// Remove the color hair effect.
asset.removeHairDyeingEffect();
Moving Picture
Animates one or more persons in the imported image, so that they smile, nod, or more.
Code:
// Add the moving picture effect.
asset.addFaceReenactAIEffect(new HVEAIProcessCallback() {
@Override
public void onProgress(int progress) {
// Handling progress.
}
@Override
public void onSuccess() {
// The handling is successful.
}
@Override
public void onError(int errorCode, String errorMessage) {
// The handling failed.
}
});
// Remove the moving picture effect.
asset.removeFaceReenactAIEffect();
This article presents just a few features of Video Editor Kit. For more, check here.
To learn more, please visit:
>> HUAWEI Developers official website
>> Development Guide
>> Reddit to join developer discussions
>> GitHub to download the sample code
>> Stack Overflow to solve integration problems
Follow our official account for the latest HMS Core-related news and updates.

Categories

Resources