[Q][DEV] Xperia light sensor - Xperia Arc Q&A, Help & Troubleshooting

Code:
public class MainActivity extends Activity implements SensorEventListener{
final String tag = "myLogs";
SensorManager sm = null;
Sensor lightSensor;
float lightQuantity;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sm = (SensorManager) getSystemService(SENSOR_SERVICE);
lightSensor = sm.getDefaultSensor(Sensor.TYPE_LIGHT);
if(lightSensor == null)
Log.d(tag, "no sensor:(");
else
Log.d(tag, "GOT IT!");
}
@Override
protected void onResume() {
super.onResume();
sm.registerListener((SensorEventListener)this, lightSensor, SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onStop() {
sm.unregisterListener((SensorEventListener)this);
super.onStop();
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
Log.d(tag,"onAccuracyChanged: " + sensor.getType() + ", accuracy: " + accuracy);
}
public void onSensorChanged(SensorEvent event) {
lightQuantity = event.values[0];
Log.d(tag,"onSensorChanged: " + event.sensor.getType() + ", result: " + lightQuantity);
}
}
cant reach the light sensor stats with this code
"no sensor" message always. What am i doung wrong?

You're not doing anything wrong. The problem is that Xperia doesn't have the sensor implemented in a standard Android way through drivers.
There's only a proprietary implementation which can be used through reading the kernel variables as detailed below.
The path to your sensor is "/sys/class/leds/lcd-backlight/als/value"
You can read it with the following code:
Code:
InputStream is = new FileInputStream(sensorPath);
InputStreamReader ir = new InputStreamReader(is);
char[] buf = new char[20];
int siz = ir.read(buf, 0, 20);
if (siz > 0)
{
float sensor = Float.parseFloat(String.copyValueOf(buf, 0, siz).replaceAll(",", "."));
}
is.close();

thank u once more)

Related

Device Power Management in WM

