C# Battery State - Windows Mobile Software Development

Hi Everyone,
I'm making a windows mobile app in C# to help those affected by alzheimers disease and other dimentia related conditions
One function of the app is sending SMS text messages and so I'd really like to include the battery charge percentage in each text, but I can't find how to do so!
How can I put this in my program?
Thanks!
James

Use PowerBatteryStrength of Status.SystemProperty!

I know it's something to do with
Code:
Microsoft.WindowsMobile.Status.SystemState.PowerBatteryStrength.ToString();
but beyond that I'm lost! How do I put it in to my code so that I just get the string "Battery level: 42%" for example?

Signal strenght and battery level example
Hi,
Here is a simple example on how you can use the SystemState and SystemProperties.
Hope this will help you.
Code:
using System;
using System.Windows.Forms;
using Microsoft.WindowsMobile.Status;
namespace SignalAndBatteryLevel
{
public partial class BatteryAndSignalLevel : Form
{
private readonly SystemState _signalStrenght =
new SystemState(SystemProperty.PhoneSignalStrength);
private readonly SystemState _batteryLevel =
new SystemState(SystemProperty.PowerBatteryStrength);
private readonly SystemState _batteryState =
new SystemState(SystemProperty.PowerBatteryState);
public BatteryAndSignalLevel()
{
InitializeComponent();
SetSignalStrenght();
SetBatteryLevel();
_signalStrenght.Changed +=
SignalStrenghtChanged;
_batteryLevel.Changed += BatteryLevelChanged;
_batteryState.Changed += BatteryLevelChanged;
}
private void SignalStrenghtChanged(object sender,
EventArgs e)
{
SetSignalStrenght();
}
public void SetSignalStrenght()
{
_lblSignalStrenght.Text =
SystemState.PhoneSignalStrength.ToString();
}
private void BatteryLevelChanged(object sender,
EventArgs e)
{
SetBatteryLevel();
}
private void SetBatteryLevel()
{
_lblBatteryLevel.Text = GetBatteryLevel();
}
private string GetBatteryLevel()
{
string batteryLevel = "Unknown";
if (SystemState.PowerBatteryState ==
BatteryState.Charging)
{
return "Charging";
}
switch (SystemState.PowerBatteryStrength)
{
case BatteryLevel.VeryLow:
batteryLevel = "Very lowt";
break;
case BatteryLevel.Low:
batteryLevel = "Low";
break;
case BatteryLevel.Medium:
batteryLevel = "Medium";
break;
case BatteryLevel.High:
batteryLevel = "High";
break;
case BatteryLevel.VeryHigh:
batteryLevel = "Very High";
break;
}
return batteryLevel;
}
}
}

Hi PerOla,
This is really a good solution and working fine for me. Its really help me out in one of my project.
Thank you very much....
Vimal Panchal

Related

Closing gps in gps event handler - endless loop

In my application when I get position latitude and longitude from GPS, I am downloading bing map to a picture box. I've been trying now to protect my application in case there is no internet connection. I've done that in the GetMap function and it works fine. After that I want to close gps - the problem is that I'm trying to do that in gps event handler - it is so because I update the picture box constantly:
Code:
void UpdateData(object sender, System.EventArgs args)
{
menuGPS.Text = "Enable GPS";
menuZoom.Enabled = false;
menuView.Enabled = false;
}
void gps_LocationChanged(object sender, Microsoft.WindowsMobile.Samples.Location.LocationChangedEventArgs args)
{
if (args.Position.LatitudeValid && args.Position.LongitudeValid)
{
if (isCameraEnabled == false)
{
try
{
pbMap.Invoke((UpdateMap)delegate()
{
pbMap.Image = bingMap.GetMap(args.Position.Latitude,
args.Position.Longitude,
zoom,
mapStyle);
});
if (pbMap.Image == null)
{
Invoke(updateDataHandler);
gpsData.gps.LocationChanged -= gps_LocationChanged;
gpsData.closeGPS();
}
}
catch (ArgumentException ex)
{
MessageBox.Show("An error has occured:" + ex.Message , "Error");
}
}
else
{
}
}
}
So after the gpsData.gps.LocationChanged -= gps_LocationChanged; and gpsData.closeGPS(); are being called in the event handler the gps gets stuck in the WaitForGpsEvents() method in GPS.cs in the while loop because bool lisening value is not changed to false.
If I put gpsData.gps.LocationChanged -= gps_LocationChanged; and gpsData.closeGPS(); to the void UpdateData(object sender, System.EventArgs args) then it stops in the Close() method on the lock condition:
// block until our event thread is finished before
// we close our native event handles
lock (this)
How can I close the GPS?

