[Q] .9 png's and layouts.. ? - Xposed General

I'm having trouble replacing certain drawables, i've made a few work, some others just don't get replaced.
Here's a bit for a part that works.
Code:
package mjxl.xposed.cm11;
import android.content.res.XModuleResources;
import android.content.res.XResources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import de.robv.android.xposed.IXposedHookInitPackageResources;
import de.robv.android.xposed.IXposedHookZygoteInit;
import de.robv.android.xposed.callbacks.XC_InitPackageResources.InitPackageResourcesParam;
public class CM11transparentstuff implements IXposedHookZygoteInit, IXposedHookInitPackageResources {
private static String MODULE_PATH = null;
@Override
public void initZygote(StartupParam startupParam) throws Throwable {
MODULE_PATH = startupParam.modulePath;
}
@Override
public void handleInitPackageResources(InitPackageResourcesParam resparam) throws Throwable {
XModuleResources modRes = XModuleResources.createInstance(MODULE_PATH, resparam.res);
resparam.res.setReplacement("android", "drawable", "overscroll_edge", new XResources.DrawableLoader() {
@Override
public Drawable newDrawable(XResources res, int id) throws Throwable {
return new ColorDrawable(Color.TRANSPARENT);
}
});
}
}
Now i want to replace the notification_bg_normal.9.png and notification_bg_normal_pressed.9.png with my versions.
Technically i should be able to add a line like this:
resparam.res.setReplacement("android", "drawable", "notification_bg_normal", modRes.fwd(R.drawable.not_bg_normal));
And ofcourse add the drawable (notification_bg_normal_BLA.9.png) in my folder (xhdpi in my case)
Then i've tried to do it in a different class like this, which fails aswell. :/
Code:
package mjxl.xposed.cm11;
import android.content.res.XModuleResources;
import android.content.res.XResources;
import de.robv.android.xposed.IXposedHookZygoteInit;
public class CM11notifications implements IXposedHookZygoteInit {
public void initZygote(StartupParam startupParam) throws Throwable {
XModuleResources modRes = XModuleResources.createInstance(startupParam.modulePath, null);
XResources.setSystemWideReplacement("android", "drawable", "notification_bg", modRes.fwd(R.drawable.notification_bg)); <<<<--- notification_bg.xml (doesnt work)
XResources.setSystemWideReplacement("android", "drawable", "notification_bg_normal", modRes.fwd(R.drawable.not_bg_normal)); <<<<---- notification_bg_normal.9.png (also does not work)
XResources.setSystemWideReplacement("android", "drawable", "notification_bg_normal_pressed", modRes.fwd(R.drawable.not_bg_normal_pressed));
}
}
Any help ? What am i missing ?
Just fyi, i don't have any Java programming experience.
I followed the steps on Github wiki, and i've made SOME stuff work.. Why don't these work ?
/added:
I also made this, it's in 'framework-res' aswell, but this one DOES seem to work.
Code:
package mjxl.xposed.cm11;
import android.content.res.XResources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import de.robv.android.xposed.IXposedHookInitPackageResources;
import de.robv.android.xposed.IXposedHookZygoteInit;
import de.robv.android.xposed.callbacks.XC_InitPackageResources.InitPackageResourcesParam;
public class ts2 implements IXposedHookZygoteInit, IXposedHookInitPackageResources {
@Override
public void initZygote(StartupParam startupParam) throws Throwable {
}
@Override
public void handleInitPackageResources(InitPackageResourcesParam resparam) throws Throwable {
resparam.res.setReplacement("android", "drawable", "overscroll_glow", new XResources.DrawableLoader() {
@Override
public Drawable newDrawable(XResources res, int id) throws Throwable {
return new ColorDrawable(Color.TRANSPARENT);
}
});
resparam.res.setReplacement("android", "drawable", "overscroll_edge", new XResources.DrawableLoader() {
@Override
public Drawable newDrawable(XResources res, int id) throws Throwable {
return new ColorDrawable(Color.TRANSPARENT);
}
});
}
}

