[Help] Hooking A Jar Library Such As Cardboard - Xposed Framework Development

[Help] Hooking a jar library such as Cardboard
Hi there,
I am currently working on an Xposed module which tries to anti-jitter the gyroscope for the phones that have an unprecise gyroscope such as Moto G 2nd gen or Huawei Ascendn G7.
The app currently hooks directly to the SystemSensorManager to modify the gyroscope's values before they get sent to another app (from the code in my github repo: lrq3000/GyroscopeNoiseFilter):
Code:
public class GyroscopeNoiseFilter implements IXposedHookLoadPackage {
public XSharedPreferences pref;
@Override
public void handleLoadPackage(XC_LoadPackage.LoadPackageParam lpparam) throws Throwable {
pref = new XSharedPreferences(GyroscopeNoiseFilter.class.getPackage().getName(), "pref_median"); // load the preferences using Xposed (necessary to be accessible from inside the hook, SharedPreferences() won't work)
pref.makeWorldReadable();
try {
final Class<?> sensorEQ = findClass(
"android.hardware.SystemSensorManager$SensorEventQueue",
lpparam.classLoader);
XposedBridge.hookAllMethods(sensorEQ, "dispatchSensorEvent", new
XC_MethodHook() {
...
However, this does not work with apps that use the latest Google Cardboard SDK, since it provides its own virtual sensors and it seems it directly access the hardware sensors, thus this totally bypass the dispatchSensorEvent.
Thus, I would like to hook into a class inside Google Cardboard SDK. I identified some candidates, but everytime I try to hook a class inside this library, I get an exception "java.lang.ClassNotFoundException".
Google Cardboard SDK is directly imported by the app devs inside their projects, and it's referenced as an external jar in the build path. I guess this is where the problem is: I am neither trying to hook a specific app or a global android SDK class, but a class in a library that is imported in multiples apps.
Is there a way to hook into such a library using Xposed?

I fixed the issue, in fact Xposed will just hook to the class you want even if it's a library inside the app you're targeting, because, as you know in Java, the included libraries are included in the project with a package path just like the main application. So for example, if for example your main package is "com.app.my" and the library is "com.some.lib", then you can easily hook onto "com.some.lib" just like you would for "com.app.my".
Now as to why my code posted above didn't work, I don't really know why, but I guess this is because the Cardboard's SDK is fastly changing and the classes I was targeting (from the last SDK version) simply weren't in the app I targeted for my testing, because the app was using an older Cardboard's SDK version where the classes weren't available yet.
For a practical example, see my diff between non-working to working hook here:
https://github.com/lrq3000/XposedJitteryGyroFix/compare/master...lrq3000:cardboard

Related

WM 6.1 Simple App Error

I am learning to program for windows mobile. I am working on making a small app, and when I test it with virtually nothing in the program (just a main menu, form, and 2 labels), I get a error when testing on my phone.
The error is:
An unhandled exception of type 'System.ObjectDisposedException' occurred in System.Drawing.dll
This happens no matter what I do, but does not happen in the emulator.
jexmex said:
I am learning to program for windows mobile. I am working on making a small app, and when I test it with virtually nothing in the program (just a main menu, form, and 2 labels), I get a error when testing on my phone.
The error is:
An unhandled exception of type 'System.ObjectDisposedException' occurred in System.Drawing.dll
This happens no matter what I do, but does not happen in the emulator.
Click to expand...
Click to collapse
There has to be some code that is causing this issue. Are you saying that your app does not have any code in it at all? If that's the case then it's probably one of the controls that you're using. Are they standard windows .Net controls, or are you using 3rd party controls?
The error message basically means that an object has been created and then disposed and you're trying to do something with it after that. That obviously isn't gonna work
Give us some more information, or even better, give us the code that causes the error.
Yeah I have not added any custom code, just added standard toolkit items (main menu was already there when I made the new project, and 2 labels).
I am going to try just making a new project, and not doing anything to it, and just running it, to see if that works, but I dont think it will.
This is the complete code from the new project that I did nothing to, and it still errored out.
namespace SmartDeviceProject4
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
private System.Windows.Forms.MainMenu mainMenu1;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.mainMenu1 = new System.Windows.Forms.MainMenu();
this.Menu = this.mainMenu1;
this.components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.Text = "Form1";
this.AutoScroll = true;
}
#endregion
}
}
Click to expand...
Click to collapse
Some other information:
using Windows Standard SDK 6
Phone is running Windows Mobile 6.1 with Compact framework of 3.5
jexmex said:
This is the complete code from the new project that I did nothing to, and it still errored out.
Some other information:
using Windows Standard SDK 6
Phone is running Windows Mobile 6.1 with Compact framework of 3.5
Click to expand...
Click to collapse
To be perfectly honest with you mate, I'm at a bit of a loss. Do you have another device you could try it on? It's clutching at straws a bit, but there could possibly be a problem with the installation of .Net 3.5 on your phone. That would obviously explain why it works on the emulator but not your phone, but it really is a bit far fetched.
If you don't have another device, maybe try re-installing .Net and see if that helps.
johncmolyneux said:
To be perfectly honest with you mate, I'm at a bit of a loss. Do you have another device you could try it on? It's clutching at straws a bit, but there could possibly be a problem with the installation of .Net 3.5 on your phone. That would obviously explain why it works on the emulator but not your phone, but it really is a bit far fetched.
If you don't have another device, maybe try re-installing .Net and see if that helps.
Click to expand...
Click to collapse
I have already tried reinstalling .net (on the phone), with no luck, and I dont have any other device to test on.
Really sucks, cause I really wanted to get into mobile app development.

[Q] [Resolved] [.Net CF 3.5] How do i create a treeview based file browser

I have a problem with a project i'm working on and that is:
How do i create a TreeView based file browser that can export a selected path and filename to a textbox and a Process.Start call at the same time. That's it in a nut shell. The main part if the tree view bit but i haven't figured out how to do variables yet and i'm gonna need one for the second part. I have spent hours googling and i have this question posted on a dedicated VB forum.
I'm using Visual Basic 2008 as the IDE and .Net CF 3.5 as the language (obviously)
If anyone has any ideas on this i'll gladly hear them coz i am really stuck. I found writting code to soft reset a device was easier
TreeNodeCollection tr=treeView1.Nodes;
TreeNode tn;
foreach (string dirs in System.IO.Directory.GetDirectories(System.IO.Directory.GetDirectoryRoot(Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName)))
{
tn = new TreeNode(dirs);
//tr = new TreeNodeCollection();
tr.Add(tn);
}
ergintiravoglu said:
TreeNodeCollection tr=treeView1.Nodes;
TreeNode tn;
foreach (string dirs in System.IO.Directory.GetDirectories(System.IO.Directory.GetDirectoryRoot(Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName)))
{
tn = new TreeNode(dirs);
//tr = new TreeNodeCollection();
tr.Add(tn);
}
Click to expand...
Click to collapse
Is that C# code or VB?
M3PH said:
Is that C# code or VB?
Click to expand...
Click to collapse
C#....VB don't have the curly brackets
So i've come back to this question after a few months avoiding VB. I'm now working on a new product and the lack of an folderbrowserdialog object in .Net CF is killing me.
What i need is this (oh and thanks to everyone that posted above but i can't make that solution work). A way to list all the folders on a device and then select one that can be passed to a variable so it's path can be used elsewhere. Maybe also pass the path to a textbox just so it's clear what you have selected. I've spent 2 days googling this and i did find a few things. Most don't work and the rest are in c# which is not much good. So if anyone wants to help me out i would really appreciate it.
Get your head round this.........
O.K. Here's how it's done, with a crash course in one of the most powerful of programming techniques - Recursion. It can confuse the hell out of rookie programmers, as they just can't get their heads round what's going on. It is dependant on a function's local variables and fortunately, .NET's stack based architecture allows us to use it to the full.
You will need, 1.) a TreeView object - named "treeView1" and 2.), a label named "label1" placed underneath it. The label is only there to prove the point that we can get at the full pathname of the selected directory in the Treeview. In reality it can be dropped, just put your processing code directly in the TreeView's AfterSelect() event.
The Form_Load() event gets the directories in the root directory, by calling GetDirList with an initial directory of "\".
GetDirList() adds the directories to the TreeView then calls GetDirList again on each directory to get any subdirectories, and again on each subdirectory, ad nauseum. Keep going until there are no more directories returned.
When completed TreeView contains a list of every directory/subdirectory on the device.
When you select an item from the TreeView the full pathname is displayed in the label. The image at the bottom shows it running under debug on the WinMo 5.0 emulator. There are several directories you would not normally see on your device.
Good Luck, stephj.
Code:
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
Me.GetDirList("\")
End Sub
Private Sub GetDirList(ByVal PathName As String)
Dim dirs As String
For Each dirs In Directory.GetDirectories(PathName)
Dim tn As New TreeNode(dirs)
Me.treeView1.Nodes.Add(tn)
Me.GetDirList(tn.FullPath)
Next
End Sub
Private Sub treeView1_AfterSelect(ByVal sender As Object, ByVal e As TreeViewEventArgs)
Me.label1.Text = e.Node.FullPath
End Sub
P.S.
You will need the VB equivalent of using System.IO adding to your project.
This stuff has been around since .NET CF 1.1
The original project was written in C#, I used .NET Reflector to translate it into VB from the original. The original C# is included here:-
Code:
using System;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace Test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
GetDirList("\\");
}
private void GetDirList(string PathName)
{
foreach (string dirs in System.IO.Directory.GetDirectories(PathName))
{
TreeNode tn = new TreeNode(dirs);
treeView1.Nodes.Add(tn);
GetDirList(tn.FullPath);
}
}
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
label1.Text = e.Node.FullPath;
}
}
}
cool thanks. I'll have a look at coding this tomorrow (i having some fun time right now).
I did have a look at doing this with a list box yesterday but i was getting errors left, right and centre so i really do appreciate the help.
Just an FYI the VB equivelent of "using" is "imports" otherwise most of the objects are the same but i don't nee to worry about adding it as the program is already interacting with the file system.
Again thanks very much. I really appreciate you taking the time to help me out.
I've just had a look at implementing this but i'm having trouble getting the treeview to populate with the folder list. What am i doing wrong? the object names all match up and i can't see why it's not working. Am i just being plain dense?
What i have Is pretty much what you posted except for a few changes to allow for the fact that the treeview object is in a tabcontrol and i already have a bunch of labels knocking around so the label is called label28 and not label1.
I'm sorry if it appears like i'm not trying or i'm asking you to do all the work but i am genuinely really stuck. I get the recursion principal, That's not an issue but i'm trying to create something from scratch that should really have been included in .net CF and i'm just not that good a programmer yet
Should work..... but without seeing the actual code it's rather hard to remotely debug it.
To prove the point, here's the complete VS2008 VB .NET CF 3.5 project.
In the \bin\release directory is the actual executable. If you have .NET CF 3.5 on your device, drop DirList.exe onto it and run it.
I had a look at the project you posted and just copied the coded over. I did make some tweaks so it only loaded the folder list when the tab the treeview was on was clicked but that didn't work so i repated the code in as is and voila! it works. Now all i need is to create a variable to store the selected path in but i think i can manage that.
Again a huge thanks.
Hierarchical view......
Here's the project to indent, compress, and expand the directory tree structure.
I was just playing around with this and i noticed that when you click on a directory below "\" the path becomes "\\this\path". This is obviously not a valid windows mobile path and it is causing an IOexception and I have no idea how to fix it. Google suggests lots of c# pages that say to use a regular expression to strip out the illegal characters but the example i found was for the entire path and it seemed to check each character against a variable of illegal values. I'm sure if that would work for me. Heres the link.
Let me know what you think.
I have no idea where the \\this is coming from, I can't replicate it.
To filter out the extra leading slash use this:-
Code:
Private Sub TreeView1_AfterSelect(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelect
If TreeView1.SelectedNode.FullPath.Length() = 1 Then
Label1.Text = TreeView1.SelectedNode.FullPath
Else
Label1.Text = TreeView1.SelectedNode.FullPath.Substring(1)
End If
Interesting new problem has cropped up with this code. It doesn't seem to work on rhodiums. It works fine in the emulator, my HD2 and all of CajunFlavouredBob's devices but i have a user that has a rhodium that get the error posted here. I can't replicte it and i don't have a rhodium to test it with. Any ideas?
Hmmmmm another tricky one. Without seeing the device actually throw the error, it can be a bit difficult.
Does this machine actually report the storage card as "\Storage Card"? Some machines don't. In which case you may have to use some storage card enumeration trick to get hold of the real name it uses. This may not apply in this case.
Also, to make things trickier still, the stack dump shows 'GetInternalDirectoryNames()' as the function throwing the error first. This is a level below your call of GetDirectories(), and is being used by the OS to actually go get the info. You may have to create a test version of EXCT2 full of Try...Catch programming blocks, to try to get to the real point where the error is being thrown.
well this turned out to be a memory related issue. So instead of using the folder browser we now use the stock winmo savedialog. because it uses less memory and allows us access to the locations we need.
Thanks for helping though steph.

State of WP7 Homebrew - D3D11, Filesystem, Sockets, etc

Hey guys,
There has been a lot of great strides here in learning more about this WP7 and what it's capabilities are! I'm very excited about what everyone is doing!
I'm sure a lot of you have been doing your own tinkering and was hoping to combine some efforts and maybe eventually come up with a solid SDK for home brew applications.
Here is where I'm at with my exploration:
With the COM bridge and Visual Studio 2008 one can develop a native ARM COM DLL to talk to native code from Silverlight.
I believe the ComBridge.RegisterComDll does not really register the COM class in the system registry. I believe the runtime simply caches the clsid and filename and creates the class when the runtime is looking to instantiate the ComImport COM class.
We are able to use wince's win32 API to make operating system calls from the C++ code.
There does not seem to be any security restrictions that I have come across in using the operating system from native code. I will note that without the NETWORKING caps in the manifest, DNS would only resolve cached addresses, but the rest of the sockets worked fine. I do not believe this to be a security measure, but more of a missing initialization method I am not aware of.
We can return other COM interfaces created in our native code and talk to it by implementing the COM interop interfaces in C# ( InterfaceType(ComInterfaceType.InterfaceIsIUnknown))
Currently I have written a sockets library here: dl[dot]dropbox[dot][c][o][m]/u/4165054/PhoneNetworkingSample[dot]zip
I also have the workings of a file system library that I have not completed yet. I realize there is some OEM lib out there that does FS access, but I believe it to be important to homebrew that we make our own.
I recently have been looking into Direct3D 11 API support for the phone. I have successfully created a D3D11 device and passed it back to .NET code where I was able to execute some methods on it. A lot of work needs to be done here. First the device is almost useless if we cannot render to something. I believe I have been able to create a window, but not been able to actually show it. My next method of attack will be to find the hwnd Silverlight is rendering to, hook its WndProc and do our own rendering here.
If anyone else has any information on their hacking, please let us know! You can contact me on this board or on twitter [at-sign]jmorrill.
-Jer
Great work! I will definitely have a look at the sockets source code. This should open up a lot of possibilities for app developers
Sent from my HTC HD2 using XDA App
jmorrill said:
Hey guys,
[*]We are able to use wince's win32 API to make operating system calls from the C++ code.
[*]There does not seem to be any security restrictions that I have come across in using the operating system from native code. I will note that without the NETWORKING caps in the manifest, DNS would only resolve cached addresses, but the rest of the sockets worked fine. I do not believe this to be a security measure, but more of a missing initialization method I am not aware of.
[/LIST]
Click to expand...
Click to collapse
There definitely are security restrictions applied to the native code. This is what I think. Our applications are deployed in the Least Privilidged chamber (LPC) which has dynamic capabilities by the ones we specify when the application is deployed.
<Macro Id="LEAST_PRIVILEGE_CHAMBER_GROUP_NAME" Description="Least Privilege Chamber Group" Value="S-1-5-112-0-0X80" />
and are members of the:
<Account Id="S-1-5-112-0-0X70" Description="All public capability accounts are members of this group" FriendlyName="Public capabilities group" Type="Group" />
There are certain win32 API calls which are allowed but anything which could be used to compromise the OS is only allowed to be called from the TCB chamber.
<Macro Id="SYSTEM_CHAMBER_GROUP_NAME" Description="TCB Chamber Group" Value="S-1-5-112-0-0X00" />
<Macro Id="SYSTEM_USER_NAME" Description="TCB user SID" Value="S-1-5-112-0-0-1" />
For example, loading nativeinstallerhost.exe:
<Rule PriorityCategoryId="PRIORITY_HIGH" ResourceIri="/LOADERVERIFIER/ACCOUNT/(+)/ACCOUNT_CAN_LAUNCH/NONE/NONE/PRIMARY/WINDOWS/NATIVEINSTALLERHOST.EXE" SpeakerAcc ountId="S-1-5-112-0-0-1" Description="Only TCB can launch into this chamber">
I am guessing the LOADVERIFIER is doing this using the code signing certificates. If you check your apps they will be signed with a LPC certificate but if you look ones included in the ROM then they have TCB signing.
I can't see anything that would prevent you from doing socket stuff in the security policy (as you have found). However, it looks like you need:
<Macro Id="ELEVATED_RIGHTS_RESOURCE_GROUP_NAME" Description="Elevated Rights Resource Group SID" Value="S-1-5-112-0-0X14" />
To use raw sockets:
<Rule PriorityCategoryId="PRIORITY_STANDARD" ResourceIri="/RESOURCES/GLOBAL/WINSOCK/RAWSOCKET" SpeakerAccountId="S-1-5-112-0-0-1" Description="Acess to Winsock Ra w sockets">
<Authorize>
<!-- Match loaded from:
<Match AccountId="S-1-5-112-0-0X14" AuthorizationIds="GENERIC_ALL" />
</Authorize>
Would be useful to confirm that this is the case and that this policy is actually being applied
Yep, that reflects the same behavior in Windows on the desktop. Normal socket use is okay, raw requires admin.
Do we have a tutorial on how to create native COM classes?
Also, this url explains why you cannot copy/read some files from the \Windows directory, but can LoadLibrary on them (which is how I load d3d11.dll).
blogs.msdn.com/b/windowsmobile/archive/2007/12/29/why-can-t-i-copy-programs-out-of-windows.aspx
Sorry no tutorial on making COM objects. But basically just create a new smart device mfc dll in VS2008, then add a new ATL class to the project. I modified the COM interface/classes to inherit from IUnknown vs. IDispatch.
I guess I misspoke about the security restrictions. Really what I'm looking for, is to have about the same level of access to the device as any Windows Mobile application has, which is enough to suite most of my needs personally.
Ok, I've just created a native dll and call it from Silverlight.
Once you know what type of project to create it's quite easy. The longest part was to reinstall Visual Studio 2008.
Quick question: how do you handle passing string between native and managed? I have several ways in mid but they all seems very complicated.
(nico) said:
Ok, I've just created a native dll and call it from Silverlight.
Once you know what type of project to create it's quite easy. The longest part was to reinstall Visual Studio 2008.
Quick question: how do you handle passing string between native and managed? I have several ways in mid but they all seems very complicated.
Click to expand...
Click to collapse
Depends. Sometimes you can get away with StringBuilder. Or you can do a string outgument, and create the wchar_t in native code.
What I've done so far is creating wchar_t in native code, return an IntPtr to managed code, use Microsoft.Phone.InteropServices.Marshal.PtrToStringUni to get a string and then call a custom native method to delete my wchar_t array (didn't find a release method).
Seems a lot of work just to get a string...
(nico) said:
What I've done so far is creating wchar_t in native code, return an IntPtr to managed code, use Microsoft.Phone.InteropServices.Marshal.PtrToStringUni to get a string and then call a custom native method to delete my wchar_t array (didn't find a release method).
Seems a lot of work just to get a string...
Click to expand...
Click to collapse
Just stick it in a function, and be done with it. That way you only have to do it once. Don't worry about efficiency; unless it is in a tight loop, the string conversion isn't going to slow you down noticeably.
BTW, I got registry working and started working on a registry viewer.
However, I got access denied when trying to browser most of the node.
For example I can browse HKLM\System\State but not HKLM\System.
(nico) said:
What I've done so far is creating wchar_t in native code, return an IntPtr to managed code, use Microsoft.Phone.InteropServices.Marshal.PtrToStringUni to get a string and then call a custom native method to delete my wchar_t array (didn't find a release method).
Seems a lot of work just to get a string...
Click to expand...
Click to collapse
That isn't necessary at all. Simply define your managed class/interface with the MarshalAs attribute on your params. .NET will take care of the rest.
For example:
HRESULT MyFunction([in] LPWSTR param)
Would translate to:
UInt32 MyFunction(
[MarshalAs(UnmanagedType.LPWStr)]
[In] String param);
Thanks Rafael.
This is nice! How do I do the opposite? I need to create a string in unmanaged and use it from managed code Do I just have to use [out] instead of [in] in your example?
This is much simpler that my method
(nico) said:
Thanks Rafael.
This is nice! How do I do the opposite? I need to create a string in unmanaged and use it from managed code Do I just have to use [out] instead of [in] in your example?
Click to expand...
Click to collapse
Yep, it should match the direction indicated in your COM library's IDL. It basically just drives how Marshaller handles copying of memory, pinning, etc.
You guys are smarter the me at this, obviously, but is there a site where you share your code? because i'm smart enough to use existing code and make something happen..
jmorrill said:
I recently have been looking into Direct3D 11 API support for the phone. I have successfully created a D3D11 device and passed it back to .NET code where I was able to execute some methods on it. A lot of work needs to be done here. First the device is almost useless if we cannot render to something. I believe I have been able to create a window, but not been able to actually show it. My next method of attack will be to find the hwnd Silverlight is rendering to, hook its WndProc and do our own rendering here.
Click to expand...
Click to collapse
Have you checked out ZuneBoards? They've done some work in this area already with their OpenZDK, which looks similar to what we may need to do. Their method of breaking out of the CLI virtual machine is different than ours, but a lot of what they've done is what we want to do, too.
One thing that doesn't work are the typical WinCE graphics functions:
GetDC(NULL) ;
GetDesktopWindow();
LineTo();
GetClientRect();
That is they work, but the root window is empty! 0 wide and 0 tall. The drawing engine (unsurprisingly) is elsewhere.
ajhvdb said:
You guys are smarter the me at this, obviously, but is there a site where you share your code? because i'm smart enough to use existing code and make something happen..
Click to expand...
Click to collapse
Have you gotten anything to compile yet?
Check this one out: http://dl.dropbox.com/u/4165054/PhoneNetworkingSample.zip
And see if you can get it to compile (I would make it an attachment in this post but it's jmmorril's code). I've been using Visual Studio 2008 and the WinCE 6 refresh to compile the com dll: http://www.microsoft.com/downloads/...3A-A651-4745-88EF-3D48091A390B&displaylang=en
Then I copy the com dll over to my visual studio 2010 Windows Phone project, ready to be used. There are probably better ways, but you need to find out at least some way of doing it.
I've managed to create a basic Registry Viewer, readonly for the moment.
For now, I didn't manage to get access to root path, so the first 2 levels are hardcoded.
Download it here: (link removed, see below)
Edit:
Updated version here: http://bit.ly/eEZ0Uf
(nico) said:
I've managed to create a basic Registry Viewer, readonly for the moment.
For now, I didn't manage to get access to root path, so the first 2 levels are hardcoded.
Download it here: http://bit.ly/hOWLnI
Click to expand...
Click to collapse
wow man nice work , could you also make a file explorer ?
edit: here is a direct link http://www.xda-developers.ch/download/?a=d&i=7061084002