Photochooser task not working after phone was synced with PC?

hello guys and girls,
I have a very peculiar problem with my application (two actually, working together to make a bigger problem)
I have a resume tile, which allows the users to resume working on the picture they were working after navigating away from the game.
Now, the users can choose pictures in their media lib to use in the game.
However, after i sync my phone to laptop, unplug it, then try to use the resume tile, it simply brings me to main page and does not continue doing the resume as it should do. This only happens with pictures from photochooser task: the ones integrated in the app work fine.
The photochooser task also refuses to work properly until i start the app "the usual way" and not from the resume tile. It basically goes back to the MainPage no matter what.
So, what's with all this? I think it has something to do with the syncing messing up isolated storage and phone storage.
here's some code:
MainPage:
Basically, I'm using some messages to know from where i navigated to the MainPage. The "resumeTile" message is obviously coming from the resume tile, whereas "FromPlay" means the player just left the play page.
App.IsFirstLoaded is used to known that it loaded already and should ignore the "ResumeTile" message and continue with the resume, but not to repeat the same feat in case the user navigates from any page in the game.
Code:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
string msesage = null;
try
{
NavigationContext.QueryString.TryGetValue("message", out msesage);
if (msesage == "resumeTile")
{
App.isFirstLoaded = true;
}
if (msesage == "FromPlay")
{
NavigationService.RemoveBackEntry();
}
if (App.isFirstLoaded == true)
{
resume_SubmitResume();
App.isFirstLoaded = false;
msesage = null;
}
else
{
//NavigationService.RemoveBackEntry();
base.OnNavigatedTo(e);
if (msg == "openPlay")
{
string msggs = msg;
msg = null;
if (portrait)
{
NavigationService.Navigate(new Uri("/PlayPage.xaml?msg=" + msggs, UriKind.Relative));
}
else
{
NavigationService.Navigate(new Uri("/PlayPageLandscape.xaml?msg=" + msggs, UriKind.Relative));
}
}
}
}
catch (NullReferenceException)
{
}
}
and here is the photochooser task completed event handler
Code:
void photochoser_Completed(object sender, PhotoResult e)
{
string path = "mhgcjtcthgg.jpg";
if (e.TaskResult == TaskResult.OK)
{
using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fs = new IsolatedStorageFileStream(path, FileMode.Create, FileAccess.Write, FileShare.ReadWrite, IsolatedStorageFile.GetUserStoreForApplication()))
{
if (e.Error == null)
{
if (App.AutoSave == true)
{
MediaLibrary ml = new MediaLibrary();
ml.SavePicture("CountlessPuzzles" + DateTime.Now.ToShortTimeString(), e.ChosenPhoto);
}
BitmapImage bi = new BitmapImage();
bi.SetSource(e.ChosenPhoto);
WriteableBitmap wb = new WriteableBitmap(bi);
if (wb.PixelHeight <= wb.PixelWidth)
{
Extensions.SaveJpeg(wb, fs, DHeigh, DWidth, 0, 100);
//NavigationService.Navigate(new Uri("/PlayPageLandscape.xaml?msg=" + msg, UriKind.Relative));
}
else
{
Extensions.SaveJpeg(wb, fs, DWidth, DHeigh, 0, 100);
//NavigationService.Navigate(new Uri("PlayPage.xaml?msg=" + msg, UriKind.Relative));
portrait = true;
}
}
}
}
msg = "openPlay";
}
else
{
isDataSavedInIsolatedStorage = false;
}
// e.ChosenPhoto.Close();
}
So, any ideas?
mcosmin222 said:
hello guys and girls,
I have a very peculiar problem with my application (two actually, working together to make a bigger problem)
I have a resume tile, which allows the users to resume working on the picture they were working after navigating away from the game.
Now, the users can choose pictures in their media lib to use in the game.
However, after i sync my phone to laptop, unplug it, then try to use the resume tile, it simply brings me to main page and does not continue doing the resume as it should do. This only happens with pictures from photochooser task: the ones integrated in the app work fine.
The photochooser task also refuses to work properly until i start the app "the usual way" and not from the resume tile. It basically goes back to the MainPage no matter what.
So, what's with all this? I think it has something to do with the syncing messing up isolated storage and phone storage.
here's some code:
MainPage:
Basically, I'm using some messages to know from where i navigated to the MainPage. The "resumeTile" message is obviously coming from the resume tile, whereas "FromPlay" means the player just left the play page.
App.IsFirstLoaded is used to known that it loaded already and should ignore the "ResumeTile" message and continue with the resume, but not to repeat the same feat in case the user navigates from any page in the game.
Code:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
string msesage = null;
try
{
NavigationContext.QueryString.TryGetValue("message", out msesage);
if (msesage == "resumeTile")
{
App.isFirstLoaded = true;
}
if (msesage == "FromPlay")
{
NavigationService.RemoveBackEntry();
}
if (App.isFirstLoaded == true)
{
resume_SubmitResume();
App.isFirstLoaded = false;
msesage = null;
}
else
{
//NavigationService.RemoveBackEntry();
base.OnNavigatedTo(e);
if (msg == "openPlay")
{
string msggs = msg;
msg = null;
if (portrait)
{
NavigationService.Navigate(new Uri("/PlayPage.xaml?msg=" + msggs, UriKind.Relative));
}
else
{
NavigationService.Navigate(new Uri("/PlayPageLandscape.xaml?msg=" + msggs, UriKind.Relative));
}
}
}
}
catch (NullReferenceException)
{
}
}
and here is the photochooser task completed event handler
Code:
void photochoser_Completed(object sender, PhotoResult e)
{
string path = "mhgcjtcthgg.jpg";
if (e.TaskResult == TaskResult.OK)
{
using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fs = new IsolatedStorageFileStream(path, FileMode.Create, FileAccess.Write, FileShare.ReadWrite, IsolatedStorageFile.GetUserStoreForApplication()))
{
if (e.Error == null)
{
if (App.AutoSave == true)
{
MediaLibrary ml = new MediaLibrary();
ml.SavePicture("CountlessPuzzles" + DateTime.Now.ToShortTimeString(), e.ChosenPhoto);
}
BitmapImage bi = new BitmapImage();
bi.SetSource(e.ChosenPhoto);
WriteableBitmap wb = new WriteableBitmap(bi);
if (wb.PixelHeight <= wb.PixelWidth)
{
Extensions.SaveJpeg(wb, fs, DHeigh, DWidth, 0, 100);
//NavigationService.Navigate(new Uri("/PlayPageLandscape.xaml?msg=" + msg, UriKind.Relative));
}
else
{
Extensions.SaveJpeg(wb, fs, DWidth, DHeigh, 0, 100);
//NavigationService.Navigate(new Uri("PlayPage.xaml?msg=" + msg, UriKind.Relative));
portrait = true;
}
}
}
}
msg = "openPlay";
}
else
{
isDataSavedInIsolatedStorage = false;
}
// e.ChosenPhoto.Close();
}
So, any ideas?
Click to expand...
Click to collapse
Photochooser does not work when the phone is syncing via zune, maybe once the app is running and you try to sync, PhotoChooser crashes or something.
http://www.codeproject.com/Articles/342149/Using-WPConnect-instead-of-Zune-for-Windows-Phone
I figured that when synced, the photochooser instantiated inside the app is turned off or something, and stays so until the constructor is called again, which would happen if the app is re-launched.
Kinda peculiar though...

