I am trying to log HTTP requests and answers from single apps.
Code:
import java.net.URL;
import android.util.Log;
import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam;
public class Module implements IXposedHookLoadPackage {
@Override
public void handleLoadPackage(LoadPackageParam lpparam) throws Throwable {
if (lpparam.packageName.equals(Common.CLASSNAME)) {
final Class<?> httpUrlConnection = XposedHelpers.findClass(
"java.net.HttpURLConnection", lpparam.classLoader);
XposedBridge.hookAllConstructors(httpUrlConnection, new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
URL url = (URL)param.args[0];
Log.d("httpLogger", "call:"+url.toString());
}
});
}
}
}
So far i can retrieve the URLs but i do not know how to advance any further from here. Can you tell a smart way to approache the problem.
now that its been a while and i did not get any closer.. *bump*
Well, just follow API.
HttpResponse response = httpclient.execute(httppost);
Click to expand...
Click to collapse
So hook "execute" method from HttpClient class.
I have two problems with that.
The first one is:
HttpClient seems to be deprecated (http://developer.android.com/reference/org/apache/http/client/HttpClient.html). I am guessing a decent application would already use java.net.URL.openConnection().
But if we keep that point asside and assume the request we are trying to hook would be done with HttpClient execute i tryed to just see any of them done:
Code:
public class Module implements IXposedHookLoadPackage {
protected static final String HTTP_TAG = "myHttpLogger";
@Override
public void handleLoadPackage(LoadPackageParam lpparam) throws Throwable {
final Class<?> httpUrlConnection = findClass("org.apache.http.client.HttpClient", lpparam.classLoader);
findAndHookMethod(httpUrlConnection, "execute", HttpResponse.class, new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
Log.d(HTTP_TAG, "execute");
}
});
}
}
This trows an exception
Code:
java.lang.NoSuchMethodError: org.apache.http.client.HttpClient#execute(org.apache.http.HttpResponse)#exact
Can you tell me where i went wrong or show me a different approach?
You used HttpResponse.class as method's params. But it is not right.
HttpUriRequest.class is right parameter.
To covel all "execute" methods (I see many here http://developer.android.com/reference/org/apache/http/client/HttpClient.html), use XposedBridge.hookAllmethods API
Related
Hello,
I'm trying to create my own first xposed module after completing the tutorial successfully
What I'm trying to do is to hook the sendTextMessage from the class android.telephony.SmsManager
I've a modified ROM, so i added logs to this API and I see that when I'm sending SMS, i enter this API for sure.
I also know that the class loading and method getting works fine, but the before and after hooks are not called...
this is my module code:
Code:
package com.example.xpossedexample;
import static de.robv.android.xposed.XposedHelpers.findAndHookMethod;
import android.app.PendingIntent;
import android.graphics.Color;
import android.os.Message;
import android.widget.TextView;
import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XC_MethodHook.MethodHookParam;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam;
public class Smstry implements IXposedHookLoadPackage {
public void handleLoadPackage(final LoadPackageParam lpparam) throws Throwable {
// XposedBridge.log("handleLoadPackage:: Enter:: package name is:: " + lpparam.packageName);
if (!lpparam.packageName.equals("android")) {
// XposedBridge.log("not android package");
return;
}
XposedBridge.log("this is android package");
findAndHookMethod("android.telephony.SmsManager", lpparam.classLoader, "sendTextMessage",String.class,String.class,String.class,PendingIntent.class,PendingIntent.class, new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
XposedBridge.log("Enter:: before sendTextMessage hook");
}
});
}
}
any idea why the hooks are not called? any good way to debug this?
Thanks,
Gidi
Is the method being hooked correctly? Check your Xposed log and see if there are any errors. If not, then that method probably isn't getting called.
PS. You may want to use IXposedHookZygote/initZygote instead of IXposedHookLoadPackage/handleLoadPackage for "android".
GermainZ said:
Is the method being hooked correctly? Check your Xposed log and see if there are any errors. If not, then that method probably isn't getting called.
PS. You may want to use IXposedHookZygote/initZygote instead of IXposedHookLoadPackage/handleLoadPackage for "android".
Click to expand...
Click to collapse
Hi,
Thanks for your reply.
from the test i did, the method is being correctly hooked, there are no errors in the logs.
The method is definitely being called, I added logs to the original method, so I see that it's being called.
Since i need to hook this method, I'm not sure if IXposedHookZygote/initZygote will work here (at least from the examples i saw).
can I use IXposedHookZygote/initZygote to hook a method?
Thanks,
Gidi
Ok, I managed to hook my method as you suggested.
Now, I've a problem I don't understand.
in AOSP, there's a class called RIL (com.android.internal.telephony.RIL), when i try to hook it, and give it as com.android.internal.telephony.RIL.class, I get an error, the IDE doesn't recognize this class (only com.android.internal.util) can be found...
any idea?
Thanks,
Gidi
shnapsi said:
Ok, I managed to hook my method as you suggested.
Now, I've a problem I don't understand.
in AOSP, there's a class called RIL (com.android.internal.telephony.RIL), when i try to hook it, and give it as com.android.internal.telephony.RIL.class, I get an error, the IDE doesn't recognize this class (only com.android.internal.util) can be found...
any idea?
Thanks,
Gidi
Click to expand...
Click to collapse
Use "com.android.internal.telephony.RIL" (as a string).
GermainZ said:
Use "com.android.internal.telephony.RIL" (as a string).
Click to expand...
Click to collapse
Thanks, but then i need to give a classLoader as a parameter which i don't have when i'm using initZygote method.
Have i missed something?
shnapsi said:
Thanks, but then i need to give a classLoader as a parameter which i don't have when i'm using initZygote method.
Have i missed something?
Click to expand...
Click to collapse
I found the solution: i'm using the startupParam class's classloader
startupParam.getClass().getClassLoader(),
Thanks a lot!
If you're using initZygote the classloader argument can be null as well.
GermainZ said:
If you're using initZygote the classloader argument can be null as well.
Click to expand...
Click to collapse
So now I'm confused...
In that case, if i want to hook this specific method (or method located in packages that are not recognized, it's better to use handleLoadPackage and not initZygote?
No, just replace "startupParam.getClass().getClassLoader()" by "null".
GermainZ said:
No, just replace "startupParam.getClass().getClassLoader()" by "null".
Click to expand...
Click to collapse
Sorry, now i lost you completely
shnapsi said:
Sorry, now i lost you completely
Click to expand...
Click to collapse
Here's an example that should show the difference clearly. Both methods (initZygote and handleLoadPackage) will have the same effect (this is only true if you're hooking the "android" package; if you're hooking anything else, you must use handleLoadPackage).
Java:
public class XposedMod implements IXposedHookLoadPackage, IXposedHookZygoteInit {
[PLAIN]@Override[/PLAIN]
public void initZygote(StartupParam startupParam) throws Throwable {
XC_MethodHook myHook = new XC_MethodHook() {
[PLAIN]@Override[/PLAIN]
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
// Do something.
}
};
findAndHookMethod(SomeSdkClass.class, "methodName", myHook);
findAndHookMethod("SomeOtherClass", null , "methodName", myHook);
}
[PLAIN]@Override[/PLAIN]
public void handleLoadPackage(final LoadPackageParam lpparam) throws Throwable {
if (!lpparam.packageName.equals("android"))
return;
XC_MethodHook myHook = new XC_MethodHook() {
[PLAIN]@Override[/PLAIN]
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
// Do something.
}
};
findAndHookMethod(SomeSdkClass.class, "methodName", myHook);
findAndHookMethod("SomeOtherClass", lpparam.classLoader , "methodName", myHook);
}
}
GermainZ said:
Here's an example that should show the difference clearly. Both methods (initZygote and handleLoadPackage) will have the same effect (this is only true if you're hooking the "android" package; if you're hooking anything else, you must use handleLoadPackage).
Java:
public class XposedMod implements IXposedHookLoadPackage, IXposedHookZygoteInit {
[PLAIN]@Override[/PLAIN]
public void initZygote(StartupParam startupParam) throws Throwable {
XC_MethodHook myHook = new XC_MethodHook() {
[PLAIN]@Override[/PLAIN]
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
// Do something.
}
};
findAndHookMethod(SomeSdkClass.class, "methodName", myHook);
findAndHookMethod("SomeOtherClass", null , "methodName", myHook);
}
[PLAIN]@Override[/PLAIN]
public void handleLoadPackage(final LoadPackageParam lpparam) throws Throwable {
if (!lpparam.packageName.equals("android"))
return;
XC_MethodHook myHook = new XC_MethodHook() {
[PLAIN]@Override[/PLAIN]
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
// Do something.
}
};
findAndHookMethod(SomeSdkClass.class, "methodName", myHook);
findAndHookMethod("SomeOtherClass", lpparam.classLoader , "methodName", myHook);
}
}
Click to expand...
Click to collapse
Thanks a lot!!! :laugh:
I want to hook the constructor with xposed , and the code is as follows ,but there is some wrong.
Code:
XposedHelpers.findAndHookConstructor("java.io.File",
lpparam.classLoader, new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param)
throws Throwable {
}
@Override
protected void afterHookedMethod(MethodHookParam param)
throws Throwable {
System.out.println("file interception" + "-------------->"
+ param.args[0]);
}
});
Error content:
java.lang.NoSuchMethodError: java.io.File()#exact
Thanks
That's because there is no File() constructor. To hook e.g. File(String filename), you need to use:
Code:
XposedHelpers.findAndHookConstructor("java.io.File",
lpparam.classLoader, [COLOR="Red"][B]String.class, [/B][/COLOR]new XC_MethodHook() {
or simply
Code:
XposedHelpers.findAndHookConstructor(File.class, [COLOR="Red"][B]String.class, [/B][/COLOR]new XC_MethodHook() {
Be careful with such generic classes though, you can easily get lots of calls to it.
rovo89 said:
That's because there is no File() constructor. To hook e.g. File(String filename), you need to use:
Code:
XposedHelpers.findAndHookConstructor("java.io.File",
lpparam.classLoader, [COLOR="Red"][B]String.class, [/B][/COLOR]new XC_MethodHook() {
or simply
Code:
XposedHelpers.findAndHookConstructor(File.class, [COLOR="Red"][B]String.class, [/B][/COLOR]new XC_MethodHook() {
Be careful with such generic classes though, you can easily get lots of calls to it.
Click to expand...
Click to collapse
It works, thanks you very much .
Hi, I'm new development Xposed modules i have one problem in the hook process. My goal is to log the device imei by XposedBridge i tried by different forms but i can't have success . I all ready can change the imei but i can't do the correct log of the imei or put the value the correct value in a string anyone can help me? Thanksss Best regards... my code is this:
public class TelephoneManager implements IXposedHookLoadPackage {
@override
public void handleLoadPackage(LoadPackageParam lpparam) throws Throwable {
// TODO Auto-generated method stub
if(lpparam.packageName.equals("fca.up.identityspoofing")){
XposedHelpers.findAndHookMethod(TelephonyManager.class, "getDeviceId", new XC_MethodReplacement() {
protected Object replaceHookedMethod(MethodHookParam param) throws Throwable {
XposedBridge.log("in....");
String id_device = (String) param.thisObject.toString();
//TextView id = (TextView) param.thisObject;
//String device_id = id.getText().toString();
XposedBridge.log(id_device);
return "0000000";
}
});
Well you don't even need xposed to get imei, you can simply just do
Code:
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
// get IMEI
String imei = tm.getDeviceId();
If you still want to go with the xposed module way, the correct code would be
Code:
@override
public void handleLoadPackage(LoadPackageParam lpparam) throws Throwable {
if(lpparam.packageName.equals("fca.up.identityspoo fing")){
XposedHelpers.findAndHookMethod(TelephonyManager.class, lpparam.classLoader, "getDeviceId", new XC_MethodHook() {
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
String deviceId = (String) param.thisObject;
}
});
You hook after the original method has called so you can get the return value. You can still manipulate the result at this point if you want to do that.
Thanks for yoour help!
I tried that but does not result. In ;
if(lpparam.packageName.equals("fca.up.identityspoofing")){
XposedHelpers.findAndHookMethod(TelephonyManager.class, lpparam.classLoader, "getDeviceId", new XC_MethodHook() {
TelephonyManager.class needs to be a String. I tried "TelephonyManager.class" but Xposed can't find the class.
Then i tried with all all path to getDeviceId and not working too :
Code:
[user=439709]@override[/user]
public void handleLoadPackage(LoadPackageParam lpparam) throws Throwable {
if(lpparam.packageName.equals("fc.up.identityspoofing")){
XposedHelpers.findAndHookMethod("com.android.internal.telephony.PhoneSubInfo", lpparam.classLoader, "getDeviceId", new XC_MethodHook(){
[user=439709]@override[/user]
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
String deviceId = (String) param.thisObject;
XposedBridge.log(deviceId);
}
});
}
The logcat error's are :
W/System.err( 4247): at de.robv.android.xposed.XposedBridge.invokeOriginalMethodNative(Native Method)
W/System.err( 4247): at de.robv.android.xposed.XposedBridge.handleHookedMethod(XposedBridge.java:631)
W/System.err( 4247): at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
W/System.err( 4247): at de.robv.android.xposed.XposedBridge.invokeOriginalMethodNative(Native Method)
W/System.err( 4247): at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
Do you have an idea of what may be happening? Best Regards
[QUOTE="sokie, post: 66189459, member: 2502626"]Well you don't even need xposed to get imei, you can simply just do
[CODE]
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
// get IMEI
String imei = tm.getDeviceId();
If you still want to go with the xposed module way, the correct code would be
Code:
[user=439709]@override[/user]
public void handleLoadPackage(LoadPackageParam lpparam) throws Throwable {
if(lpparam.packageName.equals("fca.up.identityspoofing")){
XposedHelpers.findAndHookMethod(TelephonyManager.class, lpparam.classLoader, "getDeviceId", new XC_MethodHook() {
[user=439709]@override[/user]
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
String deviceId = (String) param.thisObject;
}
});
You hook after the original method has called so you can get the return value. You can still manipulate the result at this point if you want to do that.[/QUOTE]
jmarques00 said:
Do you have an idea of what may be happening? Best Regards
Click to expand...
Click to collapse
Yeah, sorry wrote this quickly.
Code:
@override
public void handleLoadPackage(LoadPackageParam lpparam) throws Throwable {
if(lpparam.packageName.equals("android.telephony")){
XposedHelpers.findAndHookMethod("android.telephony.TelephonyManager", lpparam.classLoader, "getDeviceId", new XC_MethodHook() {
@override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
super.afterHookedMethod(param);
String deviceId = (String) param.getResult();
}
});
This will work.
Also I take for granted you know your device and Android ver and know this method gets called.
Because depending on your android version there are other classes that take care of imei like:
- com.android.internal.telephony.PhoneSubInfo getDeviceId
- com.android.internal.telephony.gsm.GSMPhone getDeviceId
- com.android.internal.telephony.PhoneProxy getDeviceId
- android.telephony.TelephonyManager getImei
Cheers
Thanks for yoour help!
Thanks for your feedback i allready test the new code but unfortunately don't work too ! If the new code works all packages that require the emei this emei changed right? For that we don't need to implement IXposedHookZygoteInit instead IXposedHookLoadPackage? The code break in the frist if condition when lpparam.packageName.equals("android.telephony") :/ .
package fc.up.identityspoofing;
import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam;
public class TelephoneManager implements IXposedHookLoadPackage {
private static final String TAG = "Xposed";
@override
public void handleLoadPackage(LoadPackageParam lpparam) throws Throwable {
XposedBridge.log("aaaaa");
if(lpparam.packageName.equals("android.telephony")){
XposedBridge.log("bbbbb");
//XposedHelpers.findAndHookMethod("com.android.internal.telephony.PhoneSubInfo", lpparam.classLoader, "getDeviceId", new XC_MethodHook() {
XposedHelpers.findAndHookMethod("android.telephony.TelephonyManager", lpparam.classLoader, "getDeviceId", new XC_MethodHook() {
@override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
XposedBridge.log("cccc");
super.afterHookedMethod(param);
String deviceId = (String) param.getResult();
XposedBridge.log(deviceId);
}
});
}
}
}
What doesn't work? How are you testing?
As said earlier, depending on your android version, the above code if you go to Settings ->About Phone -> Status -> IMEI Information you will hit the log ( if not and you're in europe you could try com.android.internal.telephony.gsm.GSMPhone ).
Also keep in mind that changing IMEI will probably work only for apps requesting it and the OS, network carriers get that info directly from the sim afaik.
EDIT: this is an example complete app that should work http://pastebin.com/uPjY47VR
I'm testing in in 2 modes my phone version 4.2.2 and with genymotion with 4.2.2 version too. My frist goal is to this package when wants to receive the device_id the device_id revived must be fake and i want to log the original one. Thanks for your help
sokie said:
What doesn't work? How are you testing?
As said earlier, depending on your android version, the above code if you go to Settings ->About Phone -> Status -> IMEI Information you will hit the log ( if not and you're in europe you could try com.android.internal.telephony.gsm.GSMPhone ).
Also keep in mind that changing IMEI will probably work only for apps requesting it and the OS, network carriers get that info directly from the sim afaik.
Click to expand...
Click to collapse
jmarques00 said:
I'm testing in in 2 modes my phone version 4.2.2 and with genymotion with 4.2.2 version too. My frist goal is to this package when wants to receive the device_id the device_id revived must be fake and i want to log the original one. Thanks for your help
Click to expand...
Click to collapse
Read my last edit:
EDIT: this is an example complete app that should work http://pastebin.com/uPjY47VR
Thanks for all sokie it really works fine in my mobile phone !!!
sokie said:
Read my last edit:
EDIT: this is an example complete app that should work http://pastebin.com/uPjY47VR
Click to expand...
Click to collapse
I am on pie so obviously its EdXposed running.
I want to hook a method which is like
Code:
public void setSensorBrightness(int var1) {
Log.d(TAG, "setSensorBrightness: " + var1);
AODCommonSettingsUtils.setBrightnessSettingValue(var1);
this.mSensorBrightness = var1;
}
this original method is located in class "com.samsung.android.app.aodservice.manager.BrightnessManager" and a package name is "com.samsung.android.app.aodservice"
I use reflection as suggested in tutorial otherwise it throws no class found exception.
My code is
Code:
@Override
public void handleLoadPackage(final LoadPackageParam lpparam) throws Throwable
{
if (!lpparam.packageName.equals("com.samsung.android.app.aodservice"))
return;
XposedHelpers.findAndHookMethod(
"com.samsung.android.app.aodservice.manager.BrightnessManager",
lpparam.classLoader,
"setSensorBrightness",
"int",
new MethodHook());
}
protected static class MethodHook extends XC_MethodHook
{
@Override
protected void beforeHookedMethod(MethodHookParam param)
throws Throwable
{
int x =3;
param.args[0]=x;
Log.d("Brightness_hack :", "works");
}
@Override
public boolean equals(Object o)
{
if (o instanceof MethodHook)
{
return true;
}
return super.equals(o);
}
@Override
public int hashCode()
{
return ~MethodHook.class.hashCode() ^ 0xdeadbeef;
}
}
Now my problem is its tooooooo slow hooks in like 15-20 mins and returns no result.
Am I missing something???
I'm having a class Mqtt with this code as below :
Code:
package com.example.myhome;
import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import androidx.appcompat.app.AlertDialog;
import java.io.UnsupportedEncodingException;
public class Mqtt {
public MqttAndroidClient mqttAndroidClient;
final String serverUri = "tcp://***";
final String clientId = "***";
final String username = "***";
final String password = "***";
public Mqtt(Context context) {
mqttAndroidClient = new MqttAndroidClient(context, serverUri, clientId);
mqttAndroidClient.setCallback(new MqttCallback() {
//@Override
public void connectComplete(boolean b, String s) {
Log.w("mqtt", s);
}
@Override
public void connectionLost(Throwable throwable) {
}
@Override
public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
Log.w("Mqtt", mqttMessage.toString());
}
@Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
}
});
connect();
}
public void setCallback(MqttCallback callback) {
mqttAndroidClient.setCallback(callback);
}
private void connect() {
MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
//mqttConnectOptions.setAutomaticReconnect(true);
mqttConnectOptions.setCleanSession(false);
mqttConnectOptions.setUserName(username);
mqttConnectOptions.setPassword(password.toCharArray());
try {
mqttAndroidClient.connect(mqttConnectOptions, null, new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
//DisconnectedBufferOptions disconnectedBufferOptions = new DisconnectedBufferOptions();
// disconnectedBufferOptions.setBufferEnabled(true);
// disconnectedBufferOptions.setBufferSize(100);
//disconnectedBufferOptions.setPersistBuffer(false);
//disconnectedBufferOptions.setDeleteOldestMessages(false);
// mqttAndroidClient.setBufferOpts(disconnectedBufferOptions);
subscribeToTopic("esp/test");
//publishToTopic("esp/test","POPdd");
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.w("Mqtt", "Failed to connect to: " + serverUri + exception.toString());
}
});
} catch (MqttException ex) {
ex.printStackTrace();
}
}
private void subscribeToTopic(String Topic) {
try {
mqttAndroidClient.subscribe(Topic, 0, null, new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.w("Mqtt", "Subscribed!");
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.w("Mqtt", "Subscribed fail!");
}
});
} catch (MqttException ex) {
System.err.println("Exceptionst subscribed");
ex.printStackTrace();
}
}
public void publishToTopic(MqttAndroidClient client,String Topic,String MessageForTopic) {
String payload = MessageForTopic ;
byte[] encodedPayload = new byte[0];
try {
encodedPayload = payload.getBytes("UTF-8");
MqttMessage message = new MqttMessage(encodedPayload);
client.publish(Topic, message,null,new IMqttActionListener() {
// @Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.w("Mqtt", "Published!");
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.w("Mqtt", "Published fail!");
}
});
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (MqttPersistenceException e) {
e.printStackTrace();
} catch (MqttException e) {
e.printStackTrace();
}
}
}
i have also a class Hoofdmenu (code below) with a layout. Here i want to send a message into the mqtt
=> MqttCommunicatie.publishToTopic(MqttCommunicatie.mqttAndroidClient,"esp/test","Message MQTT");
when i publishToTopic after the subscribe into class Mqtt the i receive the message when i ask into the class Hoofdmenu it doens't work
what do i do wrong ? Or wht can i do to to it work ?
now receive the message "MyHome is stopped Open app again"
Code:
package com.example.myhome;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import com.example.myhome.HoofdmenuTabs.PagerAdapter;
import com.google.android.material.tabs.TabLayout;
import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
import java.io.UnsupportedEncodingException;
public class Hoofdmenu extends AppCompatActivity {
public Mqtt MqttCommunicatie;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hoofdmenu);
TabLayout tabMenu = (TabLayout) findViewById(R.id.tabMenu);
final ViewPager viewPager = (ViewPager) findViewById(R.id.tabpager);
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabMenu.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabMenu));
tabMenu.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
startMqtt();
MqttCommunicatie.publishToTopic(MqttCommunicatie.mqttAndroidClient,"esp/test","Message MQTT");
}
private void startMqtt(){
MqttCommunicatie = new Mqtt(getApplicationContext());
MqttCommunicatie.setCallback(new MqttCallback() {
//@Override
public void connectComplete(boolean b, String s) {
}
@Override
public void connectionLost(Throwable throwable) {
}
@Override
public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
Log.w("Debug", mqttMessage.toString());
//dataReceived.setText(mqttMessage.toString());
}
@Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
}
});
}
}