Heart Sensor/Passive Wellness sensor

Hello dear forum members,
As far as I know , moto360 doesn't have a sensor of type : TYPE_HEART_RATE, it's called passive wellness sensor.
The problem is that this wellness sensor is not giving me any data, as opposed to every other sensor that I've tried (like gravity, accelerometer...)
I've been waiting for more than 5 min but this sensor gives me data only when I start the app.
I've tried sdk20,sdk21,sdk22,sdk23 ... still no result I also have the android.permission.BODY_SENSORS in my manifest
Question : How to get the sensor working, what can I do?
Code:
package com.x.firstapp;
import android.app.Activity;
import android.os.Bundle;
import android.support.wearable.view.WatchViewStub;
import android.util.Log;
import android.widget.Toast;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.view.WindowManager;
public class MainActivity extends Activity implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mHeartSensor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
@Override
public void onLayoutInflated(WatchViewStub stub) {
}
});
// keep watch screen on
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Toast.makeText(getApplicationContext(), "Hi Oleg", Toast.LENGTH_LONG).show();
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mHeartSensor = mSensorManager.getDefaultSensor(65538); //wellness sensor
mSensorManager.registerListener(this, mHeartSensor, SensorManager.SENSOR_DELAY_NORMAL);
}
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == 65538) {
String msg = "" + (int) event.values[0];
Log.d("Main Activity", msg);
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
Log.d("Main Activity", "accuracy : " + accuracy + " sensor : " + sensor.getName());
}
@Override
protected void onStop() {
super.onStop();
mSensorManager.unregisterListener(this);
}
only output out of this "wellness" sensor (only when app starts) :
D/Main Activity: accuracy : 3 sensor : Wellness Passive Sensor
D/Main Activity: 0​
I have also posted this question on stack overflow, but so far - no success.
As soon as I get an answer here I'll spread it on stack overflow as well.
Thank you
Did you ever solve this? This might help.
What version of OS is your device running. For me, on my moto360 gen 1, now running 6.0.1, I have the permission in the manifest, but I MUST request it from the user using the new android M request mechanism, as BODY_SENSORS is labelled as a dangerous permission. Under debug, you can see all the sensors in the list if you get all sensors, but the iteration through them checks granted permissions.
Apparently, if the app is installed as a companion to an on phone app, it inherits the permissions from the device, so you don't need to ask, but a side-loaded app needs to ask.
Having said that, I clearly got a null for the HEART_RATE sensor until I'd requested user permissions. You at least get something.
dazbys said:
Did you ever solve this? This might help.
What version of OS is your device running. For me, on my moto360 gen 1, now running 6.0.1, I have the permission in the manifest, but I MUST request it from the user using the new android M request mechanism, as BODY_SENSORS is labelled as a dangerous permission. Under debug, you can see all the sensors in the list if you get all sensors, but the iteration through them checks granted permissions.
Apparently, if the app is installed as a companion to an on phone app, it inherits the permissions from the device, so you don't need to ask, but a side-loaded app needs to ask.
Having said that, I clearly got a null for the HEART_RATE sensor until I'd requested user permissions. You at least get something.
Click to expand...
Click to collapse
Hello,
It's a year later. I have a 2nd gen Moto 360 Sport. The android version is 6.01.
I am having what sounds like the same problem. Did you ever solve this?
I am using software which I basically copied from the web. When I run the software I get onAccuracyChanged events with accuracy values somewhere between one and three – mostly two and three.
But, I never get onSensorChanged events. I have the BODY_SENSORS permission in the manifest. And on the watch, if I go into Settings-Permissions, I see that the Sensors permission is enabled.
You mention "I MUST request it from the user using the new android M request mechanism". I'm not familiar with this mechanism. Could you explain a little more? I will also search for more information about this.
Do you have any more suggestions? Did you ever get yours working? It seems strange that I get the onAccuracyChanged events, but no onSensorChanged events. Could it possibly be something like the accuracy has to be four or greater in order to get onSensorChanged events?
Thanks,
Barry.
To answer my own question…
Of course it turned out I had a software error - I had assumed one of the event fields was an integer, it was not.
As was stated in the original answer: Be sure to have the BODY_SENSORS permission in the manifest (for both the phone and wearable). Since I am using SDK platform 20 rather than 23, I don't need to follow the android M procedure of requesting permission, but on the watch I did make sure the Settings-Permissions for my app had Sensors enabled.

