Hi,
I believe the title says it all. I tried to find the solution here but without success. While Im satisfied with my Nexus 7 case, I found out that sometimes if I just close it and put the tablet into bag it fails to turn the screen off. So, Id prefer to do that manually.
Is there a software way to disable the magnetic sensor? I dont want to play tailor with my case ...
Just manually turn it off. Closing the case won't turn your screen back on...
If the problem is that as the tab shuffles around in your bag and the case cover opens just enough to turn it back on, that's a different issue. Then you'll need some type of band or something to put around it.
Sent from my Nexus 7 using Tapatalk 2
Thanks, that will do. :good: But is there really NO sw way to disable it? I dont like automatic functions just lying around ...
michalurban said:
Thanks, that will do. :good: But is there really NO sw way to disable it? I dont like automatic functions just lying around ...
Click to expand...
Click to collapse
Unless you find a way in the code to disable it or figure out how to physically remove it.
or... just get a case with out a magnet in it.
knitler said:
Unless you find a way in the code to disable it or figure out how to physically remove it.
or... just get a case with out a magnet in it.
Click to expand...
Click to collapse
Ive been hoping in someone else finding the way to disable it in the code. Anyway, I guess Ill get another case and see ... THX! :good:
michalurban said:
Ive been hoping in someone else finding the way to disable it in the code. Anyway, I guess Ill get another case and see ... THX! :good:
Click to expand...
Click to collapse
Until seeing it on youtube, I wasn't even aware of this feature. The amazing thing to me is the fact that the actual case sold for the N7 at the google store does not have this feature (ie. no magnet)......
Im afraid I took the matters into my own hands and solved my magnetic problem once and for all ... :laugh:
michalurban said:
Im afraid I took the matters into my own hands and solved my magnetic problem once and for all ... :laugh:
Click to expand...
Click to collapse
Your case isn't nearly as attractive now.
Seriously, I can't see how this was a real issue unless your case was designed badly. Example; some flip-around cases if not shielded will turn the N7 off when flipped around.
khaytsus said:
Your case isn't nearly as attractive now.
Seriously, I can't see how this was a real issue unless your case was designed badly. Example; some flip-around cases if not shielded will turn the N7 off when flipped around.
Click to expand...
Click to collapse
Well, small hole inside the case isnt a big deal for me. Anyway, the problem was that the case managed to turn the tablet off only when closed really good. And if closed, only a few milimeters (say 2) of movement of the front cover to the left made the case wake my N7. I couldnt really be sure what would the Thing do in my bag - but the case itself is good, co I kept it this way.
This can be done strictly via software. Here is a modified version of the kernel driver from drivers/input/lid.c that allows you to enable/disable this feature. By default, it acts normally. To disable the magnetic switch, do "echo 0 > /sys/module/lid/parameters/lid_enabled", or use any other app you want to write to that file. To enable it again, just write a non-zero value to the parameter. Ive only tested it on my nexus7, but it seems to work perfectly.
Code:
/*
* ASUS Lid driver.
*/
#include <linux/module.h>
#include <linux/err.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/input.h>
#include <linux/platform_device.h>
#include <linux/workqueue.h>
#include <linux/gpio_event.h>
#include <asm/gpio.h>
#include <../gpio-names.h>
#include "lid.h"
MODULE_DESCRIPTION(DRIVER_LID);
MODULE_LICENSE("GPL");
/*
* functions declaration
*/
static void lid_report_function(struct work_struct *dat);
static int lid_input_device_create(void);
static ssize_t show_lid_status(struct device *class, struct device_attribute *attr,char *buf);
/*
* global variable
*/
static unsigned int hall_sensor_gpio = TEGRA_GPIO_PS6;
static struct workqueue_struct *lid_wq;
static struct input_dev *lid_indev;
static struct platform_device *lid_dev; /* Device structure */
// to allow enabling/disabling the lid switch
static int lid_enabled = 1;
module_param( lid_enabled, int, 0644 );
static DEVICE_ATTR(lid_status, S_IWUSR | S_IRUGO, show_lid_status,NULL);
/* Attribute Descriptor */
static struct attribute *lid_attrs[] = {
&dev_attr_lid_status.attr,
NULL
};
/* Attribute group */
static struct attribute_group lid_attr_group = {
.attrs = lid_attrs,
};
static ssize_t show_lid_status(struct device *class,struct device_attribute *attr,char *buf)
{
return sprintf(buf, "%d\n", gpio_get_value(hall_sensor_gpio));
}
static irqreturn_t lid_interrupt_handler(int irq, void *dev_id){
if( lid_enabled )
{
int gpio = irq_to_gpio(irq);
if (gpio == hall_sensor_gpio){
LID_NOTICE("LID interrupt handler...gpio: %d..\n", gpio_get_value(hall_sensor_gpio));
queue_delayed_work(lid_wq, &lid_hall_sensor_work, 0);
}
}
else
{
printk( "lid: ignoring irq\n" );
}
return IRQ_HANDLED;
}
static int lid_irq_hall_sensor(void)
{
int rc = 0 ;
unsigned gpio = hall_sensor_gpio;
unsigned irq = gpio_to_irq(hall_sensor_gpio);
const char* label = "hall_sensor" ;
LID_INFO("gpio = %d, irq = %d\n", gpio, irq);
LID_INFO("GPIO = %d , state = %d\n", gpio, gpio_get_value(gpio));
tegra_gpio_enable(gpio);
rc = gpio_request(gpio, label);
if (rc) {
LID_ERR("gpio_request failed for input %d\n", gpio);
}
rc = gpio_direction_input(gpio) ;
if (rc) {
LID_ERR("gpio_direction_input failed for input %d\n", gpio);
goto err_gpio_direction_input_failed;
}
LID_INFO("GPIO = %d , state = %d\n", gpio, gpio_get_value(gpio));
rc = request_irq(irq, lid_interrupt_handler,IRQF_TRIGGER_RISING|IRQF_TRIGGER_FALLING, label, lid_indev);
if (rc < 0) {
LID_ERR("Could not register for %s interrupt, irq = %d, rc = %d\n", label, irq, rc);
rc = -EIO;
goto err_gpio_request_irq_fail ;
}
enable_irq_wake(irq);
LID_INFO("LID irq = %d, rc = %d\n", irq, rc);
return 0 ;
err_gpio_request_irq_fail :
gpio_free(gpio);
err_gpio_direction_input_failed:
return rc;
}
static void lid_report_function(struct work_struct *dat)
{
int value = 0;
if (lid_indev == NULL){
LID_ERR("LID input device doesn't exist\n");
return;
}
msleep(CONVERSION_TIME_MS);
value = gpio_get_value(hall_sensor_gpio);
if(value)
input_report_switch(lid_indev, SW_LID, 0);
else
input_report_switch(lid_indev, SW_LID, 1);
input_sync(lid_indev);
LID_NOTICE("SW_LID report value = %d\n", value);
}
static int lid_input_device_create(void){
int err = 0;
lid_indev = input_allocate_device();
if (!lid_indev) {
LID_ERR("lid_indev allocation fails\n");
err = -ENOMEM;
goto exit;
}
lid_indev->name = "lid_input";
lid_indev->phys = "/dev/input/lid_indev";
set_bit(EV_SW, lid_indev->evbit);
set_bit(SW_LID, lid_indev->swbit);
err = input_register_device(lid_indev);
if (err) {
LID_ERR("lid_indev registration fails\n");
goto exit_input_free;
}
return 0;
exit_input_free:
input_free_device(lid_indev);
lid_indev = NULL;
exit:
return err;
}
static int __init lid_init(void)
{
int err_code = 0;
printk(KERN_INFO "%s+ #####\n", __func__);
LID_NOTICE("start LID init.....\n");
lid_dev = platform_device_register_simple("LID", -1, NULL, 0);
if (!lid_dev){
printk ("LID_init: error\n");
return -ENOMEM;
}
sysfs_create_group((struct kobject*)&lid_dev->dev.kobj, &lid_attr_group);
err_code = lid_input_device_create();
if(err_code != 0)
return err_code;
lid_wq = create_singlethread_workqueue("lid_wq");
INIT_DELAYED_WORK_DEFERRABLE(&lid_hall_sensor_work, lid_report_function);
lid_irq_hall_sensor();
return 0;
}
static void __exit lid_exit(void)
{
input_unregister_device(lid_indev);
sysfs_remove_group(&lid_dev->dev.kobj, &lid_attr_group);
platform_device_unregister(lid_dev);
}
module_init(lid_init);
module_exit(lid_exit);
So how would one go about implementing this modified code? Personally, I can't believe that there is not a standard setting to enable/disable this feature, but it ROM developers and/or users can implement this modified code easily, that would be a big help!
Thanks.
Sent from my ASUS Transformer Pad TF700T using Tapatalk 2
jtrosky said:
So how would one go about implementing this modified code? Personally, I can't believe that there is not a standard setting to enable/disable this feature, but it ROM developers and/or users can implement this modified code easily, that would be a big help!
Thanks.
Click to expand...
Click to collapse
To disable the magnetic switch, do "echo 0 > /sys/module/lid/parameters/lid_enabled"
Click to expand...
Click to collapse
The code was for reference. EDIT: No it's not, I'm an idiot.
Not the way I read it. The modified code has to be built into a kernel to access the option file.
Sent from my Nexus 7 using xda app-developers app
Yes, this is one of the files that make up the kernel, with about 10 lines added to it. You would have to replace the file in the kernel source code, build the kernel, insert that kernel into a boot.img, and flash it to your tablet. If you can't manage all that, then you could pester the person who does make the kernel you're using to add it.
rmm200 said:
Not the way I read it. The modified code has to be built into a kernel to access the option file.
Click to expand...
Click to collapse
This is what I get for reading things too fast.. Ah well.
gianptune said:
This can be done strictly via software. Here is a modified version of the kernel driver from drivers/input/lid.c that allows you to enable/disable this feature. By default, it acts normally. To disable the magnetic switch, do "echo 0 > /sys/module/lid/parameters/lid_enabled", or use any other app you want to write to that file. To enable it again, just write a non-zero value to the parameter. Ive only tested it on my nexus7, but it seems to work perfectly.
Code:
/*
* ASUS Lid driver.
*/
#include <linux/module.h>
#include <linux/err.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/input.h>
#include <linux/platform_device.h>
#include <linux/workqueue.h>
#include <linux/gpio_event.h>
#include <asm/gpio.h>
#include <../gpio-names.h>
#include "lid.h"
MODULE_DESCRIPTION(DRIVER_LID);
MODULE_LICENSE("GPL");
/*
* functions declaration
*/
static void lid_report_function(struct work_struct *dat);
static int lid_input_device_create(void);
static ssize_t show_lid_status(struct device *class, struct device_attribute *attr,char *buf);
/*
* global variable
*/
static unsigned int hall_sensor_gpio = TEGRA_GPIO_PS6;
static struct workqueue_struct *lid_wq;
static struct input_dev *lid_indev;
static struct platform_device *lid_dev; /* Device structure */
// to allow enabling/disabling the lid switch
static int lid_enabled = 1;
module_param( lid_enabled, int, 0644 );
static DEVICE_ATTR(lid_status, S_IWUSR | S_IRUGO, show_lid_status,NULL);
/* Attribute Descriptor */
static struct attribute *lid_attrs[] = {
&dev_attr_lid_status.attr,
NULL
};
/* Attribute group */
static struct attribute_group lid_attr_group = {
.attrs = lid_attrs,
};
static ssize_t show_lid_status(struct device *class,struct device_attribute *attr,char *buf)
{
return sprintf(buf, "%d\n", gpio_get_value(hall_sensor_gpio));
}
static irqreturn_t lid_interrupt_handler(int irq, void *dev_id){
if( lid_enabled )
{
int gpio = irq_to_gpio(irq);
if (gpio == hall_sensor_gpio){
LID_NOTICE("LID interrupt handler...gpio: %d..\n", gpio_get_value(hall_sensor_gpio));
queue_delayed_work(lid_wq, &lid_hall_sensor_work, 0);
}
}
else
{
printk( "lid: ignoring irq\n" );
}
return IRQ_HANDLED;
}
static int lid_irq_hall_sensor(void)
{
int rc = 0 ;
unsigned gpio = hall_sensor_gpio;
unsigned irq = gpio_to_irq(hall_sensor_gpio);
const char* label = "hall_sensor" ;
LID_INFO("gpio = %d, irq = %d\n", gpio, irq);
LID_INFO("GPIO = %d , state = %d\n", gpio, gpio_get_value(gpio));
tegra_gpio_enable(gpio);
rc = gpio_request(gpio, label);
if (rc) {
LID_ERR("gpio_request failed for input %d\n", gpio);
}
rc = gpio_direction_input(gpio) ;
if (rc) {
LID_ERR("gpio_direction_input failed for input %d\n", gpio);
goto err_gpio_direction_input_failed;
}
LID_INFO("GPIO = %d , state = %d\n", gpio, gpio_get_value(gpio));
rc = request_irq(irq, lid_interrupt_handler,IRQF_TRIGGER_RISING|IRQF_TRIGGER_FALLING, label, lid_indev);
if (rc < 0) {
LID_ERR("Could not register for %s interrupt, irq = %d, rc = %d\n", label, irq, rc);
rc = -EIO;
goto err_gpio_request_irq_fail ;
}
enable_irq_wake(irq);
LID_INFO("LID irq = %d, rc = %d\n", irq, rc);
return 0 ;
err_gpio_request_irq_fail :
gpio_free(gpio);
err_gpio_direction_input_failed:
return rc;
}
static void lid_report_function(struct work_struct *dat)
{
int value = 0;
if (lid_indev == NULL){
LID_ERR("LID input device doesn't exist\n");
return;
}
msleep(CONVERSION_TIME_MS);
value = gpio_get_value(hall_sensor_gpio);
if(value)
input_report_switch(lid_indev, SW_LID, 0);
else
input_report_switch(lid_indev, SW_LID, 1);
input_sync(lid_indev);
LID_NOTICE("SW_LID report value = %d\n", value);
}
static int lid_input_device_create(void){
int err = 0;
lid_indev = input_allocate_device();
if (!lid_indev) {
LID_ERR("lid_indev allocation fails\n");
err = -ENOMEM;
goto exit;
}
lid_indev->name = "lid_input";
lid_indev->phys = "/dev/input/lid_indev";
set_bit(EV_SW, lid_indev->evbit);
set_bit(SW_LID, lid_indev->swbit);
err = input_register_device(lid_indev);
if (err) {
LID_ERR("lid_indev registration fails\n");
goto exit_input_free;
}
return 0;
exit_input_free:
input_free_device(lid_indev);
lid_indev = NULL;
exit:
return err;
}
static int __init lid_init(void)
{
int err_code = 0;
printk(KERN_INFO "%s+ #####\n", __func__);
LID_NOTICE("start LID init.....\n");
lid_dev = platform_device_register_simple("LID", -1, NULL, 0);
if (!lid_dev){
printk ("LID_init: error\n");
return -ENOMEM;
}
sysfs_create_group((struct kobject*)&lid_dev->dev.kobj, &lid_attr_group);
err_code = lid_input_device_create();
if(err_code != 0)
return err_code;
lid_wq = create_singlethread_workqueue("lid_wq");
INIT_DELAYED_WORK_DEFERRABLE(&lid_hall_sensor_work, lid_report_function);
lid_irq_hall_sensor();
return 0;
}
static void __exit lid_exit(void)
{
input_unregister_device(lid_indev);
sysfs_remove_group(&lid_dev->dev.kobj, &lid_attr_group);
platform_device_unregister(lid_dev);
}
module_init(lid_init);
module_exit(lid_exit);
Click to expand...
Click to collapse
im interested in trying this on the sprint GS4.
can you possibly be a little more detailed on what i need to do?
thank you very much.
In my opinion the best solution to this problem is two steps:
1) Remove any magnet in the case cover. Disables smart cover feature physically rather than software.
2) Use NFC tags with programs configured to control exactly the items needed, e.g. sleep mode, settings, wi-fi, etc.
This may require two to four NFC tags, one for each major scenario. These might be "deep sleep, battery save", "sleep with fast restore", "wake no communicate", "wake and communication", etc. You could put the tags on a strip of material along with color codes. Touch the tag to the NFC sensor and no messing around.
As others may notice, I attended the XDA dev conference. LOL
As I know all magnetic cases or stuffs are harmful for mobile phones or tablets...
By the way do you guys think that, can this little magnet in the case ، hurm n7 in the long term ?
Xposed Module
Somebody made a Xposed module for the Moto G that disables the magnetic lock.
It could work on the N7, but i dont have a smart cover to try.
http://forum.xda-developers.com/showthread.php?t=2621807
sasa31 said:
As I know all magnetic cases or stuffs are harmful for mobile phones or tablets...
By the way do you guys think that, can this little magnet in the case ، hurm n7 in the long term ?
Click to expand...
Click to collapse
I ordered my N7 during the IO in which it was announced. Been in a magnetic case since then, so about a year and a half. What do you "know" is harmful? A static magnetic field is unlikely to harm solid state electronics or affect their operation.
Sent from my SCH-I545 using Tapatalk
Related
I'm wondering if anyone can give any pointers...
I'm trying to wake my TyTN from it's slumber in c#... after a few hours research I found an example in the MSDN that will set my "Beep" program to run at a certain time buy using CeRunAppAtTime. The problem is that although it works ... if the phones sleeping the screen doesn't activate ... (cont below)
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using HowDoI.Examples;
namespace DemoRunAppAtTimeCS
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void menuTest_Click(object sender, EventArgs e)
{
DateTime startTime = DateTime.Now + new TimeSpan(0, 0, 30);
long fileStartTime = startTime.ToFileTime();
long localFileStartTime = 0;
Win32.FileTimeToLocalFileTime(ref fileStartTime, ref localFileStartTime);
SystemTime systemStartTime = new SystemTime();
Win32.FileTimeToSystemTime(ref localFileStartTime, systemStartTime);
Win32.CeRunAppAtTime(@"\Windows\Beep.exe", systemStartTime);
}
}
}
Not a problem ... I know the programs activating so I thought if I mess about with the BKL1: and set it to "on" using DevicePowerState my test app will activate and the screen and speaker will then kick into life.
The problem is that it activates ... the screen comes on and then starts flashing or locks on so you can't turn it off without a reset. The speaker doesn't activate at all..... Can anyone shed anylight?? I'm not bothered about the screen but would love the speaker to activate to I can play a alarm.
Cheers
Phil
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace DeviceApplication8
{
public partial class Form1 : Form
{
public Int32 sd;
public Form1()
{
InitializeComponent();
SetDevicePower("BKL1:", POWER_NAME, DevicePowerState.D1);
sd = 0;
}
private void timer1_Tick(object sender, EventArgs e)
{
sd = sd + 1;
textBox1.Text = sd.ToString();
Microsoft.VisualBasic.Interaction.Beep();
}
public enum DevicePowerState : int
{
Unspecified = -1,
D0 = 0, // Full On: full power, full functionality
D1, // Low Power On: fully functional at low power/performance
D2, // Standby: partially powered with automatic wake
D3, // Sleep: partially powered with device initiated wake
D4, // Off: unpowered
}
private const int POWER_NAME = 0x00000001;
[DllImport("coredll")]
private static extern int SetDevicePower(
string pvDevice,
int dwDeviceFlags,
DevicePowerState DeviceState);
}
}
It's late so I can't be arsed trying this, but it looks like you haven't PInvoked the API call properly...
Try this
Code:
[DllImport("coredll.dll", SetLastError = true)]
static extern int SetSystemPowerState(string psState, int StateFlags, int Options);
const int POWER_STATE_ON = 0x00010000;
const int POWER_STATE_OFF = 0x00020000;
const int POWER_STATE_SUSPEND = 0x00200000;
const int POWER_FORCE = 4096;
const int POWER_STATE_RESET = 0x00800000;
#endregion
internal static void PowerOn()
{
SetSystemPowerState(null, POWER_STATE_ON, POWER_FORCE);
}
P.S. Check PInvoke.net and MSDN On SetSystemPowerState for more info.
Ta
Dave
Cheers Dave,
I'll give it a try tomorrow ... got a bottle of plonk in me and busy cooking a fish finger sandwich!!
Cheers
Phil
You're a star Dave ... ... changed my test program as per your advice and it works a treat!!! It wakes up even when locked, screen active, speaker active.
Thanks again for your help Dave ... I spent 10 hours on it yesterday with no joy!! Below's the code so maybe it'll help someone else.
Cheers
Phil
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace DeviceApplication8
{
public partial class Form1 : Form
{
public Int32 sd;
public Form1()
{
InitializeComponent();
SetSystemPowerState(null, POWER_STATE_ON, POWER_FORCE);
sd = 0;
}
private void timer1_Tick(object sender, EventArgs e)
{
sd = sd + 1;
textBox1.Text = sd.ToString();
Microsoft.VisualBasic.Interaction.Beep();
}
[DllImport("coredll.dll", SetLastError = true)]
static extern int SetSystemPowerState(string psState, int StateFlags, int Options);
const int POWER_STATE_ON = 0x00010000;
const int POWER_STATE_OFF = 0x00020000;
const int POWER_STATE_SUSPEND = 0x00200000;
const int POWER_FORCE = 4096;
const int POWER_STATE_RESET = 0x00800000;
}
}
If anyone every wonders how ... if you've set an application to run at a certain time, you can cancel the request by setting the run date/time to null
Win32.CeRunAppAtTime(@"\Windows\Beep.exe", null);
Cheers
Phil
Okay here's the thing:
I have an assignment in Java class that's due in 1.5 hours and figured that this would be the best place to ask since you guys are (hopefully) good at this kind of stuff.
Here's the code:
/**
* Exercise 3.
*
* Complete the setBalances method below to set all accounts in an array to the specified value.
*
* The test methods should pass.
*
*/
public class AccountMethods {
public static void main(String[] args) {
Account[] accounts = {new Account(100, "joe"),
new Account(200, "jane"),
new Account(300, "jerry")};
testSetBalances(accounts, 50);
testBalanceNonNegative();
}
public static void setBalances(Account[] accounts, double value) {
double balance = 0;
for (int i = 0; i < accounts.length; i++) {
balance += accounts.getBalance();
}
}
public static boolean testSetBalances(Account[] accounts, double value) {
setBalances(accounts, value);
for (int i = 0; i < accounts.length; i++) {
if (accounts.getBalance() != value) {
System.out.println("testSetBalances fails on element " + i);
return false;
}
}
System.out.println("testSetBalances passes.");
return true;
}
public static boolean testBalanceNonNegative() {
Account a = new Account(100, "jim");
a.setBalance(-100);
if (a.getBalance() < 0) {
System.out.println("testBalanceNonNegtaive fails");
return false;
} else {
System.out.println("testBalanceNonNegative passes.");
return true;
}
}
}
The bold part is what I'm suppose to be working with, but I can't get it to pass in the testSetBalances method. I don't know if I'm explaining this right, but when I'm compiling the code, it's suppose to say:
testSetBalances passes
But instead, it's saying: testSetBalances fails on element 0
Don't worry about the other parts of the code because the assignment for that is done already.
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.
Dear People,
I´m working on a app to control my robot with bluetooth.
So i made a thread to handle the bluetooth device, and a handler to read the information in the Gui thread.
(See code below)
The problem is that i´m not able to print the information to the textview in the handler.
When i print somthing to the textview in de onCreate function, everythings works fine, but when i print something to the textview in the handler, nothing happens.
There are also no errors or something like that.
I know that the handler function is called, because the receive messages are printed well in the log.d.
I hope that there is anyone who can help me.
thanks in advance.
Tom
public class InteractionActivity extends Activity {
private ConnectThread mConnectThread;
private interface MessageConstants
{
public static final int MESSAGE_READ = 0;
public static final int MESSAGE_WRITE = 1;
public static final int MESSAGE_TOAST = 2;
}
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_interaction);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
BluetoothDevice device = getIntent().getExtras().getParcelable("btdevice");
((TextView) findViewById(R.id.textView5)).setText("Hallo"); // works fine, print correct to the screen
mConnectThread = new ConnectThread(device);
mConnectThread.start();
}
private final Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
byte[] writeBuf = (byte[]) msg.obj;
int begin = (int)msg.arg1;
int end = (int)msg.arg2;
String writeMessage = new String(writeBuf);
writeMessage = writeMessage.substring(begin, end);
((TextView) findViewById(R.id.textView5)).setText("Hallo1111"); //Nothing happens
Log.d(TAG, writeMessage); //is printed fine in the log
}
};
private class ConnectThread extends Thread {
etc ............
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