XClasses - A Xposed Library

Hello guys,
I want to share my library XClasses.
My idea was to see every XClass as an extension of the original class.
My aim was to improve the user experience during the development.
Also I wanted to increase the readability of xposed code.
So it's nothing special.
It's just my personal opinion how readable code should look like.
A small example:
Code:
public class XposedMain implements IXposedHookLoadPackage
{
@Override
public void handleLoadPackage(XC_LoadPackage.LoadPackageParam lpparam)
throws Throwable {
if(lpparam.packageName.equals("com.android.systemui"))
{
XposedHelpers.findAndHookMethod(TextView.class, "setText", CharSequence.class, TextView.BufferType.class, boolean.class, int.class, new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param)
throws Throwable {
TextView tv = (TextView)param.thisObject;
CharSequence text = (CharSequence)param.args[0];
TextView.BufferType type = (TextView.BufferType)param.args[1];
boolean notifyBefore = (Boolean)param.args[2];
int oldlen = (Integer)param.args[3];
XposedBridge.log("setText "+text+" with size "+tv.getTextSize());
}
});
}
}
}
The same code with XClasses:
Code:
// class 1
public class XposedMain implements IXposedHookLoadPackage
{
@Override
public void handleLoadPackage(XC_LoadPackage.LoadPackageParam lpparam)
throws Throwable {
if(lpparam.packageName.equals("com.android.systemui"))
{
setup(lpparam.classLoader);
hook(XTextView.class);
}
}
}
// class 2
public class XTextView
extends AbstractXClass<TextView>
{
public static String getOriginalClassName() { return TextView.class.getCanonicalName(); }
public XTextView(TextView objectThis) { super(objectThis); }
@BeforeOriginalMethod
private void setText_Before(CharSequence text, TextView.BufferType type,
boolean notifyBefore, int oldlen) throws Throwable {
XposedBridge.log("setText "+text+" with size "+getThis().getTextSize());
}
}
If you would like to know more you should visit the following site: https://github.com/seebye/XClasses
Regards,
Seebye

