how to hook function with xposed? - java

for example,i decompile the app and want to hook function with xposed,how can i do that?
package com.my.app;
public class myClass
{
public static int myFunction()
{
//do something inside
}
}
how to hook "myFunction" with xposed?

Have you tried to simply adapt the available examples to your class and method?
XposedHelpers.findAndHookMethod("com.my.app.myClass", lpparam.classLoader, "myFunction", new XC_MethodHook() {
#Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
XposedBridge.log("before myFunction()");
}
#Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
XposedBridge.log("after myFunction()");
}
);

Related

Guava ListenableFuture fan-in callback on exceptions

I have been looking around and haven't been able to find a clear documentation on how to work with ListenableFuture and exceptions. So I would like to get a verification on the following statements or answers to questions:
Question 1:
Would the following setup invoke the onFailure callback?
public int doWork() throws SomeException {
return doActualWork(); // Let's say this end up throwing SomeException
}
public ListenableFuture<Integer> queueWork() {
executorService.submit( () -> doWork());
}
public static void main(String[] args) {
// bunch of setup
Futures.addCallback(queueWork(),
new FutureCallback<Integer>() {
#Override
public void onSuccess(Integer result) {}
#Override
public void onFailure(Throwable t) {
// Should I expect SomeException will end up here?
}
}
}
Question 2: Same setup as above exception I have multiple futures with Futures.successfulAsList(), when should onFailure be invoked?
public int doWork() throws SomeException {
return doActualWork(); // Let's say this end up throwing SomeException
}
public ListenableFuture<Integer> queueWork() {
executorService.submit( () -> doWork());
}
public static void main(String[] args) {
// bunch of setup
ListenerableFuture<List<Integer>> manyWorks = Futures.successfulAsList(queueWork(), queueWork(), queueWork());
Futures.addCallback(manyWorks(),
new FutureCallback<Integer>() {
#Override
public void onSuccess(Integer result) {
// I get if some tasks fails, its result is null ... but what if it throws exception?
}
#Override
public void onFailure(Throwable t) {
// If the 2nd task throws SomeException, will it end up here??
}
}
}
I think I tested question 2 and it end up in onSuccess with result being null .... what should I do to make it go to onFailure ?

Unit Testing In Network With Using Volley in Android

I am trying to test functions from my Presenter Class. In below, I can reach getSomeThing() function however, I cannot reach the getData() and getError() functions.
Volley functions are not working in unit tests. Further help would be highly appreciated as I am struggling with this for over a week.
Below is my Presenter Class, Presenter Listener and Test Function.
my Presenter Class:
public abstract class SomePresenter implements BasePresenterListener {
private static final String sTAG = SomePresenter.class.getSimpleName();
private Context context;
private Integer testInteger;
protected SomePresenter(Context context, Integer testInteger) {
this.context = context;
this.testInteger = testInteger;
onResponse();
}
#Override
public void onResponse() {
try {
Thread.sleep(1000);
getSomeThing();
} catch (InterruptedException e) {
e.printStackTrace();
}
final GetRequest<SomeResponse> someResponseRequest =
ApiRequests.getSomeResponse(
new Response.Listener<SomeResponse>() {
#Override
public void onResponse(SomeResponse response) {
getData(response);
}
}
,
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setMessage(Constant.NETWORK_ERROR);
getError(errorResponse);
}
}
);
NetworkInstance.addRequest(context, poiResponseGetRequest, sTAG);
}
public static void cancelRequest(Context context) {
NetworkInstance.cancelAllRequests(context, sTAG);
}
protected abstract void getSomeThing();
protected abstract void getData(SomeResponse response);
protected abstract void getError(ErrorResponse response);
}
my BasePresenter Class:
public interface BasePresenterListener {
void onResponse();
}
my Unit Test Function:
#Test
public void test() throws InterruptedException {
new SomePresenter(mockContext, 107){
#Override
protected void getData(PoiResponse response) {
SomeLogger.debug("getData works");//this is not called.
}
#Override
protected void getSomeThing() {
SomeLogger.debug("getSomeThing works!");//this is called.
}
#Override
protected void getError(ErrorResponse response) {
SomeLogger.debug("ErrorResponse works!"); //this is not called.
}
};
}
I have looked below links none of them solved my problem.
Unit testing a network response. Works when debugging, not when actually running
Android Unit test with Volley
In my case is I can reach the getSomething() function from unit test but I cannot reach the getData() nor getError() functions because Volley does not seem to work in unit tests.
All, getSomething(), getData(), getError() functions are callback functions, I can reach the getSomeThing() function but I cannot reach the getData() and getError() functions.