[HELP] Can we use native libs in a module? Mine dies as soon as a lib is added.

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");
}
static {
System.loadLibrary("native-lib");
}
}
Have you tried capturing an ADB log _during the bootup_?
Xposed bugs in general are unfortunaley hard to identify and harder to fix, since the underlying code isn't well understood and/or maintained by many people.
Namnodorel said:
Have you tried capturing an ADB log _during the bootup_?
Xposed bugs in general are unfortunaley hard to identify and harder to fix, since the underlying code isn't well understood and/or maintained by many people.
Click to expand...
Click to collapse
Thanks for the response. I think that I have it figured out. The System.loadlibrary method looks for the native library within a path relative to the process that it is running within. The code within the apk ultimately does not run within that apk process, it runs within the xposed process. You therefore need to give xposed an absolute path to the library using the system.load method instead. Going to do some fiddling tonight and see if it works.
looxonline said:
Thanks for the response. I think that I have it figured out. The System.loadlibrary method looks for the native library within a path relative to the process that it is running within. The code within the apk ultimately does not run within that apk process, it runs within the xposed process. You therefore need to give xposed an absolute path to the library using the system.load method instead. Going to do some fiddling tonight and see if it works.
Click to expand...
Click to collapse
What about an alternative without using library we discussed earlier? Are you planning to test this as well?
If so, please let me know how it went.
C3C076 said:
What about an alternative without using library we discussed earlier? Are you planning to test this as well?
If so, please let me know how it went.
Click to expand...
Click to collapse
I didn't try it yet for two reasons.
1.) From the research I have done it seems as if my app would need the system INJECT_EVENTS permission in order to send keypress events outside of its own process. I cannot get this permission unless I sign my apk with the system cert that the ROM is compiled with. Maybe the method that you are using in the suggestion does not need this cert? Have you personally used this to inject key events across processes? I did see that you are getting the context of the system input service so maybe that solves this issue if the request appears to come from that PID...???
2.) The unit that I am working with has only two input devices and none of them have the keycodes I require. Does your method use a completely virtual device that is created on the fly? If so then it could work well without the need for me to create an HID input device.
I mostly was just on a role with the method that I was trying and I didn't want to turn back since I was so far down the road. I'm sure you understand how addictive certain challenges become and its quite fun to try to get them working even if they may not be the most optimal way.
In any case I managed to get the native library working last night and can successfully convince Android that I have a real HID keyboard plugged in and then send key events through that keyboard. Still not done though as there are a few hiccups that need solving. May still try your original suggestion. Thanks
looxonline said:
I didn't try it yet for two reasons.
1.) From the research I have done it seems as if my app would need the system INJECT_EVENTS permission in order to send keypress events outside of its own process. I cannot get this permission unless I sign my apk with the system cert that the ROM is compiled with. Maybe the method that you are using in the suggestion does not need this cert? Have you personally used this to inject key events across processes? I did see that you are getting the context of the system input service so maybe that solves this issue if the request appears to come from that PID...???
2.) The unit that I am working with has only two input devices and none of them have the keycodes I require. Does your method use a completely virtual device that is created on the fly? If so then it could work well without the need for me to create an HID input device.
I mostly was just on a role with the method that I was trying and I didn't want to turn back since I was so far down the road. I'm sure you understand how addictive certain challenges become and its quite fun to try to get them working even if they may not be the most optimal way.
In any case I managed to get the native library working last night and can successfully convince Android that I have a real HID keyboard plugged in and then send key events through that keyboard. Still not done though as there are a few hiccups that need solving. May still try your original suggestion. Thanks
Click to expand...
Click to collapse
I see.
1) Depends on in what process (package) your hooks are running within because permissions of this process apply of course, not the permissions you define in your module's manifest.
I am using key injecting method within "android" process (package) which means it works without me needing to worry about INJECT_EVENTS permission as "android" process already has it.
By the way, missing permissions are not of a big issue when developing with xposed as you can really do some magic with it.
E.g. I was adding some functionality to SystemUI that required some additional permissions that SystemUI typically lacks. So my module takes care of it.
https://github.com/GravityBox/Gravi...eco/pie/gravitybox/PermissionGranter.java#L75
C3C076 said:
I see.
1) Depends on in what process (package) your hooks are running within because permissions of this process apply of course, not the permissions you define in your module's manifest.
I am using key injecting method within "android" process (package) which means it works without me needing to worry about INJECT_EVENTS permission as "android" process already has it.
By the way, missing permissions are not of a big issue when developing with xposed as you can really do some magic with it.
E.g. I was adding some functionality to SystemUI that required some additional permissions that SystemUI typically lacks. So my module takes care of it.
https://github.com/GravityBox/Gravi...eco/pie/gravitybox/PermissionGranter.java#L75
Click to expand...
Click to collapse
Wow! I had no idea that you can use an xposed helper function to grant permissions to whatever process you are hooked within like that. That is VERY cool. Thanks so much for sharing

Categories

Resources