issue dealing with random function. - Android Studio

Code:
public void random(View view){
int min = 0;
int max = 5;
int ran = Random.nextInt((max - min) + 1) + min;
TextView t = (TextView) findViewById(R.id.msg);
t.setText(ran);
}
screwing up on the random line giving error => Error25, 31) error: non-static method nextInt(int) cannot be referenced from a static context
====================================
Edit
====================================
redid it
Code:
public void random(View view){
Random rand = new Random();
int number = rand.nextInt(10)+1;
TextView t = (TextView) findViewById(R.id.msg);
t.setText(""+number);
}

Random is not based on the cpu clock, but the seed used can be based on the current time for example.
How it works
As anything that happens in a computer, the result of a calculation is deterministic and cannot be really random. Basically, the random function remembers the latest returned value, and calculates the new one starting from the old one, for example:
X(i) = (a*X(i-1) + b)mod where a, b and n are constants
so a (pseudo)random function actually returns a predictable sequence of numbers based on the first value. In C you can specify the first value (seed) with srand():
srand(time(NULL));
For example in this way you initialize the seed to the current number of seconds. But if you know the starting value, again the sequence is predictable.
Problems
This is not good for numerous reasons, mainly related to security: for example, if you have a web session identified by a random number given from the server to the user at login, and an attacker is able to predict it, this can be used to impersonate the real user.
Usually is the same with the other programming languages. The only way to get better random numbers, is to rely also on inputs given by the user, such as mouse movements, key press and so on. This gives more unpredictability to the generated value, and this is how OS number generators such as /dev/random work.

Related

fix multitouch?? or not??

MotionEvent http://android-developers.blogspot.com/?hl=en
The Android framework’s primary point of access for touch data is the android.view.MotionEvent class. Passed to your views through the onTouchEvent and onInterceptTouchEvent methods, MotionEvent contains data about “pointers,” or active touch points on the device’s screen. Through a MotionEvent you can obtain X/Y coordinates as well as size and pressure for each pointer. MotionEvent.getAction() returns a value describing what kind of motion event occurred.
One of the more common uses of touch input is letting the user drag an object around the screen. We can accomplish this in our View class from above by implementing onTouchEvent as follows:
@Override
public boolean onTouchEvent(MotionEvent ev) {
final int action = ev.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN: {
final float x = ev.getX();
final float y = ev.getY();
// Remember where we started
mLastTouchX = x;
mLastTouchY = y;
break;
}
case MotionEvent.ACTION_MOVE: {
final float x = ev.getX();
final float y = ev.getY();
// Calculate the distance moved
final float dx = x - mLastTouchX;
final float dy = y - mLastTouchY;
// Move the object
mPosX += dx;
mPosY += dy;
// Remember this touch position for the next move event
mLastTouchX = x;
mLastTouchY = y;
// Invalidate to request a redraw
invalidate();
break;
}
}
return true;
}
The code above has a bug on devices that support multiple pointers. While dragging the image around the screen, place a second finger on the touchscreen then lift the first finger. The image jumps! What’s happening? We’re calculating the distance to move the object based on the last known position of the default pointer. When the first finger is lifted, the second finger becomes the default pointer and we have a large delta between pointer positions which our code dutifully applies to the object’s location.
If all you want is info about a single pointer’s location, the methods MotionEvent.getX() and MotionEvent.getY() are all you need. MotionEvent was extended in Android 2.0 (Eclair) to report data about multiple pointers and new actions were added to describe multitouch events. MotionEvent.getPointerCount() returns the number of active pointers. getX and getY now accept an index to specify which pointer’s data to retrieve.
anyone know?
You don't have much code up there but...
"mLastTouchX = x;
mLastTouchY = y;"
I assume those are globals... and the fact is that both action down and action move use those at the same time if you use two fingers...
EX:
-finger down create mlasttouchx&y at lets says 0,0 and you move to 1,1 enabling action move to correct it...
-keep finger still and add second finger...
-second finger changes the SAME variables of the previous item
-lift first finger so on action up theres no update (since you have no action up)
I'm not sure HOW to fix this issue (I've never tried multitouch) but your code doesn't support it.
How about adding some toggle variables and add an action up so on release it updates the points OR try using pointers (up to 3 as far as i can see probably for multitouch)
http://developer.android.com/reference/android/view/MotionEvent.html