getThis() trick and ClassCastException

I've been wondering about the getThis() trick, and the alternative of the unsafe cast from a self-bounded type to its type parameter.
public abstract class SelfBound<T extends SelfBound<T>> {
protected abstract T getThis();
public void doSomething(T instance) { ... }
public final void doSomethingWithThis() { doSomething(getThis()); }
public final void doSomethingWithThisUnsafe() { doSomething((T) this); }
}
Is it possible to subclass SelfBound such that doSomethingWithThisUnsafe() throws a ClassCastException? (Is it possible to do this without subclassing SelfBound?)
Surely it's possible to have ClassCastException with subclassing. Here's a simple example:
public abstract class SelfBound<T extends SelfBound<T>> {
protected abstract T getThis();
public void doSomething(T instance) { }
public final void doSomethingWithThis() { doSomething(getThis()); }
public final void doSomethingWithThisUnsafe() { doSomething((T) this); }
public static class A extends SelfBound<A> {
#Override
protected A getThis() {
return this;
}
}
public static class B extends SelfBound<A> {
#Override
public void doSomething(A instance) {
super.doSomething(instance);
}
#Override
protected A getThis() {
return null;
}
}
public static void main(String[] args) {
new B().doSomethingWithThisUnsafe();
}
}
Output:
Exception in thread "main" java.lang.ClassCastException: SelfBound$B cannot be cast to SelfBound$A
at SelfBound$B.doSomething(SelfBound.java:1)
at SelfBound.doSomethingWithThisUnsafe(SelfBound.java:6)
at SelfBound.main(SelfBound.java:28)
It's not so clear what do you mean by "without subclassing SelfBound". As SelfBound is an abstract class, you cannot call its methods without subclassing it, thus you cannot have any exception when calling its methods.

How to reimplement Java listeners with anonymous classes in C#

