2017-03-27 20 views
0

私はAndroidスタジオでMQTTプロトコルを使用して学習を始めました。 mosquittoブローカーを使用すると、pub/subウィンドウの間でメッセージを交換できます。しかし、私はアンドロイドスタジオを介してブローカーにメッセージを送信すると、アプリケーションは正常に構築されますが、ブローカーの最後には何も表示されません&システムは接続失敗を表示します。 EclipseのJavaアプリケーションでは同じコードが正常に動作しますが、必要なライブラリと依存関係が追加されていますが、アンドロイドでは動作しません。Androidスタジオ - MQTTが接続されていない

私はこの基本的なステップで何が欠けているので、私は前方に学ぶことができます助けてください。ありがとうございました!

アプリ-build.gradle

dependencies { 
    compile fileTree(dir: 'libs', include: ['*.jar']) 
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { 
     exclude group: 'com.android.support', module: 'support-annotations' 
    }) 
    compile 'com.android.support:appcompat-v7:25.2.0' 
    compile 'com.android.support.constraint:constraint-layout:1.0.2' 
    testCompile 'junit:junit:4.12' 

// have added following dependencies 

    provided 'com.google.android.things:androidthings:0.2-devpreview' 
    provided 'com.google.android.things:androidthings:0.1-devpreview' 
    compile 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.0.2' 

} 

プロジェクト-build.gradle

repositories { 
      jcenter() 
      maven { 
       url "https://repo.eclipse.org/content/repositories/paho-snapshots/" 
      }  
} 

のAndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.example.zoha.mqttandroidiot"> 

    <!-- Permissions the Application Requires --> 
    <uses-permission android:name="android.permission.WAKE_LOCK" /> 
    <uses-permission android:name="android.permission.INTERNET" /> 
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
    <uses-permission android:name="android.permission.READ_PHONE_STATE" /> 
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 


    <application 
     android:allowBackup="true" 
     android:icon="@mipmap/ic_launcher" 
     android:label="@string/app_name" 
     android:roundIcon="@mipmap/ic_launcher_round" 
     android:supportsRtl="true" 
     android:theme="@style/AppTheme"> 


     <activity android:name=".HomeActivity"> 

      <intent-filter> 
       <action android:name="android.intent.action.MAIN"/> 
       <category android:name="android.intent.category.LAUNCHER"/> 
      </intent-filter> 

      <!-- Launch activity automatically on boot --> 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN"/> 
       <category android:name="android.intent.category.IOT_LAUNCHER"/> 
       <category android:name="android.intent.category.DEFAULT"/> 
      </intent-filter> 

     </activity> 
<service android:name="org.eclipse.paho.android.service.MqttService"/> 

    </application> 

</manifest> 

HomeActivity

public class HomeActivity extends AppCompatActivity{ 

    MqttAndroidClient client; 
    // private static final MemoryPersistence persistence = new MemoryPersistence(); 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     final MqttAndroidClient mqttAndroidClient = new MqttAndroidClient(this.getApplicationContext(), "tcp://localhost:1883", "androidSampleClient"); 
     mqttAndroidClient.setCallback(new MqttCallback() { 
      @Override 
      public void connectionLost(Throwable cause) { 
       System.out.println("Connection was lost!"); 

      } 

      @Override 
      public void messageArrived(String topic, MqttMessage message) throws Exception { 
       System.out.println("Message Arrived!: " + topic + ": " + new String(message.getPayload())); 

      } 

      @Override 
      public void deliveryComplete(IMqttDeliveryToken token) { 
       System.out.println("Delivery Complete!"); 
      } 
     }); 

     try { 
      mqttAndroidClient.connect(null, new IMqttActionListener() { 
       @Override 
       public void onSuccess(IMqttToken asyncActionToken) { 
        System.out.println("Connection Success!"); 
        try { 
         System.out.println("Subscribing to /test"); 
         mqttAndroidClient.subscribe("/test", 0); 
         System.out.println("Subscribed to /test"); 
         System.out.println("Publishing message.."); 
         mqttAndroidClient.publish("/test", new MqttMessage("Hello world testing..!".getBytes())); 
        } catch (MqttException ex) { 

        } 

       } 

       @Override 
       public void onFailure(IMqttToken asyncActionToken, Throwable exception) { 
        System.out.println("Connection Failure!"); 
       } 
      }); 
     } catch (MqttException ex) { 

     } 


    } 
    } 