Java...HELP!

For homework, we're required to write code for a cash register. Basically what it does is it prints out a menu and asks the user for input. At the end it prints out the order along with the total.
The part I am having trouble with is how do I make something like this:
Code:
Hamburger Hamburger Hamburger
display as this:
Code:
(3) Hamburger
We're told to think in terms of parallel arrays, but seeing as I missed that class, I am a bit lost.
If wanted, I can put up what code I have.
Thanks in advance.
can you post all your code?
Here is what I have.
I haven't written anything in my code that would relate to the problem I am having because I do not know where to start.
Code:
import java.util.Scanner;
import java.util.ArrayList;
public class CashRegister{
public static void main(String[]args){
Scanner scan=new Scanner(System.in);
ArrayList<String> list=new ArrayList<String>();
Register reg=new Register();
int b;
do{
String [] item = new String[11];
item [0]="Hot Dog";
item [1]="Hamburger";
item [2]="Soda";
item [3]="Chips";
item [4]="Ice Cream";
item [5]="Shave Ice";
item [6]="Cookie";
item [7]="Plate Lunch";
item [8]="French Fries";
item [9]="Shake";
item [10]="Order Complete";
for (int a=0;a<item.length;a++){
System.out.println((a+1)+". "+item[a]);}
b=scan.nextInt();
if (b==1){
list.add(item[0]);
reg.add(2.50);}
if (b==2){
list.add(item[1]);
reg.add(3.00);}
if (b==3){
list.add(item[2]);
reg.add(1.25);}
if (b==4){
list.add(item[3]);
reg.add(1.50);}
if (b==5){
list.add(item[4]);
reg.add(2.00);}
if (b==6){
list.add(item[5]);
reg.add(2.00);}
if (b==7){
list.add(item[6]);
reg.add(1.00);}
if (b==8){
list.add(item[7]);
reg.add(5.00);}
if (b==9){
list.add(item[8]);
reg.add(2.50);}
if (b==10){
list.add(item[9]);
reg.add(3.00);}
}
while (b != 11);
System.out.println("");
System.out.println("Your order contains: ");
System.out.println(list);
System.out.print("Your order costs: $");
double f=reg.getTotal();
System.out.format("%.2f %n",f);
}}
class Register{
double total=0;
public void add (double b){
total=total+b;}
public double getTotal(){
return total;}
}
I looked into your code and I can see what you want to do. I came up with a way to do it, however, I don't think it will be an efficient code (I'm not really familiar with Java).
I'm sure someone with more knowledge with Java could help you with this.
If you don't mind, could you post what you came up with or maybe point me in the right direction? Thanks
Sent from 234 Elm Street
We're told to think in terms of parallel arrays, but seeing as I missed that class, I am a bit lost.
If wanted, I can put up what code I have.
Thanks in advance.
Click to expand...
Click to collapse
Woops! I haven't read that, here is the almost much more cleaner solution.
There are several things that could be done (checking for valid input for example, ...) but i think thats to much for now.
Code:
import java.util.ArrayList;
import java.util.Scanner;
public class CashRegister {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<String> order = new ArrayList<String>();
Register reg = new Register();
// init & declare the array outside the loop
String[] menu = new String[] { "Hot Dog", "Hamburger", "Soda", "Chips",
"Ice Cream", "Shave Ice", "Cookie", "Plate Lunch",
"French Fries", "Shake" };
double[] prices = new double[] { 2.50, 3.00, 1.25, 1.50, 2.00, 2.00,
1.00, 5.00, 2.50, 3.00 };
// every order contains a amount int
int[] amountOf = new int[10];
for (int a = 0; a < menu.length; a++) {
System.out.println((a) + ". " + menu[a]);
}
System.out.println("10. " + "Order Complete");
System.out.print("Please choose from the menu:");
int input;
do {
input = scan.nextInt();
if (input >= 0 && input <= 10) {
reg.add(prices[input]);
amountOf[input]++;
}
}
while (input != 11);
System.out.println("");
System.out.println("Your order contains: ");
// System.out.println(list);
// calculate the amount of items from the order
for (int singleItem = 0; singleItem < menu.length; singleItem++) {
for (int menuIndex = 0; menuIndex < order.size(); menuIndex++) {
if (order.get(menuIndex).equals(menu[singleItem])) {
amountOf[singleItem]++;
}
}
}
// print the receipt
for (int i = 0; i < amountOf.length; i++) {
if (amountOf[i] > 0) {
System.out.println("(" + amountOf[i] + ") " + menu[i]);
}
}
System.out.print("Your order costs: $");
double f = reg.getTotal();
System.out.format("%.2f %n", f);
}
}
class Register {
private double total = 0;
public void add(double b) {
total = total + b;
}
public double getTotal() {
return total;
}
}
Thanks for your help. Now I can rest until the next assignment...which is tonight.
slow_DC4 said:
Thanks for your help. Now I can rest until the next assignment...which is tonight.
Click to expand...
Click to collapse
You know where to ask
Hi, sadly, it's me again seeking for some help.
This is what we are supposed to do
Code:
In this assignment you will use the techniques you used in lab to create an interactive vending machine. You must use Arraylists to store the information about the items for sale in the machine. Use the class you created in Assignment 5 in your ArrayLists.
Only the first item in a slot can be sold.
Hint:
Declaring and ArrayList of ArrayLists
Where Type is your class:
ArrayList<ArrayList<Type>> array;
You must also add each ArrayList to the ArrayList
array.add(new ArrayList<Type>());
End Hint
All Methods listed should be public:
Items will follow the restrictions delineated in Assignment 5. (You should leverage the abilities built into that class)
You will create a VendingMachine class that has at least the following methods:
VendingMachine(int numSlots, int maxItems)
This constructor will set up the object so that numSlots is the number of slots the machine has. MaxItems will be the maximum number of items that can be placed in each slot.
void menu()
This method will print a list of the items available, their price and the slot it is in. Only the first item in a slot will be printed. If a slot is Empty “Empty” should be printed with $0.00 for the price. Will also print out the current amount held in the machine.
boolean load(int slotNum, String name, double price, int quantity)
This method will load items into the machine. slotNum will be the slot that the items will be placed in, name will be the name of the item in the machine and price the price. Quantity is the number of this item that should be added. If the quantity exceeds the current capacity of the slot it should add nothing to the slot and return false. If the loading is successful return true.
int capacity(int slotNum)
returns the number of spaces empty in the slot specified.
void insertMoney( double money)
Will increase the amount of money in the machine by the amount of money (will not do anything if money is negative)
double returnMoney()
Will set amount of money in the machine to 0 and return the amount that was in the machine.
boolean select(int slotNumber)
Attempts to purchase the item in the slotnumber selected it returns true if the sale was successful and false if it was not. For a successful sale the amount held in the machine must be greater than the selected item. There must also be a valid item to be sold (the slot is not empty). If the item is sold the amount in the machine should be decreased by the price of the item. The first items in the slot should be removed.
This is what I have:
Code:
import java.util.ArrayList;
class itemVend{
public String item;
public double price;
final double maxPrice=99.99;
public itemVend(String item, double price){
this.item=item;
this.price=price;
}
public String getItem(){
if (item.length()>20){
item=item.substring(0,20);
}
System.out.println(item);
return item;
}
public double getPrice(){
if (price>=100.00){
price=99.99;
}
String priceNormal=String.format("%.2f",price);
System.out.format("$%5s",priceNormal);
double nPrice=Double.valueOf(priceNormal);
return nPrice;
}
}
class VendingMachine{
int numSlots;
int maxItems;
int slotNum;
String name;
double price;
int quantity;
double total;
double money;
int [] NumSlot=new int[numSlots];
int [] SlotAdd=new int [maxItems];
ArrayList<ArrayList<VendingMachine>> VendM;
public VendingMachine(int numSlots, int maxItems){
this.numSlots=numSlots;
this.maxItems=maxItems;
}
/*
public void menu(){
for (int x=0;x<numSlots;x++){
System.out.print(NumSlot[x]+","+name+","+price);
}
}
*/
public boolean load (int slotNum, String name, double price,int quantity){
if (quantity<=maxItems){
this.slotNum=slotNum;
this.name=name;
this.price=price;
itemVend IV=new itemVend(name,price);
this.quantity=quantity;
return true;
}
else {
return false;
}
}
public int capacity (int slotNum){
int emptySpace=maxItems-quantity;
return emptySpace;
}
public void insertMoney (double money){
total=total+money;
}
public boolean select(int slotNum){
if ((money>price)){
total=total-price;
return true;
}
else {
return false;
}
}
}
It's not quite done yet, and I'm sure that I have a lot of errors, because I am getting a little frustrated. The parts that I am having the most difficulty with is the VendingMachine constructor and the printing of the menu. Also I don't understand how the hint applies.
I think I may have figured out the menu problem:
Code:
public void menu(){
for (int x=0;x<VendNumber.size();x++){
System.out.println("Slot number: "+VendNumber.get(x)+", Item Name: "+VendItemName.get(x)+", Item Price: $"+ItemPrice.get(x));
}
}
Assignment 5 refers to the itemVend class.
Thanks in advance.
I'll take a look at this at the weekend, maybe tomorrow.