Hooking a protected List in an Inner Class with an odd set of Parameters

So, I'm getting fairly good at hooking and modifying classes, but this one is so unique, I'm not quite sure how to approach hooking it to do what I want. Code for the method/class I want to attack:
Code:
private class CreateLaunchPointListTask
extends AsyncTask<Void, Void, List<LaunchPoint>>
{
private CreateLaunchPointListTask() {}
protected List<LaunchPoint> doInBackground(Void... paramVarArgs)
{
paramVarArgs = mContext.getString(2131558445);
Object localObject = new Intent("android.intent.action.MAIN");
((Intent)localObject).addCategory(paramVarArgs);
paramVarArgs = new LinkedList();
PackageManager localPackageManager = mContext.getPackageManager();
localObject = localPackageManager.queryIntentActivities((Intent)localObject, 129);
int j = ((List)localObject).size();
int i = 0;
while (i < j)
{
ResolveInfo localResolveInfo = (ResolveInfo)((List)localObject).get(i);
if (activityInfo != null) {
paramVarArgs.add(new LaunchPoint(mContext, localPackageManager, localResolveInfo));
}
i += 1;
}
return paramVarArgs;
}
public void onPostExecute(List<LaunchPoint> arg1)
{
synchronized (mLock)
{
mAllLaunchPoints.clear();
mAllLaunchPoints.addAll(???);
synchronized (mCachedActions)
{
LaunchPointListGenerator.access$502(LaunchPointListGenerator.this, true);
if (!mCachedActions.isEmpty()) {
((LaunchPointListGenerator.CachedAction)mCachedActions.remove()).apply();
}
}
}
LaunchPointListGenerator.access$602(LaunchPointListGenerator.this, true);
Iterator localIterator = mListeners.iterator();
while (localIterator.hasNext()) {
((LaunchPointListGenerator.Listener)localIterator.next()).onLaunchPointListGeneratorReady();
}
}
}
So, while this is a big chunk of code, everything I want to do is really in the first few lines:
Code:
paramVarArgs = mContext.getString(2131558445);
Object localObject = new Intent("android.intent.action.MAIN");
((Intent)localObject).addCategory(paramVarArgs);
So, string 2131558445 is a specific intent. What I would like to do is add *another* category after 2131558445 is added to localObject.
That would be the simplest implementation.
A more advanced implementation would be to actually and return a second LinkedList, paramVarArgs2, that only matches up to the second intent category that we're inserting.
Any help would be greatly appreciated.

[Q] How to use a variable from one hook in another? (Why is this an NPE?)

Hello, I have made this code
Link : http://hastebin.com/hiyupafibi.java
Duplicated here :
Code:
//In my module, I have this activity MainActivity, which has a function to generate random number
private int randomNumber() {
return (new Random()).nextInt(3);
}
//Toast this random number somewhere in the main activity
Toast.makeText(MainActivity.this, " " + randomNumber(), Toast.LENGTH_LONG).show();
//In XposedMod, make a hook
public class XposedMod implements IXposedHookLoadPackage {
private TextView tv;
public static final String PACKAGE_NAME = ".......";
@Override
public void handleLoadPackage(LoadPackageParam lpparam) throws Throwable {
if (lpparam.packageName.equals(PACKAGE_NAME)) {
Class<?> MainActivityClass = XposedHelpers.findClass(PACKAGE_NAME + ".MainActivity", lpparam.classLoader);
XposedHelpers.findAndHookMethod(MainActivityClass, "randomNumber", new XC_MethodReplacement() {
@Override
protected Object replaceHookedMethod(MethodHookParam methodHookParam) throws Throwable {
try {
tv.setText("No NPE");
return 45;
} catch (NullPointerException e) {
return 44;
}
}
});
} else if (lpparam.packageName.equals("com.android.systemui")) {
Class<?> someClass = XposedHelpers.findClass("com.android.systemui.SomeClass", lpparam.classLoader);
XposedHelpers.findAndHookMethod(someClass, "someMethod", Context.class, new XC_MethodHook() {
@Override
protected Object beforeHookedMethod(MethodHookParam methodHookParam) throws Throwable {
tv = new TextView((Context) param.args[0]);
if (tv==null)
XposedBridge.log("tv is null, apologies!");
}
});
}
}
}
Everytime that toast is supposed to be shown, I get the answer to be 44 (that is, tv is null), but that should not be the case, because the log statement when tv is null is not shown. What am I doing wrong?
Thanks for the help, I appreciate it.
Cheers!

Categories

Resources