I am trying to replicate my Java code in C# and I wish to know how can I replicate this Java functionality in C#.
Util.java
public class Util
{
public void function(String s, final SetAvailabilityStatusListener setStatusListener)
{
// ....
}
public static interface SetAvailabilityStatusListener {
public void setAvailabilityStatus(Status status);
}
}
Activity.java
public class Activity
{
public void anotherFunction()
{
util.function("name", new SetAvailabilityStatus()
{
#Override
public void setAvailabilityStatus(Status status) {
loginSetAvailabilityStatus(status);
}
}
}
}
Use delegates. They are used in C# instead of Java anonymous classes that implement interfaces.
public class Util
{
public void Function(String s, Action<Status> setStatusListener)
{
// ....
setStatusListener("myStatus");
}
}
public class Activity
{
private Util util = new Util();
public void AnotherFunction()
{
util.Function("name", status => LoginSetAvailabilityStatus(status));
}
public void LoginSetAvailabilityStatus(string status){
//do something with status
}
}
I was unable to find suitable duplicate, so:
1. C# does not have anonymous classes like Java does, but no one stops you from creating needed listener classes manually
public class Util
{
public void Function(String s, ISetAvailabilityStatusListener setStatusListener)
{
// ....
}
public interface ISetAvailabilityStatusListener {
public void SetAvailabilityStatus(Status status);
}
}
public class Activity
{
private class MySetAvailabilityStatusListener: Util.ISetAvailabilityStatusListener
{
public void SetAvailabilityStatus(Status status)
{
// do your handling, but nested classes have some differences with anonymous Java classes, so it may require additional infrastructure.
}
}
public void AnotherFunction()
{
utilObj.Function("name",
new MySetAvailabilityStatusListener())
}
}
It is so-called observer design pattern (just without unregistration method!!).
2. As it has been already suggested by #AndreySarafanov you can use Action Delegates and lambda expressions:
public class Util
{
public void Function(String s, Action<Status> statusChangeListener)
{
// ....
}
}
public class Activity
{
public void AnotherFunction()
{
utilObj.Function("name",
(status) =>
{
loginSetAvailabilityStatus(status);
}
}
}
3. C# has another more simple mechanism to deal with event-handling(subsrciption) mechanics - events and delegates
public class StatusEventArgs : EventArgs
{
//...
}
public class Util
{
public void SomeFunction()
{
// ....
if (this.OnAvailabilityChanged != null)
OnAvailabilityChanged(this, new StatusEventArgs(status));
}
public event EventHandler<StatusEventArgs> OnAvailabilityChanged
}
public class Activity
{
public void AvailabilityStatusChangedHandler(object sender, EventArgs<Status> eventArgs)
{
}
public void AnotherFunction()
{
utilObj.OnAvailabilityChanged += this.AvailabilityStatusChangedHandler;
}
}
It does not allow you to associate the name property with event handler, well, you can overcome it with special registration method, but it will reduce the usability of events, so you should probably stick with another solution.

Abstract Class, OOP Design Pattern

I have an abstract class called "Operation"
and this class has an abstract method called "Prepare".
public abstract class Operation {
public abstract void prepare() throws Exception;
public abstract void run() throws Exception;
// other stuff here that's not abstract
public void printHelloWorld() {
System.out.println("Hello World!");
}
}
The only issue is that some things that are "Operation" (
some classes that extends Operation ) need arguments to prepare ( some
need ints, some need String, some need more complex data types..so it's not always an int )
public class Teleportation extends Operation {
#Override
public void prepare(int capacityRequired ) throws Exception {
// do stuff
}
#Override
public void run() throws Exception {
}
}
What OOP pattern do I use to achieve this
and how do I set up this code ?
EDIT :
Ideally, I want to prepare and run operations like this :
for (Operation operation : operations ) {
operation.prepare();
operation.run();
}
Assuming I use this solution :
public class Teleportation extends Operation {
private int cReq;
public void setCapacityRequired(int cReq) {
this.cReq = cReq;
}
#Override
public void prepare() throws Exception {
// I can do the preparation stuff
// since I have access to cReq here
}
#Override
public void run() throws Exception {
}
}
Then - I wonder if it's possible to avoid this :
for (Operation operation : operations ) {
if (operation.getClass().isInstanceOf(Teleporation.class)) {
((Teleporation)operation).setCapacityRequired( 5 );
}
operation.prepare();
operation.run();
}
I would recommend having an additional constructor where you can add the necessary data that the implementation requires and store it in fields for the class implementation.
For your example:
public class Teleportation extends Operation {
private final int capacityRequired;
public Teleportation(int capacityRequired) {
this.capacityRequired = capacityRequired;
}
public void prepare() throws Exception {
// do stuff using the capacityRequired field...
}
}
This approach applies for more complex parameters as well.
The very first thing to do here is to override the abstract class operation and overload with your capacity.
public class Teleportation extends Operation {
public void prepare() throws Exception {
prepare(0);
}
public void prepare(int capacityRequired) throws Exception {
//do stuff
}
}
And remember the KISS and YAGNI statements, there is no need to use design patterns anywhere in your code, just where they makes things simpler.
You either need to expand the abstract class to include two method signatures or change the signature to take a varargs int parameter:
public abstract class Operation {
public abstract void prepare(int... args) throws Exception;
}
You can use generic class for your operation class:
public abstract class Operation<T>
{
private T operationModel;
public Operation(T operationModel)
{
super();
this.operationModel = operationModel;
}
public abstract void prepare() throws Exception;
public abstract void run() throws Exception;
public T getOperationModel()
{
return operationModel;
}
}
Then for concrete classes, extend it with proper parameter-type (You can have a specific class for each operation):
public class TeleOperation extends Operation<TeleOperationModel>
{
public TeleOperation(TeleOperationModel operationModel)
{
super(operationModel);
}
#Override
public void prepare() throws Exception
{
TeleOperationModel teleOperationModel = getOperationModel();
//...
}
#Override
public void run() throws Exception
{
}
}
public class TeleOperationModel
{
private int capacity;
....
}
and:
public class MicroOperation extends Operation<MicroOperationModel>
{
public MicroOperation(MicroOperationModel operationModel)
{
super(operationModel);
}
#Override
public void prepare() throws Exception
{
MicroOperationModel microOperationModel = getOperationModel();
//...
}
#Override
public void run() throws Exception
{
}
}
public class MicroOperationModel
{
private int x;
private int y;
private int z;
....
}

Categories

Resources