[Q] How to save "game progress" in a clicker app

I am currently working on a clicker game and need to save and restore the Strings and ints between when i shut down the app and when i restore it again, instead of losing all progress. Any suggestions on how to accomplish this? @mmdeveloper10
Hello,
To store some strings and ints while closing your app:
inside onDestroy() method
(if you haven't implemented it yet, it is like onCreate() you just write: )
Code:
@Override
protected void onDestroy() {
super.onDestroy();
//Put the below code here
}
Code:
SharedPreferences prefss = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor ed = prefss.edit();
ed.putString("mystring", mystring);
ed.putInt("myint", myint);
ed.commit(); //or ed.apply(); if you want to write them and wait for the write to be completed
Now to read them:
inside onCreate() (after super):
Code:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
mystring = prefs.getString("mystring", defaultStringValueHere); //defaultStringValueHere is a String (whatever you like), for the default value if the preference "mystring" is not found
myint = prefs.getInt("myint", defaultIntValueHere);
where mystring is the String that you want to store
and myint is the int that you want to store.
You can store as many as you like strings and ints (But the more you store, the more time to write and read them all your app will take)
If you still need help feel free to ask
Not sure how to explain the problem so I have attached my whole main method in pictures. I don't think it is finding any saved preferences on onCreate() because if i change the default int value it only changes to that instead of what the value was before exiting the app. Any idea what could be the cause of this?
mmdeveloper10 said:
Hello,
To store some strings and ints while closing your app:
inside onDestroy() method
(if you haven't implemented it yet, it is like onCreate() you just write: )
Code:
@Override
protected void onDestroy() {
super.onDestroy();
//Put the below code here
}
Code:
SharedPreferences prefss = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor ed = prefss.edit();
ed.putString("mystring", mystring);
ed.putInt("myint", myint);
ed.commit(); //or ed.apply(); if you want to write them and wait for the write to be completed
Now to read them:
inside onCreate() (after super):
Code:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
mystring = prefs.getString("mystring", defaultStringValueHere); //defaultStringValueHere is a String (whatever you like), for the default value if the preference "mystring" is not found
myint = prefs.getInt("myint", defaultIntValueHere);
where mystring is the String that you want to store
and myint is the int that you want to store.
You can store as many as you like strings and ints (But the more you store, the more time to write and read them all your app will take)
If you still need help feel free to ask
Click to expand...
Click to collapse
Hello,
Your strings a, b, c, e, f, g, h, i, j, k are empty ( Am I right? ).
So it tried to find a preference with an empty keyname, and write a preference with an empty keyname, it failed.
You need to have a, b, c, e, f, g, h, i, j, k hold a String value (different for each variable)
e.g.
Code:
String a = "a";
String b = "b";
...
Hope it helps
Ok, I tried changing them all to real Strings like you said and still no progress. Anything else that could be the problem?
mmdeveloper10 said:
Hello,
Your strings a, b, c, e, f, g, h, i, j, k are empty ( Am I right? ).
So it tried to find a preference with an empty keyname, and write a preference with an empty keyname, it failed.
You need to have a, b, c, e, f, g, h, i, j, k hold a String value (different for each variable)
e.g.
Code:
String a = "a";
String b = "b";
...
Hope it helps
Click to expand...
Click to collapse
Sorry but the code seems good to me. For me it is working.
Are you setting anywhere else in your code these variables?
Try moving the int w,z,... above the onCreate method.
In what phone are you testing?
Which Android Version?
Is it a custom ROM?
Can you share the logcat to see if it reports anything?
I am testing on an htc one m8 running Android 5.0.1 with no roms and I don't think the variables are used anywhere else I'll send the logcat when I get home
Sent from my HTC6525LVW using XDA Free mobile app
OK I fixed the issue, it turns out that I was closing the app by going into multitasking vs pressing the back key and now it is working fine thanks a lot
Sent from my HTC6525LVW using XDA Free mobile app
Ok
dillenge said:
OK I fixed the issue, it turns out that I was closing the app by going into multitasking vs pressing the back key and now it is working fine thanks a lot
Sent from my HTC6525LVW using XDA Free mobile app
Click to expand...
Click to collapse
Hello again,
If you want to save your app's state also by going into multitasking (pausing the app), then place the code in the onPause and onResume, instead of onDestroy and onCreate, respectively, as shown below
Code:
@Override
protected void onPause() {
super.onPause();
SharedPreferences prefss = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor ed = prefss.edit();
ed.putString("mystring", mystring);
ed.putInt("myint", myint);
ed.commit(); //or ed.apply(); if you want to write them and wait for the write to be completed
}
Code:
@Override
protected void onResume() {
super.onResume();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
mystring = prefs.getString("mystring", defaultStringValueHere); //defaultStringValueHere is a String (whatever you like), for the default value if the preference "mystring" is not found
myint = prefs.getInt("myint", defaultIntValueHere);
//Restore game state here instead of onCreate (onResume is called after onCreate, so you need to call the related methods for your game to restore the state here)
}

How do you get the number of items in a spinner control

I am trying to use m_BTArrayAdapter.getCount()
However this function returns 0 regardless of what is in the spinner popup.
I found some doco on this function: http://developer.android.com/reference/android/widget/ArrayAdapter.html#getCount%28%29
"public int getCount ()"
That is - no description. So what does that mean? In android Studio this function is redundant?
There are no other functions that I can see that tell you how many items there are in an ArrayAdapter or in the spinner control itself.
Surely I don't have to resort to a counter in my BT listener function to keep count of how many items are added to the adapter????
Code:
void setupBTListener()
{
m_BTArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item);
final Spinner spinnerBluetooth = (Spinner)findViewById(id.spinner_bluetooth);
spinnerBluetooth.setAdapter(m_BTArrayAdapter);
Can anyone explain to me why m_BTArrayAdapter.getCount() returns non zero inside my listener function but zero in the code below?
Code:
m_BTArrayAdapter.clear();
if (m_BTAdapter.isDiscovering())
m_BTAdapter.cancelDiscovery();
m_BTAdapter.startDiscovery();
long longStart = System.currentTimeMillis(),
longTimer;
boolean bDone = false;
while (m_BTAdapter.isDiscovering() && !bDone)
{
longTimer = System.currentTimeMillis();
//bDone = (longTimer - longStart) < 5000;
}
bEnable = m_BTArrayAdapter.getCount() > 0;
spinnerBluetooth.setEnabled(bEnable);
buttonConnect.setEnabled(bEnable);
buttonSearch.setEnabled(true);

Module stops working as soon as I load a native library (Please help)

Hi,
First, a disclaimer.
I am a Java and xposed noob. My background is in embedded C development so I can get by with some simple Java code and thanks to the great tutorials online I have been able to put together an xposed module but I'm struggling with a problem that is beyond my abilities now and am reaching out to the community for help.
Next, the background.
I have an Android head unit in my car. There is an app that provides me with CarPlay functionality but none of the controls on the steering wheel work with the app. When I analysed the code I found that they handle all of their button inputs using proprietary methods that do not inject an event into any input streams. I wrote an xposed module to hook the button press methods and then inject a proper input into one of the event streams.
Initially I tried to use the command line 'input' command to do this but since it is a Java app and takes about 1s to load it was too slow. My only other option was to create a virtual device on an input stream that I could then use to inject keypresses through the hooked method. To create a virtual device I needed to write C code that my xposed module would be able to access through the JNI. Long story short, after some pain I was able to get the native library integrated into the project and compiling using the NDK.
Finally, the problem.
When I was using the module without the native library it worked but just with a large delay because of the time it takes to load the 'input' java app. I was able to see logs from the module in the logcat as I hooked the method and as I went through the various actions within the hook.
As soon as I introduce the native library though the entire xposed module just stops running completely. I do not get any logs from the module even though I have installed, activated and rebooted. It shows up in the xposed installer but it just does nothing. The funny thing is that this happens even if I make no reference whatsoever to any native functions within the library. All I need to do to kill the module is to build it with the System.loadlibrary line in the Main.java uncommented. As soon as I comment that piece of code out the module starts to hook the function and output logs again. Below is the code from the Main.Java that I am referring to. I am happy to make any manifest, C and gradle files available too. Looking for any ideas as to why the module dies completely as soon as I include this...
Code:
package projects.labs.spike.zlink_xposed_swc;
import de.robv.android.xposed.XposedBridge;
import static de.robv.android.xposed.XposedHelpers.findAndHookMethod;
import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.IXposedHookZygoteInit;
import de.robv.android.xposed.XSharedPreferences;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.callbacks.XC_LoadPackage;
import de.robv.android.xposed.XposedHelpers;
import android.app.AndroidAppHelper;
import android.content.Intent;
import android.os.Bundle;
import android.content.Context;
/* shellExec and rootExec methods */
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ByteArrayOutputStream;
import android.view.KeyEvent;
import android.media.AudioManager;
public class Main implements IXposedHookLoadPackage {
public static final String TAG = "ZLINK_XPOSED ";
public static void log(String message) {
XposedBridge.log("[" + TAG + "] " + message);
}
//public native int CreateVirtualDevice();
//public native int SendPrev();
@Override
public void handleLoadPackage(final XC_LoadPackage.LoadPackageParam lpparam) throws Throwable {
log("handleLoadPackage: Loaded app: " + lpparam.packageName);
if (lpparam.packageName.equals("com.syu.ms")) {
findAndHookMethod("module.main.HandlerMain", lpparam.classLoader, "mcuKeyRollLeft", new XC_MethodHook() {
@Override
protected void afterHookedMethod(XC_MethodHook.MethodHookParam param) throws Throwable {
// previous
log("PREVKEYHIT");
//rootExec("input keyevent 88");
log("EVENTSENT");
//Below was trying to use media keys which zlink never responded to...
/* Context context = (Context) AndroidAppHelper.currentApplication();
AudioManager mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PREVIOUS);
mAudioManager.dispatchMediaKeyEvent(event);
KeyEvent event2 = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_PREVIOUS);
mAudioManager.dispatchMediaKeyEvent(event2);*/
//Below is the failed broadcast intent method...
/*Context mcontext = (Context) AndroidAppHelper.currentApplication();
Intent i = new Intent("com.android.music.musicservicecommand");
i.putExtra("command", "pause");
mcontext.sendBroadcast(i);*/
}
});
}
}
public static String rootExec(String... strings) {
String res = "";
DataOutputStream outputStream = null;
InputStream response = null;
try {
Process su = Runtime.getRuntime().exec("su");
outputStream = new DataOutputStream(su.getOutputStream());
response = su.getInputStream();
for (String s : strings) {
s = s.trim();
outputStream.writeBytes(s + "\n");
outputStream.flush();
}
outputStream.writeBytes("exit\n");
outputStream.flush();
try {
su.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
res = readFully(response);
} catch (IOException e) {
e.printStackTrace();
} finally {
Closer.closeSilently(outputStream, response);
}
return res;
}
public static String readFully(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length = 0;
while ((length = is.read(buffer)) != -1) {
baos.write(buffer, 0, length);
}
return baos.toString("UTF-8");
}
[COLOR="Red"] static {
System.loadLibrary("native-lib");
}[/COLOR]
}
The issue with native library is quite strange and I cannot help with it as my experience with native libs is zero.
But maybe try a different method of injecting media key events.
Create a method:
Code:
void injectKey(int keyCode) {
try {
final long eventTime = SystemClock.uptimeMillis();
final InputManager inputManager = (InputManager)
mContext.getSystemService(Context.INPUT_SERVICE);
int flags = KeyEvent.FLAG_FROM_SYSTEM;
XposedHelpers.callMethod(inputManager, "injectInputEvent",
new KeyEvent(eventTime - 50, eventTime - 50, KeyEvent.ACTION_DOWN,
keyCode, 0, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0, flags,
InputDevice.SOURCE_KEYBOARD), 0);
XposedHelpers.callMethod(inputManager, "injectInputEvent",
new KeyEvent(eventTime - 50, eventTime - 25, KeyEvent.ACTION_UP,
keyCode, 0, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0, flags,
InputDevice.SOURCE_KEYBOARD), 0);
} catch (Throwable t) {
// something went wrong
XposedBridge.log(t.getMessage());
}
}
Then just do: injectKey(KeyEvent.KEYCODE_MEDIA_PREVIOUS);
And maybe try playing with different KeyEvent flags and attrs.
Thanks so much for this suggestion! Any idea if this injects at a java level or if it depends on there being a keyboard input device available on one of the /dev/input/eventX streams? The android device that I am using has no keyboard available on any of those input streams. Will give it a try nonetheless
C3C076 said:
The issue with native library is quite strange and I cannot help with it as my experience with native libs is zero.
But maybe try a different method of injecting media key events.
Create a method:
Code:
void injectKey(int keyCode) {
try {
final long eventTime = SystemClock.uptimeMillis();
final InputManager inputManager = (InputManager)
mContext.getSystemService(Context.INPUT_SERVICE);
int flags = KeyEvent.FLAG_FROM_SYSTEM;
XposedHelpers.callMethod(inputManager, "injectInputEvent",
new KeyEvent(eventTime - 50, eventTime - 50, KeyEvent.ACTION_DOWN,
keyCode, 0, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0, flags,
InputDevice.SOURCE_KEYBOARD), 0);
XposedHelpers.callMethod(inputManager, "injectInputEvent",
new KeyEvent(eventTime - 50, eventTime - 25, KeyEvent.ACTION_UP,
keyCode, 0, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0, flags,
InputDevice.SOURCE_KEYBOARD), 0);
} catch (Throwable t) {
// something went wrong
XposedBridge.log(t.getMessage());
}
}
Then just do: injectKey(KeyEvent.KEYCODE_MEDIA_PREVIOUS);
And maybe try playing with different KeyEvent flags and attrs.
Click to expand...
Click to collapse
looxonline said:
Thanks so much for this suggestion! Any idea if this injects at a java level or if it depends on there being a keyboard input device available on one of the /dev/input/eventX streams? The android device that I am using has no keyboard available on any of those input streams. Will give it a try nonetheless
Click to expand...
Click to collapse
Simply use whatever InputDevice that you think should work in your case.
The method basically calls this:
https://android.googlesource.com/pl.../android/hardware/input/InputManager.java#869
which is then propagated to Input Manager Service here:
https://android.googlesource.com/pl...oid/server/input/InputManagerService.java#598
which then calls nativeInjectInputEvent

Categories

Resources