Trying to hook the layout where the notification_bg.xml is called as background.
Following the "Modifying Layouts" on the Github Tutorial i came up to this:
Code:
package mjxl.xposed.cm11;
import android.widget.TextView;
import de.robv.android.xposed.IXposedHookInitPackageResources;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.callbacks.XC_InitPackageResources.InitPackageResourcesParam;
import de.robv.android.xposed.callbacks.XC_LayoutInflated;
public class CM11notifications implements IXposedHookInitPackageResources {
public void handleInitPackageResources(InitPackageResourcesParam resparam) throws Throwable {
resparam.res.hookLayout("android", "layout", "notification_template_base", new XC_LayoutInflated() {
@Override
public void handleLayoutInflated(LayoutInflatedParam liparam) throws Throwable {
TextView notif = (TextView) liparam.view.findViewById(
liparam.res.getIdentifier("status_bar_latest_event_content", "id", "android"));
notif.setBackgroundResource(R.drawable.notification_bg);
XposedBridge.log("hey Ho");
}
});
resparam.res.hookLayout("android", "layout", "notification_template_big_base", new XC_LayoutInflated() {
@Override
public void handleLayoutInflated(LayoutInflatedParam liparam) throws Throwable {
TextView notif = (TextView) liparam.view.findViewById(
liparam.res.getIdentifier("status_bar_latest_event_content", "id", "android"));
notif.setBackgroundResource(R.drawable.notification_bg);
XposedBridge.log("hey Ho");
}
});
resparam.res.hookLayout("android", "layout", "notification_template_big_text", new XC_LayoutInflated() {
@Override
public void handleLayoutInflated(LayoutInflatedParam liparam) throws Throwable {
TextView notif = (TextView) liparam.view.findViewById(
liparam.res.getIdentifier("status_bar_latest_event_content", "id", "android"));
notif.setBackgroundResource(R.drawable.notification_bg);
XposedBridge.log("hey Ho");
}
});
resparam.res.hookLayout("android", "layout", "notification_template_inbox", new XC_LayoutInflated() {
@Override
public void handleLayoutInflated(LayoutInflatedParam liparam) throws Throwable {
TextView notif = (TextView) liparam.view.findViewById(
liparam.res.getIdentifier("status_bar_latest_event_content", "id", "android"));
notif.setBackgroundResource(R.drawable.notification_bg);
XposedBridge.log("hey Ho");
}
});
resparam.res.hookLayout("android", "layout", "notification_template_big_picture", new XC_LayoutInflated() {
@Override
public void handleLayoutInflated(LayoutInflatedParam liparam) throws Throwable {
TextView notif = (TextView) liparam.view.findViewById(
liparam.res.getIdentifier("status_bar_latest_event_content", "id", "android"));
notif.setBackgroundResource(R.drawable.notification_bg);
XposedBridge.log("hey Ho");
}
});
}
}
Am i making any mistakes here ? i don't see it :/ i've tried setBackground instead of BackgroundResource, but that doesn't get accepted.. Neither does setBackgroundDrawable
edit: in initZygote with systemwideLayout
Code:
package mjxl.xposed.cm11;
import android.content.res.XResources;
import android.widget.TextView;
import de.robv.android.xposed.IXposedHookZygoteInit;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.callbacks.XC_LayoutInflated;
public class not implements IXposedHookZygoteInit {
@Override
public void initZygote(IXposedHookZygoteInit.StartupParam startupParam) throws Throwable {
XResources.hookSystemWideLayout("android", "layout", "notification_template_base", new XC_LayoutInflated() {
@Override
public void handleLayoutInflated(LayoutInflatedParam liparam) throws Throwable {
TextView notif = (TextView) liparam.view.findViewById(
liparam.res.getIdentifier("status_bar_latest_event_content", "id", "android"));
notif.setBackgroundResource(R.drawable.mjxl_bg);
XposedBridge.log("hey Ho");
}
});
XResources.hookSystemWideLayout("android", "layout", "notification_template_big_picture", new XC_LayoutInflated() {
@Override
public void handleLayoutInflated(LayoutInflatedParam liparam) throws Throwable {
TextView notif = (TextView) liparam.view.findViewById(
liparam.res.getIdentifier("status_bar_latest_event_content", "id", "android"));
notif.setBackgroundResource(R.drawable.mjxl_bg);
XposedBridge.log("hey Ho");
}
});
XResources.hookSystemWideLayout("android", "layout", "notification_template_big_base", new XC_LayoutInflated() {
@Override
public void handleLayoutInflated(LayoutInflatedParam liparam) throws Throwable {
TextView notif = (TextView) liparam.view.findViewById(
liparam.res.getIdentifier("status_bar_latest_event_content", "id", "android"));
notif.setBackgroundResource(R.drawable.mjxl_bg);
XposedBridge.log("hey Ho");
}
});
XResources.hookSystemWideLayout("android", "layout", "notification_template_big_text", new XC_LayoutInflated() {
@Override
public void handleLayoutInflated(LayoutInflatedParam liparam) throws Throwable {
TextView notif = (TextView) liparam.view.findViewById(
liparam.res.getIdentifier("status_bar_latest_event_content", "id", "android"));
notif.setBackgroundResource(R.drawable.mjxl_bg);
XposedBridge.log("hey Ho");
}
});
XResources.hookSystemWideLayout("android", "layout", "notification_template_inbox", new XC_LayoutInflated() {
@Override
public void handleLayoutInflated(LayoutInflatedParam liparam) throws Throwable {
TextView notif = (TextView) liparam.view.findViewById(
liparam.res.getIdentifier("status_bar_latest_event_content", "id", "android"));
notif.setBackgroundResource(R.drawable.mjxl_bg);
XposedBridge.log("hey Ho");
}
});
}
}