+0

上のエラーを印刷し、あなたの 'AndroidManifest.xml'ファイルに' service'タグを修正してください。 'service..'タグはあなたの' activity'タグの外になければなりません。したがって、 ' '行の下に貼り付けてください –

答えて

1

[OK]をので、あなたは、AndroidでMQTTを使用するために2つのライブラリを必要としています。 1つはmqtt pahoクライアントと他のAndroidサービスライブラリです。

compile 'org.eclipse.paho:org.eclipse.paho.android.service:1.0.2' 
compile 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.0.2' 

その後、MqttAndroidClient代わりのMqttClient使用。

だからnew MqttAndroidClient(...)です。

Android MQTTサービスの完全な例hereを投稿しました。

EDIT:新しいMqttAndroidClientを作成するときに完全な活性の例は

(1)MemoryPersistenceを加えます。
(2).connect()MqttAndroidClientmqttConnectOptionsおよびnull)のメソッドに2つのパラメータが追加されました。
(3)また、またonFailure()

public class HomeActivity extends AppCompatActivity { 

    private MqttAndroidClient client; 
    private final MemoryPersistence persistence = new MemoryPersistence(); 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     final MqttAndroidClient mqttAndroidClient = new MqttAndroidClient(this.getApplicationContext(), "tcp://localhost:1883", "androidSampleClient", persistence); 
     mqttAndroidClient.setCallback(new MqttCallback() { 
      @Override 
      public void connectionLost(Throwable cause) { 
       System.out.println("Connection was lost!"); 
      } 

      @Override 
      public void messageArrived(String topic, MqttMessage message) throws Exception { 
       System.out.println("Message Arrived!: " + topic + ": " + new String(message.getPayload())); 
      } 

      @Override 
      public void deliveryComplete(IMqttDeliveryToken token) { 
       System.out.println("Delivery Complete!"); 
      } 
     }); 

     MqttConnectOptions mqttConnectOptions = new MqttConnectOptions(); 
     mqttConnectOptions.setCleanSession(true); 

     try { 
      mqttAndroidClient.connect(mqttConnectOptions, null, new IMqttActionListener() { 
       @Override 
       public void onSuccess(IMqttToken asyncActionToken) { 
        System.out.println("Connection Success!"); 
        try { 
         System.out.println("Subscribing to /test"); 
         mqttAndroidClient.subscribe("/test", 0); 
         System.out.println("Subscribed to /test"); 
         System.out.println("Publishing message.."); 
         mqttAndroidClient.publish("/test", new MqttMessage("Hello world testing..!".getBytes())); 
        } catch (MqttException ex) { 

        } 
       } 

       @Override 
       public void onFailure(IMqttToken asyncActionToken, Throwable exception) { 
        System.out.println("Connection Failure!"); 
        System.out.println("throwable: " + exception.toString()); 
       } 
      }); 
     } catch (MqttException ex) { 
      System.out.println(ex.toString()); 
     } 
    } 
} 
+0

ありがとうございました。しかし、今では、発行ステートメントでnullポインタ例外を与えています: 'org.eclipse.paho.client.mqttv3.IMqttDeliveryToken org.eclipse.paho.android.service.MqttService.publish(java.lang.String、java.lang.String、org .eclipse.paho.client.mqttv3.MqttMessage、java.lang.String、java.lang.String) 'ヌルオブジェクトリファレンスで – Noor

+0

@ Noorあなたはデバッグして、パラメータのどれがヌルか調べることができますか?もしあれば、各パラメータをログに出力し、どれがnullであるかを調べてみてください。私は非常に単純な問題のようです –

+0

@ th3pat3I改訂されたコードをご覧ください。これでエラーは発生しませんが、Connection Failureと表示されます。 – Noor

関連する問題