Dear сolleagues and development guru!
I have some stopper in Power Management. I hope somebody will help me to understand.
Technologies: C#, .NET 3.5
The main point of application:
Make beep periodically.
Main problem is:
When PocketPC in active mode application running correct, but when PocketPC went to sleep mode it does not make a beep. As I understood speaker is turned off in sleep mode (like all other devices in PocketPC).
Question:
How can I turn on speaker in sleep mode?
Simply what I need is turn on speaker, make beep and back speaker to previous mode without wake up all device.
I tried code like this:
Code:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Media;
using System.Threading;
using System.Runtime.InteropServices;
namespace TestProject
{
static class Program
{
public const int POWER_NAME = 0x00000001;
public enum DevicePowerState : int
{
Unspecified = -1,
D0 = 0,
D1,
D2,
D3,
D4,
}
[DllImport("coredll.dll", SetLastError = true)]
public static extern int SetDevicePower(
string pvDevice,
int dwDeviceFlags,
DevicePowerState DeviceState
);
[DllImport("coredll.dll", SetLastError = true)]
public static extern IntPtr SetPowerRequirement(
string device,
DevicePowerState state,
uint deviceFlags,
IntPtr systemState,
ulong stateFlags
);
[DllImport("coredll.dll", SetLastError = true)]
public static extern int ReleasePowerRequirement(IntPtr handle);
[MTAThread]
static void Main()
{
MessageBox.Show("Application is running...", "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Asterisk,MessageBoxDefaultButton.Button1);
string deviceName = "WAV1:"; // speaker
for (; ; )
{
// set D0 power value
IntPtr handle = SetPowerRequirement(deviceName, DevicePowerState.D0, 1, IntPtr.Zero, 0);
// make a beep
SystemSounds.Beep.Play();
// set default power value
ReleasePowerRequirement(handle);
Thread.Sleep(10000);
}
}
}
}
And like this:
Code:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Media;
using System.Threading;
using System.Runtime.InteropServices;
namespace TestProject
{
static class Program
{
public const int POWER_NAME = 0x00000001;
public enum DevicePowerState : int
{
Unspecified = -1,
D0 = 0,
D1,
D2,
D3,
D4,
}
[DllImport("coredll.dll", SetLastError = true)]
public static extern int SetDevicePower(
string pvDevice,
int dwDeviceFlags,
DevicePowerState DeviceState
);
[DllImport("coredll.dll", SetLastError = true)]
public static extern IntPtr SetPowerRequirement(
string device,
DevicePowerState state,
uint deviceFlags,
IntPtr systemState,
ulong stateFlags
);
[DllImport("coredll.dll", SetLastError = true)]
public static extern int ReleasePowerRequirement(IntPtr handle);
[MTAThread]
static void Main()
{
MessageBox.Show("Application is running...", "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Asterisk,MessageBoxDefaultButton.Button1);
string deviceName = "WAV1:"; // speaker
int resDevicePowerOn = SetDevicePower(deviceName, POWER_NAME, DevicePowerState.D0);
for (; ; )
{
// make a beep
SystemSounds.Beep.Play();
Thread.Sleep(10000);
}
}
}
}
But any of these codes does not work - there are no beep in sleep mode.
Hi, I just happened to find an article from codeproject.
You may want to take a look at it.
http://www.codeproject.com/KB/mobile/WiMoPower1.aspx
I think what you need is cerunappattime.
It seems you are enabling the audio device to run in low-power mode, but you are not actually telling the CPU to keep running ("unattended mode").
Lookup PowerPolicyNotify, specifically PPN_UNATTENDEDMODE.
You may also need to periodically call SHIdleTimerResetEx and/or SystemIdleTimerReset to keep the device active in unattended mode or it will still truely suspend.
Prevent the system enter sleep mode
The system will stop all activitis when the system enter sleep mode.So you must prevent the system enter sleep mode.
The system sleep mode:
on -> unattended -> suspend
You can run:
on -> unattended -> resuming
my code:time up is system on
ex file:screenblack.rar
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;
using Microsoft.Win32;
namespace ScreenBlack
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//取得系統狀態 Get system state
[DllImport("Coredll.dll", SetLastError = true)]
public static extern int GetSystemPowerState(StringBuilder PowerState, int length, ref int Flags);
//設定系統電源狀態
[DllImport("Coredll.dll")]
public static extern int SetSystemPowerState(int psState, int StateFlags, int Options);
public const int POWER_STATE_ON = 0x12010000;
public const int NULL = 0;
public const int POWER_FORCE = 0x00001000;
private void Form1_Load(object sender, EventArgs e)
{
//設定 timer1 的設定值 0.5 秒 Set timer1 activie in 0.5 second
timer1.Interval = 500;
//啟動定時器 Start timer1
timer1.Enabled = true;
}
//宣告變數判斷是否有改變 suspend 0:沒有改變 1:有改變
int change = 0;
//宣告變數判斷執行秒數 10
int second = 20;
private void timer1_Tick(object sender, EventArgs e)
{
//設定其標為 0
int flags = 0;
//取得系統狀態名稱 on、suspend、unattended、resuming
StringBuilder stb = new StringBuilder(260);
//取得系統狀態 Get Current system state
GetSystemPowerState(stb, stb.Capacity, ref flags);
//判斷目前系統狀態
if (flags.ToString() == "4194304")
{
//改變 unattended 為 resuming Chang unattended into resuming
RegistryKey reg = Registry.LocalMachine.OpenSubKey(@"System\CurrentControlSet\Control\Power\State\Suspend", true);
reg.SetValue("Flags", "268435456", RegistryValueKind.DWord);
reg.Close();
//設定 reg 有改變
change = 1;
}
else if (flags.ToString() == "268435456")
{
//秒數減一
second--;
//判斷 second 是否等於零
if (second == 0)
{
//************
// your code
//************
//system on
SetSystemPowerState(NULL, POWER_STATE_ON, POWER_FORCE);
//設定秒數
second = 20;
}
}
else
{
//判斷是否有改變
if (change == 1)
{
//改變 unattended 為 resuming Chang unattended into resuming
RegistryKey reg = Registry.LocalMachine.OpenSubKey(@"System\CurrentControlSet\Control\Power\State\Suspend", true);
reg.SetValue("Flags", "2097152", RegistryValueKind.DWord);
reg.Close();
//設定 reg 有改變
change = 0;
//設定秒數
second = 20;
}
}
}
}
}

[Q] [.net cf]Loopback

