Unable to Connect MQTT Paho client in android higher version - mqtt

I am not able to connect to Mqtt paho client in android high version. while it is working fine for API less than 22 and able to publish and subscribe.here is my code
build.gradle
repositories {
maven {
url "https://repo.eclipse.org/content/repositories/paho-releases/"
}
dependencies {
compile('org.eclipse.paho:org.eclipse.paho.android.service:1.0.2') {
exclude module: 'support-v4'
}
MainviewActivity
String clientId = MqttClient.generateClientId();
client =
new MqttAndroidClient(this.getApplicationContext(), "url",
clientId);
MqttConnectOptions authen = new MqttConnectOptions();
authen.setKeepAliveInterval(200);
try {
if(client.isConnected()){
Log.e(TAG, "already connected");
}else {
Log.e(TAG, "connecting.........");
token = client.connect(authen);
}
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
// We are connected
Log.e(TAG, "onSuccess");
status.setText("Connected");
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
// Something went wrong e.g. connection timeout or firewall problems
Log.e(TAG, "onFailure");
status.setText("Not Connected");
}
});
} catch (MqttException e) {
Log.e(TAG, "Not Connected");
e.printStackTrace();
}
AndroidManifest.xml
<service android:name="org.eclipse.paho.android.service.MqttService" >
</service>

Related

how to connect TCP Socket server client with authentication in Dart

I have a java and .Net solution, but now i need to implement in Dart please help me out.
This is may java source
private Handler handler;
private int iCounter =1;
public StartQuickClient(int InstanceId)
{
try
{
handler = MarketData.GetInstance();
handler.setEventHandler(this);
handler.setAddress("122.184.137.44");
handler.setPort(9898);
handler.setUserCredentials("PREM", "xxxxx");
if (handler.connect())
{
System.out.println("Connect initiated "+ InstanceId);
}
else
{
System.out.println("Connect failed ");
}
}
catch (Exception e)
{
}
}
public static void main(String[] args) {
Random rnd = new Random();
int InstanceId = rnd.nextInt(9999);
StartQuickClient startQuickClient = new StartQuickClient(InstanceId);
}
This is the connect method:
public boolean connect()
{
try {
if (quickEvent == null) {
throw new Exception("No event handler is set, will not initiate the connection");
}
if (configuration.SERVER_ADDRESS == null) {
throw new Exception("Blank Server Address");
}
if (configuration.SERVER_PORT <= 0) {
throw new Exception("Blank Server Port");
}
tcpConnection = new TcpConnection(this, configuration);
if (isNewVersionAuthentication) {
tcpConnection.enableNewversionAuthentication();
}
tcpConnection.connect();
} catch (Exception e) {
e.printStackTrace();
mLog.error("No event handler is set and Blank Server Address,Port will not initiate the connection :" + e.getMessage());
return false;
}
return true;
}
please help me out if any one knows, i am new for dart,need any plug or how to do

MQTT subscribe not working in Android

I am trying to get a message from the MQTT Broker using the Android service, but it does not work.
The library used is the Paho MQTT library, and the source code is as follows.
final MqttConnectOptions hIoTConnectionOptions = new MqttConnectOptions();
hIoTConnectionOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1);
hIoTConnectionOptions.setAutomaticReconnect(true);
hIoTConnectionOptions.setCleanSession(false);`
try {
hIoTAndroid = new MqttClient(ip_addr, clientID, new MemoryPersistence());
IMqttToken conToken = hIoTAndroid.connectWithResult(hIoTConnectionOptions);
hIoTAndroid.setCallback(MqttMessagingService.this);
conToken.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.d(TAG, "onSuccess");
hIoTAndroid.setCallback(MqttMessagingService.this);
try {
IMqttToken subToken = hIoTAndroid.subscribeWithResponse(subtopic, 1);
subToken.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.i(TAG, "Successfully subscribe to: " + subtopic);
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.d(TAG, "Couldn't subscribe to: " + subtopic);
}
});
} catch (MqttException | NullPointerException ex) {
ex.printStackTrace();
}
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.d(TAG, "Failed Connection");
}
});
} catch (MqttException ex) {
Log.d(getClass().getCanonicalName(), "Connection attempt failed with reason code = " + ex.getReasonCode() + ":" + ex.getCause());
}
#Override
public void connectComplete(boolean reconnect, String serverURI) {
Log.d(TAG, "Connection is established....");
}
#Override
public void connectionLost(Throwable cause) {
Log.d(TAG, "The Connection was lost,,");
}
#Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
Log.i(TAG, new String(message.getPayload()));
}
#Override
public void deliveryComplete(IMqttDeliveryToken token) {
Log.d(TAG, "Sent Message !");
}
The publish and deliveryComplete functions work fine, but the subscribe function and messagArrived do not work. Why?

xamarin.forms android service run twice after restarting it

I have this code that create an android service
[Service]
public abstract class LongRunningTaskService : Service
{
public override IBinder OnBind(Intent intent)
{
return null;
}
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
Logs.Info("service started: " + this.GetType().ToString());
try
{
Tasks.RunTask(() =>
{
try
{
Task.run(() => SomeTaskFunction);
StopSelf();
Logs.Info("service ended successfully from main task");
}
catch (Android.OS.OperationCanceledException e)
{
Logs.Warning("Error in Tasks.RunTaskWithoutWaitForResult", e);
}
});
return StartCommandResult.NotSticky;
}
catch (Exception e)
{
Logs.Warning("error in OnStartCommand", e);
return StartCommandResult.NotSticky;
}
}
public override void OnDestroy()
{
try
{
Logs.Info("service destroyed: " + this.GetType().ToString());
base.OnDestroy();
}
catch (Exception e)
{
Logs.Warning("Error in service destroyed: " + this.GetType().ToString(), e);
}
}
}
when i create the service the first time it works ok, but when i destroy it from outside the service and recreate it with the same function to run there are 2 tasks running at the same time.
what am i doing wrong ?

Print in Android using a printer with IP address and Port number

My query is I have a printer connected to the Wifi and I am able to connect to that printer using the IP address of the printer but I am not able to print from that printer.
MY code:-
class MakeConnection extends AsyncTask<String, Void, String>{
String check = "NO";
#Override
protected String doInBackground(String... params) {
Socket sock = null;
PrintWriter oStream = null;
try
{
sock = new Socket(ipAddress, 9100);
oStream = new PrintWriter(sock.getOutputStream());
oStream.write("HI,test from Android Device");
check = "yes";
oStream.flush();
}
catch (IOException e)
{
e.printStackTrace();
Logger.LogError(TAG, e.toString());
AppToast.showShortToast(mContext, e.toString());
}
finally {
oStream.close();
try {
sock.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String s) {
Logger.LogError(TAG, check);
super.onPostExecute(s);
}
}
where I am wrong?

Check SerialPort Exist Modem?

In C# 2005, I used the Nokia E63, I want to check SerialPort Exist Modem, While it run does not get run COM port, you see my code
private void btnGetPort_Click(object sender, EventArgs e)
{
cmbPort.Items.Clear();
foreach (string portName in SerialPort.GetPortNames())
{
try
{
using (SerialPort sp = new SerialPort(portName, 9600))
{
if (!(sp.IsOpen)) sp.Open();
sp.DiscardInBuffer();
sp.DiscardOutBuffer();
sp.Write("AT\r\n");
System.Threading.Thread.Sleep(100);
string response = sp.ReadExisting();
if (response == "OK")
{
cmbPort.Items.Add(portName);
}
}
}
catch (Exception ex)
{
continue;
}
}
}

Resources