How is it not working? Did you check the Xposed log to see if there are any errors there?
Did you verify the drawable you're trying to replace is also on your device (by e.g. decompiling framework-res.apk)? Some vendors remove/rename drawables that are present in AOSP and/or add their own.

I don't get any errors..
The files are there, I decompiled the files myself lol.
Also the log doesn't show either :/
This SHOULD work right?¿
(Added info, I'm working on CM11 sources)

It looks correct to me. Not sure why it wouldn't work. Maybe some of the drawables you're replacing aren't actually used where you think they're used?

GermainZ said:
It looks correct to me. Not sure why it wouldn't work. Maybe some of the drawables you're replacing aren't actually used where you think they're used?
Click to expand...
Click to collapse
I know that i need to address notification_bg.xml, which contains notification_bg_normal(_pressed).9.png (Blurred Sytem-UI by Serajr: clicky, PNG'sclicky)
I just want to replace the drawables. (either xml or the png's)
Another failed try:
Code:
package mjxl.xposed.cm11;
import android.content.res.XResources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import de.robv.android.xposed.IXposedHookZygoteInit;
import de.robv.android.xposed.XposedBridge;
public class notBG implements IXposedHookZygoteInit {
@Override
public void initZygote(StartupParam startupParam) throws Throwable {
XposedBridge.log("y0");
XResources.setSystemWideReplacement("android", "drawable", "notification_bg_normal", new XResources.DrawableLoader() {
@Override
public Drawable newDrawable(XResources res, int id) throws Throwable {
return new ColorDrawable(Color.TRANSPARENT);
}
});
XResources.setSystemWideReplacement("android", "drawable", "notification_bg_normal_pressed", new XResources.DrawableLoader() {
@Override
public Drawable newDrawable(XResources res, int id) throws Throwable {
return new ColorDrawable(Color.TRANSPARENT);
}
});
}
}
I will has continue.
Also i noticed, i'm replacing 'overscroll_edge' and 'overscroll_glow' (both framework-res package) in handleInitPackageResources while theoretically (according to the tutorials) it should be placed in initZygote

I did some more searching, think i might've found something. I'll keep you guys informed.
//edit: mehhh, im about to give up :/

Are your replacement 9 files 'built'?

PainToad said:
Are your replacement 9 files 'built'?
Click to expand...
Click to collapse
What exactly do you mean with 'built' ?
Also, even without the .9 files (by replacing it with a transparent 'newDrawable') it does not work :/

Related

[Q] Retrieve HTTP POST/GET & Response

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

android studio database

hi
Im new in android studio,
I´m trying to send to a db but it not works and i dont know why. when i click the button it does nothing.
can somebody help?
thanks
my code:
Code:
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
public class WebService extends Activity {
private EditText dni;
private EditText nombre;
private EditText telefono;
private EditText email;
private Button insertar;
private Button mostrar;
private ImageButton mas;
private ImageButton menos;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
setContentView(R.layout.fragment2);
dni=(EditText)findViewById(R.id.dni);
nombre=(EditText)findViewById(R.id.nombre);
telefono=(EditText)findViewById(R.id.telefono);
email=(EditText)findViewById(R.id.email);
insertar=(Button)findViewById(R.id.insertar);
insertar.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(!dni.getText().toString().trim().equalsIgnoreCase("")||
!nombre.getText().toString().trim().equalsIgnoreCase("")||
!telefono.getText().toString().trim().equalsIgnoreCase("")||
!email.getText().toString().trim().equalsIgnoreCase(""))
new Insertar(WebServiceExample.this).execute();
else
Toast.makeText(WebServiceExample.this, "Hay informaci�n por rellenar", Toast.LENGTH_LONG).show();
}
});
}
private boolean insertar(){
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
HttpPost httppost;
httpclient=new DefaultHttpClient();
httppost= new HttpPost("myhost");
nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("dni",dni.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("nombre",nombre.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("telefono",telefono.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("email",email.getText().toString().trim()));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
return true;
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
class Insertar extends AsyncTask<String,String,String>{
private Activity context;
Insertar(Activity context){
this.context=context;
}
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
if(insertar())
context.runOnUiThread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(context, "Persona insertada con �xito", Toast.LENGTH_LONG).show();
nombre.setText("");
dni.setText("");
telefono.setText("");
email.setText("");
}
});
else
context.runOnUiThread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(context, "Persona no insertada con �xito", Toast.LENGTH_LONG).show();
}
});
return null;
}
}
}