Hey guys
I'm developing a little webserver for WM with the .net cf. it's easy and works fine as long as I don't try to access it from the same device it's running on. Nothing works: localhost,127.0.0.1 or even if I'm connected to a wifi network and I use this IP. Has anyone the solution for this issue?
ta you
a yeah I use the TcpListener-Class and I implemted some simple HTTP.
chabun
Code
Hey guys
Noone has an idea??
Here is the code which I use to setup the HttpListener and answer connections.
Code:
using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using StedySoft.SenseSDK;
using System.Threading;
using System.IO;
namespace WebServer
{
public partial class ServerForm : Form
{
IPEndPoint local;
TcpListener listener;
private volatile bool stop;
private volatile bool handled;
SensePanelItem state;
SensePanelTextboxItem response;
Thread serverThread;
public ServerForm(IPEndPoint local)
{
InitializeComponent();
this.local = local;
SetupList();
}
private void SetupList()
{
SensePanelDividerItem infos = new SensePanelDividerItem("infd", "Infos");
mainList.AddItem(infos);
mainList.AddItem(new SensePanelItem("Local-Endpoint") { PrimaryText = "Local-Endpoint", SecondaryText = local.ToString() });
mainList.AddItem(state = new SensePanelItem("Status") { PrimaryText = "Status", SecondaryText = "Wird gestartet..." });
mainList.AddItem(new SensePanelDividerItem("Response", "Response"));
mainList.AddItem(response = new SensePanelTextboxItem("body") { LabelText = "HTML-Body, welcher auf Requests gesendet wird.", Text = "<span style =\"color:red;font-size:30pt\">It works!!</span>" });
mainList.AddItem(new SensePanelDividerItem("Requests", "Requests"));
}
private void StartServer()
{
if (listener != null)
{
StopServer(true);
}
listener = new TcpListener(local.Port);
listener.Start();
serverThread = new Thread(listen);
serverThread.IsBackground = true;
stop = false;
serverThread.Start();
state.SecondaryText = "Gestartet...";
}
private void listen()
{
while (!stop)
{
while (listener.Pending())
{
handled = false;
Thread handlingThread = new Thread(handler);
handlingThread.Start();
while (!handled)
Thread.Sleep(50);
}
Thread.Sleep(200);
}
}
private void handler()
{
// Get the current connection
TcpClient client = (TcpClient)this.Invoke(new Func<TcpClient>(listener.AcceptTcpClient));
IPEndPoint remote = (IPEndPoint)client.Client.RemoteEndPoint;
handled = true;
NetworkStream stream = client.GetStream();
StreamReader reader = new StreamReader(stream);
ReadHttpRequest(reader);
StreamWriter writer = new StreamWriter(stream);
StringBuilder response = new StringBuilder(); ;
StartHTML(response);
response.AppendLine((string)this.Invoke(new Func<IPEndPoint, string>(GetResponse), remote));
EndHTML(response);
WriteHTTPResponse(writer, response.Length);
writer.WriteLine(response.ToString());
writer.Flush();
stream.Close();
client.Close();
}
private void WriteHTTPResponse(StreamWriter writer, int length)
{
writer.WriteLine("HTTP/1.1 200 OK");
writer.WriteLine("Date: " + DateTime.Now.ToString());
writer.WriteLine("Content-Length: "+ length.ToString());
writer.WriteLine("Connection: close");
writer.WriteLine("Content-Type: text/html; charset=utf-8");
writer.WriteLine();
}
private void ReadHttpRequest(StreamReader reader)
{
string buffer = null;
while (buffer != "")
buffer = reader.ReadLine();
}
int counter = 0;
private string GetResponse(IPEndPoint remote)
{
counter++;
mainList.AddItem(new SensePanelItem(counter.ToString()) { PrimaryText = remote.ToString(), SecondaryText = "Response:" + counter.ToString() });
return response.Text;
}
private void EndHTML(StringBuilder writer)
{
writer.AppendLine("</body>");
writer.AppendLine("</html>");
}
private void StartHTML(StringBuilder writer)
{
writer.AppendLine("<?xml version=\"1.0\"?>");
writer.AppendLine("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
writer.AppendLine("<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"de\" lang=\"de\">");
writer.AppendLine("<head>");
writer.AppendLine("<title>SmartWebServer</title>");
writer.AppendLine("<meta name=\"author\" content=\"Alexander Kayed\">");
writer.AppendLine("</head>");
writer.AppendLine("<body>");
}
private void StopServer(bool restart)
{
stop = true;
serverThread.Join();
if (restart)
StartServer();
}
private void ServerForm_Load(object sender, EventArgs e)
{
StartServer();
}
private void ServerForm_Closed(object sender, EventArgs e)
{
StopServer(false);
}
private void menuItem1_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
The user can choose the IPEndPoint(constructor), which the server will be bound to, in a prevouis form:
Code:
foreach (IPAddress ip in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
{
item = new SensePanelRadioItem(ip.ToString());
item.PrimaryText = ip.ToString();
item.SecondaryText = ip.AddressFamily.ToString();
item.Tag = ChoosedIp = ip;
item.OnStatusChanged += new SensePanelRadioItem.StatusEventHandler(item_OnStatusChanged);
IPList.AddItem(item);
}
So the user can choose between IPs I got from the DNS (e.g. 127.0.0.1, 192.168.0.1) and type a free (valid) port number (eg. 80, 8080, 8888)
Thanks for Your help!!
Still no answer...
I will post my experiences with this issue as long as I solved it - like small blog. Maybe some of you have the same problem...
I found another strange thing:
I'm able to connect to my Server from a TcpClient from another self-written App (own exectuable, different AppDomain):
Code:
void test()
{
Action<string> setText = new Action<string>(setTestText);
try
{
this.Invoke(setText, "Connect...");
TcpClient client = new TcpClient();
client.Connect(local);
this.Invoke(setText, "Connected...");
NetworkStream stream = client.GetStream();
StreamWriter writer = new StreamWriter(stream);
StreamReader reader = new StreamReader(stream);
writer.WriteLine();
writer.Flush();
this.Invoke(setText, "Read answer");
string buffer = reader.ReadToEnd();
this.Invoke(setText, "Test succeeded");
testing = false;
}
catch
{
this.Invoke(setText, "Test failed");
}
}
And I got a the right answer as well. It's strange, really strange that the browsers (IE,Opera etc.) can't loopback to it?

Need Developer Help - Form Refreshing

Hello,
i started to wrote my first WO7 applicatin.
I got following code:
Code:
private void BtnStart_Click(object sender, RoutedEventArgs e)
{
BtnStart.Content = "Calculating...";
for (int i = 0; i < Pb1.Maximum; i++)
{
...
}
...
}
My Problem is that the content of the Button doesn't change to "Calculating". Even my Progressbar:
Code:
private void PbStep()
{
if (Pb1.Value == Pb1.Maximum)
{
Pb1.Value = 0;
MessageBox.Show("Progressbar Overflow");
}
else
{
Pb1.Value = Pb1.Value + 1;
}
}
It is wrapped in s loop, and the bar begins with 0 and then switsch to 100%, but i cant see the steps between.
I think i need a refresh command. in visual basic it is Me.Update();.
I tried many codes from google, but nothing helped. I hope some1 can help me.
many thank
Try
Code:
Dispatcher.BeginInvoke(() =>
{
BtnStart.Content = "Calculating...";
});
i did already try this. but now when i press the button, while calculation nothing happens, and after the calculation is finished, the button content changes to "calculating" and don't changes back to "start".
so i put the code in both parts and now i got the same as before. the button did not change its content
Code:
private void BtnStart_Click(object sender, RoutedEventArgs e)
{
LblDuration.Text = "";
Dispatcher.BeginInvoke(() =>
{
BtnStart.Content = "Calculating...";
});
Pb1.Value = 0.0;
Pb1.Maximum = Max;
DateTime StartZeit = DateTime.Now;
for (int i = 0; i < Pb1.Maximum; i++)
{
PbStep();//Count Up PorgressBar
}
DateTime EndZeit = DateTime.Now;
TimeSpan GemesseneZeit = EndZeit - StartZeit;
LblDuration.Text = "Duration: " + GemesseneZeit.ToString();
Dispatcher.BeginInvoke(() =>
{
BtnStart.Content = "Start";
});
}
private void PbStep()
{
try
{
Pb1.Value = Pb1.Value + 1;
}
catch
{
Pb1.Value = 0;
MessageBox.Show("Progressbar Overflow");
}
}
But thank you for your help. any other ideas?
you really need to be looking at a background thread (background worker control may allow you do do this)
any tight loop like that will freeze the UI until the loop has finished
in the 'old days' a doevents within the loop itself would have been suffice but this is not good practice
HTH
Try this one, it does what you've trying to implement but using a correct way:
Code:
using System.Windows.Threading;
private void BtnStart_Click(object sender, RoutedEventArgs e)
{
BtnStart.Content = "Calculating...";
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromMilliseconds(100);
timer.Tick += (_, __) =>
{
// Here is replacement of your PbStep()
Pb1.Value++;
};
timer.Start();
}
i got it now this way:
Code:
private void BtnStart_Click(object sender, RoutedEventArgs e)
{
LblDuration.Text = "Duration: Calculating...";
BtnStart.Content = "Wait";
DateTime StartZeit = DateTime.Now;
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromMilliseconds(1);
timer.Tick += (_, __) =>
{
for (int i = 0; i < Pb1.Maximum; i++)
{
Pb1.Value++;
}
timer.Stop();
LblDuration.Text = "Duration: " + (DateTime.Now - StartZeit).ToString();
BtnStart.Content = "Start";
};
timer.Start();
}
It is half working. When i press Start, the button changes its content imediatly and after finishing the loop it return to its default content.
now i got 2 problems:
1. the progressbar isnt smooth jet
and the bigger one:
2. i wanted to create a benchmark programm an measure how long it takes to count a progressbar from 0 to 1million. now with the timer i dont have the real cpu speed because it is always waiting for the timer to tick. so the benchmark is sensless
@ cameronm:
I know the DoEvent command from other languages, but i wans able to use this in c#. i mainly programm in visual basic, cause this seems to be easy (In this case i would use Me.Update). I have heard from the Background worker, but never tried it. Maybe this can help.
I will do some google search and try to use the Background worker. I'll post again if i got new code
Thanks you all !
hello again
im now that far:
Code:
public partial class MainPage : PhoneApplicationPage
{
//Globale Variablen
private BackgroundWorker bw = new BackgroundWorker();
public int Max = 0;
// Konstruktor
public MainPage()
{
InitializeComponent();
Max = 500000;
bw.WorkerReportsProgress = true;
bw.WorkerSupportsCancellation = true;
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
}
private void BtnStart_Click(object sender, RoutedEventArgs e)
{
if (bw.IsBusy != true)
{
LblDuration.Text = "";
BtnStart.Content = "Calculating...";
Pb1.Value = 0.0;
Pb1.Maximum = Max;
bw.RunWorkerAsync();
}
}
private void BtnStop_Click(object sender, System.Windows.RoutedEventArgs e)
{
if (bw.WorkerSupportsCancellation == true)
{
bw.CancelAsync();
}
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
DateTime StartZeit = DateTime.Now;
//Failure by any deklarion
//like int i = 0 or BtnStart.Content = "Calculating...";
for (int i = 0; i < Pb1.Maximum; i++)
{
if ((worker.CancellationPending == true)) //Abbruchbedingung
{
e.Cancel = true;
break;
}
else //Progressbedingung
{
PbStep();//Count Up PorgressBar
}
}
DateTime EndZeit = DateTime.Now;
TimeSpan GemesseneZeit = EndZeit - StartZeit;
LblDuration.Text = "Duration: " + GemesseneZeit.ToString();
BtnStart.Content = "Start";
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if ((e.Cancelled == true))
{
this.LblStatus.Text = "Canceled!";
}
else if (!(e.Error == null))
{
this.LblStatus.Text = ("Error: " + e.Error.Message);
}
else
{
this.LblStatus.Text = "Done!";
}
}
private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.LblPercentage.Text = (e.ProgressPercentage.ToString() + "%");
}
private void PbStep()
{
try
{
Pb1.Value = Pb1.Value + 1;
}
catch
{
Pb1.Value = 0;
MessageBox.Show("Progressbar Overflow");
}
}
In the DoWork Function i receive an error when i try to set a variable like int i=0.
The Failure:UnauthorizedAccessException: Invalid cross-thread access
i followed this instruction: http://msdn.microsoft.com/en-us/library/cc221403(v=vs.95).aspx
but there they did the same. why did i have the error?
win98 said:
The Failure:UnauthorizedAccessException: Invalid cross-thread access
why did i have the error?
Click to expand...
Click to collapse
The exception you've got show exactly what's wrong: you are trying to access GUI thread variables from another (BackgroundWorker) thread.
Use Dispatcher.Invoke as I recommended to you a few posts above.
thank you sensboston. id dont understand why, because i just have one bgworker, but now it works
Code:
private void BtnStart_Click(object sender, RoutedEventArgs e)
{
if (bw.IsBusy != true)
{
LblDuration.Text = "";
BtnStart.Content = "Calculating...";
Pb1.Value = 0.0;
Pb1.Maximum = Max;
bw.RunWorkerAsync();
}
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
DateTime StartZeit = DateTime.Now;
Dispatcher.BeginInvoke(() =>
{
LblDuration.Text = "";
BtnStart.Content = "Calculating...";
for (int i = 0; i < Pb1.Maximum; i++)
{
if ((worker.CancellationPending == true)) //Abbruchbedingung
{
e.Cancel = true;
break;
}
else //Progressbedingung
{
Pb1.Value = Pb1.Value + 1;
//PbStep();
}
}
DateTime EndZeit = DateTime.Now;
TimeSpan GemesseneZeit = EndZeit - StartZeit;
LblDuration.Text = "Duration: " + GemesseneZeit.ToString();
BtnStart.Content = "Start";
});
}
private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.LblPercentage.Text = (e.ProgressPercentage.ToString() + "%");
}
Just my progressbar isnt running fluently. still just 0% (before calc) or 100% (after calc) and no steps between
win98 said:
Just my progressbar isnt running fluently. still just 0% (before calc) or 100% (after calc) and no steps between
Click to expand...
Click to collapse
It's simple, dear Watson: your code updating progress bar too fast, without delays needed for GUI updates
sensboston said:
It's simple, dear Watson: your code updating progress bar too fast, without delays needed for GUI updates
Click to expand...
Click to collapse
yep agree with this .. what you are actually doing in the loop is not enough for you to acutally see the progressbar update .. fast little things these phones of ours
yeah, this was the first i tryed, before posting in this forum.
delay() did not work in c#.
Application.DoEvents() should work if i can believe google, but visual studio says there is no definition for doevents().
So i used
Code:
Pb1.Value++;
System.Threading.Thread.Sleep(1);
after each progressbar.value++, but this either didnt work...
what is the secret?
win98 said:
yeah, this was the first i tryed, before posting in this forum.
delay() did not work in c#.
Application.DoEvents() should work if i can believe google, but visual studio says there is no definition for doevents().
So i used
Code:
Pb1.Value++;
System.Threading.Thread.Sleep(1);
after each progressbar.value++, but this either didnt work...
what is the secret?
Click to expand...
Click to collapse
1 millisecond will not be enough to slow it down either
Maybe try 1000 instead ..
something else i thought of too ..
you may want to think about your design
If a progress bar is going to just flash up and complete as what you are doing is too fast .. you need to think 'is a progress bar the right control to use'
if you are going to increase the amount of work your background thread is going to do then I would say keep the progress bar
If the background thread is going to be this quick always .. then maybe a label saying 'please wait' ... and then hide the label when done .. or something similar
i tried with 1000 ms but this progress bar isnt running.
@cameronm: i want to create a "benchmark app" where the cpu counts the progressbar to 1million and measures the time. the time measuring is working correctly. i just want to get a nice GUI with a running bar, like it runs when you download and install apps from the market.
i was very long googling and found commands like progressbar.PerfomStep(); like described here http://www.java2s.com/Code/CSharp/GUI-Windows-Form/ProgressBarinC.htm
this is also c#, but i cant perfom this command. did i miss some assembly, headers or so? or is it because im doint a windows phone form and that there are less command than in a normal windows application?
You want to make a Benchmark app and you actually used :System.Threading.Thread.Sleep(*int)...!
This is not Benchmarking.
Background Worker like any other ThreadTypeClass should report it's progress via the BackgroundWorker_ProgressChanged_Event(..args).
Inside the Event either u PerformStep() either you implement your own code logic.
If even after this the worker fills instanly like "cameronm" said above then consider making the backgroundworker's Job a bit heavier or leave the progressBar and even the seperated background thread Idea cause it is not Needed.
yes, i am not luck with using a sleep command
PerformStep() is not accepted by the compiler
so you mean just counting up is to "easy". what progress could be "heavier". now i understand what cameronm meant^^
in the evening i will try more difficult calculations like sqare and multiplication of integers. would that be heavy enough?
Typing from LG quantum
Try this: make your calculations in a for loop 1-100..at each loop make progressbar.value++ .
You should be calling ReportProgress and then updating the Progress Bar in the Progress Changed function.
See: http://msdn.microsoft.com/en-us/library/cc221403(v=vs.95).aspx
@PG2G
the link you posted was exactly the source where i learned to implement the bw_worker. but with the command you told me i got an failure in the marked line (see source code comment). It says: InvalidOperationException: Operation has already been completed.
Code:
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
double a, b, c;
DateTime StartZeit = DateTime.Now;
Dispatcher.BeginInvoke(() =>
{
LblDuration.Text = "";
BtnStart.Content = "Calculating...";
for (int i = 0; i < Pb1.Maximum/100; i++)
{
if ((worker.CancellationPending == true))
{
e.Cancel = true;
break;
}
else
{
for (int m = 0; m < 10; m++)
{
a = 3547.23; //double
b = 2354.15; //double
c = (a * b) * (a * a * b);
}
Pb1.Value++;//PbStep();
worker.ReportProgress((i * 10)); //Failure here//
}
}
DateTime EndZeit = DateTime.Now;
TimeSpan GemesseneZeit = EndZeit - StartZeit;
LblDuration.Text = "Duration: " + GemesseneZeit.ToString();
BtnStart.Content = "Start";
});
}
@Freeboss
i tried it with your loop and a double calculation but it didnt work...
im going crazy, in vb i can do this in 10 minutes^^

Boolean Replacement

Hey Guys..
I have a problem with my xposed module.
I will a class to boolean false not true if rooted device..
Code:
public static boolean isRooted()
This to return false if rooted device..
Code:
XposedHelpers.findAndHockMethod("com.example.utils.RootCheck", lpparam.classLoader, "isRooted", boolean.class, new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
param.args[0] = false;
}
});
Xposed say me nosuchmethoderror com.example.utils.RootCheck#isRooted(boolean)..
Can help me..
Thanks
Sorry for my bad English i m a german.
what class is it, is it your own?
are you filtering by package name?
Is not my own class..
From another Application..
This is the class. i have decoded.
I want replace "public static final String" , public static boolean isRooted() to ever false and private static boolean a(String str) to ever false..
can help me?
Code:
public final class RootCheck {
public static final String VALUE_DEVICE_FLAG_SU = "su";
public static final String VALUE_DEVICE_FLAG_SUPER_USER_APK = "superuser.apk";
public static final String VALUE_DEVICE_FLAG_TEST_KEYS = "testkeys";
private RootCheck() {
}
public static boolean isRooted() {
BuildConfig.IS_PROD.booleanValue();
return false;
}
public static Object[] getFlags() {
int i;
int i2;
List arrayList;
Object[] objArr;
int i3 = 1;
String str = Build.TAGS;
if (str == null || !str.contains("test-keys")) {
i = 0;
} else {
i = 1;
}
try {
if (new File("/system/app/Superuser.apk").exists()) {
i2 = 1;
if (!(a("/system/xbin/which su") || a("/system/bin/which su") || a("which su"))) {
i3 = 0;
}
arrayList = new ArrayList();
if (i3 != 0) {
arrayList.add(VALUE_DEVICE_FLAG_SU);
}
if (i2 != 0) {
arrayList.add(VALUE_DEVICE_FLAG_SUPER_USER_APK);
}
if (i != 0) {
arrayList.add(VALUE_DEVICE_FLAG_TEST_KEYS);
}
objArr = new Object[0];
if (arrayList.isEmpty()) {
return arrayList.toArray(objArr);
}
return objArr;
}
} catch (Exception e) {
}
i2 = 0;
i3 = 0;
arrayList = new ArrayList();
if (i3 != 0) {
arrayList.add(VALUE_DEVICE_FLAG_SU);
}
if (i2 != 0) {
arrayList.add(VALUE_DEVICE_FLAG_SUPER_USER_APK);
}
if (i != 0) {
arrayList.add(VALUE_DEVICE_FLAG_TEST_KEYS);
}
objArr = new Object[0];
if (arrayList.isEmpty()) {
return objArr;
}
return arrayList.toArray(objArr);
}
private static boolean a(String str) {
try {
Runtime.getRuntime().exec(str);
return true;
} catch (Exception e) {
return false;
}
}
}
oh wait, isRooted doesn't take any arguments and you're trying to hook isRooted with a boolean argument, which would be a different method
return values are called result here (getResult, setResult.) args is only for arguments
Oh thx
Code:
06-17 22:21:05.373: E/Xposed(30470): java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.Boolean.booleanValue()' on a null object reference
06-17 22:21:05.373: E/Xposed(30470): at de.bozja.hrh.Hidder$1.beforeHookedMethod(Hidder.java:22)
Error why?
class
Code:
findAndHookMethod("com.example.RootCheck", lpparam.classLoader, "isRooted", new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
boolean isRoot = (Boolean) param.getResult(); //Error on this line
if(isRoot == true)
isRoot = false;
param.setResult(isRoot);
}
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
boolean isRoot = (Boolean) param.getResult();
if(isRoot == true)
isRoot = false;
param.setResult(isRoot);
}
});
beforeHookedMethod is called before the method is executed, so there can't be any result. so it's null
Just setresult to false in beforehooked dont add extra junk
And dont hook method afterhook no need before will do what u need
gitfib said:
oh wait, isRooted doesn't take any arguments and you're trying to hook isRooted with a boolean argument, which would be a different method
return values are called result here (getResult, setResult.) args is only for arguments
Click to expand...
Click to collapse
i am also facing the same issue today when trying to hook some certain method that doesnt take in any argument. And i really didnt get the answer you gave. Could you be more elaborate please?
that was a long time. necrobumping from Google?
I think I meant to use param.setResult instead of param.args[0] to set the return value
gitfib said:
that was a long time. necrobumping from Google?
I think I meant to use param.setResult instead of param.args[0] to set the return value
Click to expand...
Click to collapse
thanks. Will try this too. Couldn't find it on Google
gitfib said:
that was a long time. necrobumping from Google?
I think I meant to use param.setResult instead of param.args[0] to set the return value
Click to expand...
Click to collapse
this is the method i want to hook. I want it to return false
public boolean vpn() {
try {
Iterator it = Collections.list(NetworkInterface.getNetworkInterfaces()).iterator();
String str = "";
do {
if (!it.hasNext()) {
return false;
}
NetworkInterface networkInterface = (NetworkInterface) it.next();
if (networkInterface.isUp()) {
str = networkInterface.getName();
}
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("IFACE NAME: ");
stringBuilder.append(str);
Log.d("DEBUG", stringBuilder.toString());
if (str.contains("tun") || str.contains("ppp")) {
Toast.makeText(getContext(), "Hello vpn detected", 1).show();
}
} while (!str.contains("pptp"));
Toast.makeText(getContext(), "Hello vpn detected", 1).show();
return true;
} catch (SocketException e) {
e.printStackTrace();
}
}
and this is my kotlin class
package app.devzeus.yesvpn.hook
import de.robv.android.xposed.IXposedHookLoadPackage
import de.robv.android.xposed.XC_MethodHook
import de.robv.android.xposed.XposedHelpers
import de.robv.android.xposed.callbacks.XC_LoadPackage
class hook: IXposedHookLoadPackage {
override fun handleLoadPackage(lpparam: XC_LoadPackage.LoadPackageParam?) {
val pakage = "com.eclipse.gamonyapp"
val className = "com.eclipse.gamonyapp.Fragments.OffersFragment"
val method = "vpn"
if (lpparam?.packageName == pakage){
XposedHelpers.findAndHookMethod(className, lpparam.classLoader, method, object: XC_MethodHook(){
override fun beforeHookedMethod(param: MethodHookParam?) {
super.beforeHookedMethod(param)
param?.result = false
}
})
}
}
}
am i doing it wrong? it still doesnt work. The class and method locations are correct
devzeus_ke said:
XposedHelpers.findAndHookMethod(className, lpparam.classLoader, method, object: XC_MethodHook(){
override fun beforeHookedMethod(param: MethodHookParam?) {
super.beforeHookedMethod(param)
param?.result = false
}
Click to expand...
Click to collapse
this should be a separate thread imo
XC_MethodHook | Xposed Framework API
api.xposed.info
in Java there would be no need for the super call and the syntax is .setResult, but I'm not sure in Kotlin
gitfib said:
this should be a separate thread imo
XC_MethodHook | Xposed Framework API
api.xposed.info
in Java there would be no need for the super call and the syntax is .setResult, but I'm not sure in Kotlin
Click to expand...
Click to collapse
about the .setResult(false) the compiler suggests .result = false

Get TextView from method [RESOLVED]

I'm trying to get the TextView of the following method, but everything I have tried returns a null value.
This is the code:
Code:
public final void a(boolean z) {
if (z) {
if (this.W == null) {
this.W = new TextView(getContext());
this.W.setBackgroundResource(android.support.design.widget.b.AnonymousClass7.ay);
this.W.setGravity(17);
LayoutParams marginLayoutParams = new MarginLayoutParams(-2, -2);
marginLayoutParams.bottomMargin = getContext().getResources().getDimensionPixelSize(android.support.design.widget.b.AnonymousClass5.ap);
addView(this.W, marginLayoutParams);
this.h = this.W;
}
this.W.setText(k.e(getContext(), this.a.k).toUpperCase());
this.W.setTextSize(a(getResources()));
this.W.setVisibility(0);
this.t = true;
return;
}
if (this.W != null) {
this.W.setVisibility(8);
}
this.t = false;
}
This is one of the ways in which I have tried to obtain value.
Code:
findAndHookMethod(class, "a", boolean.class, new XC_MethodHook() {
@Override
protected void afterHookedMethod(XC_MethodHook.MethodHookParam params) throws Throwable {
super.afterHookedMethod(params);
TextView textView = (TextView) params.thisObject;
if (textView!=null) {
textView.setTextColor(color);
}
}
});
I have also tried the following:
Code:
TextView textView = (TextView) XposedHelpers.getObjectField(p.thisObject, "W");
and
Code:
TextView textView = (TextView] params.args[0];
But nothing is working.
Is it possible to get the TextView? and if it's possible, how to do it?
Problem solved, I had to assign the private variable field as setAccessible(true).

Categories

Resources