Adding a Spinner and posting the data to database [volley]

public class MainActivity extends Activity {
EditText name, phonenumber, address;
Button insert;
RequestQueue requestQueue;
String insertUrl = "localhosti/insertCustomer.php";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* CHECK INTERNET CONNECTION */
boolean mobileNwInfo = false;
ConnectivityManager conxMgr = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
try { mobileNwInfo = conxMgr.getActiveNetworkInfo().isConnected(); }
catch (NullPointerException e) { mobileNwInfo = false; }
if ( mobileNwInfo == false ) {
Toast.makeText(this, "No Network, please check your connection. ", Toast.LENGTH_LONG).show();
}
/* CHECK INTERNET CONNECTION PROCEDURE DONE */
name = (EditText) findViewById(R.id.editText);
phonenumber= (EditText) findViewById(R.id.editText2);
address = (EditText) findViewById(R.id.editText3);
insert = (Button) findViewById(R.id.insert);
requestQueue = Volley.newRequestQueue(getApplicationContext());
insert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final ProgressDialog pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Booking Service ....");
pd.show();
StringRequest request = new StringRequest(Request.Method.POST, insertUrl, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
pd.hide();
System.out.println(response.toString());
name.setText("");
phonenumber.setText("");
address.setText("");
Toast.makeText(getApplicationContext(), "Service successfully booked !!", Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
pd.hide();
Toast.makeText(getApplicationContext(), "Error: Please try again later.", Toast.LENGTH_LONG).show();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("name", name.getText().toString());
parameters.put("phonenumber", phonenumber.getText().toString());
parameters.put("address", address.getText().toString());
return parameters;
}
};
requestQueue.add(request);
}
});
}
}
Click to expand...
Click to collapse
how can i fetch the data from a spinner and post it to my db along with the current data ?

afterHookedMethod Variable assignment method

Code:
public class SuperHook implements IXposedHookLoadPackage, IXposedHookZygoteInit {
Config mConfig;
Gson mGson;
@Override
public void initZygote(StartupParam startupParam) throws Throwable {
mConfig = new Config();
mGson = new Gson();
}
@Override
public void handleLoadPackage(XC_LoadPackage.LoadPackageParam loadPackageParam) throws Throwable {
Log.d("SuperHook", "handleLoadPackage imei:" + mConfig.getmImei());
if (loadPackageParam.packageName.equals("cn.superscript.supertools")) {
Class<?> classSuperService = XposedHelpers.findClass(SuperService.class.getName(), loadPackageParam.classLoader);
XposedHelpers.findAndHookMethod(classSuperService, "onStartCommand", Intent.class, int.class, int.class, new XC_MethodHook() {
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
super.afterHookedMethod(param);
Intent intent = (Intent) param.args[0];
String json = intent.getStringExtra("json");
mConfig = mGson.fromJson(json, new TypeToken<Config>() {
}.getType());
Log.d("SuperHook", "onStartCommand: imei = " + mConfig.getmImei());
}
});
}
}
}
Log:
01-21 18:49:56.220 664-664/? D/SuperHook: handleLoadPackage imei:null
01-21 18:49:56.240 664-664/? D/SuperHook: onStartCommand: imei = 3333333
01-21 18:50:00.930 757-757/com.android.settings D/SuperHook: handleLoadPackage imei:null
why handleLoadPackage imei = null , onStartCommand: imei = 3333333 successful.
Please help me, thank you

class problem

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) {
}
});
}
}

Categories

Resources