如何将数据从活动传递到MQTT帮助程序类(任何方法)?

时间:2017-12-22 06:39:22

标签: java android mqtt

我尝试使用意图,但应用程序一直崩溃所以我想到使用文件。该应用程序再次崩溃。该应用程序将语音转换为文本并将其发送到MQTT服务器。我测试了语音到文本功能,它工作正常。在我添加了意图或文件的代码后,它崩溃了。

这是MainActivity.class

import android.content.Intent; 
import android.net.Uri;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import helpers.MQTTHelper;

public class MainActivity extends AppCompatActivity implements    TextToSpeech.OnInitListener {
MQTTHelper mqttHelper;
TextView dataReceived;
TextToSpeech tts;
public static String s;
Button startRecognizer;
private static final int RQS_RECOGNITION = 1;

@Override

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

    dataReceived = (TextView) findViewById(R.id.dataReceived);


    startRecognizer = (Button) findViewById(R.id.startrecognizer);
    startRecognizer.setEnabled(false);
    startRecognizer.setOnClickListener(startRecognizerOnClickListener);
    tts = new TextToSpeech(this, this);
    Intent serviceIntent = new Intent(MQTTHelper.class.getName());
    serviceIntent.putExtra("name", "hello");
    this.startService(serviceIntent);
    startMqtt();
}
private Button.OnClickListener startRecognizerOnClickListener = new Button.OnClickListener() {

    @Override
    public void onClick(View arg0) {
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speech to Recognize");
        startActivityForResult(intent, RQS_RECOGNITION);
    }
};
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if ((requestCode == RQS_RECOGNITION) & (resultCode == RESULT_OK)) {
        ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
        //ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, result);
        Toast.makeText(getApplicationContext(),result.get(0),Toast.LENGTH_LONG).show();
        writeToSD(result.get(0));
        s=result.get(0);
       //Intent intent = new Intent(MainActivity.this, MQTTHelper.class);
        //Intent intent = new Intent(MQTTHelper.class.getName());
        //intent.putExtra("name", s);
        //bindService(intent, (ServiceConnection) this, Context.BIND_AUTO_CREATE);
        //startService(intent);
    }

}
private void writeToSD(String sttdata)
{
    File root=android.os.Environment.getExternalStorageDirectory();
    File dir=new File(root.getAbsolutePath() + "/VoiceReader");
    if(!dir.exists() && !dir.isDirectory())
    {dir.mkdir();}
    File file=new File(dir,"Output.txt");
    try
    {
        FileOutputStream f=new FileOutputStream(file);
        PrintWriter pw=new PrintWriter(f);
        pw.println(sttdata);
        pw.flush();
        pw.close();
        f.close();
    }catch (FileNotFoundException e){
        e.printStackTrace();
    }catch (IOException i){
        i.printStackTrace();
    }
    try {
        Intent in=new Intent(Intent.ACTION_EDIT);
        Uri uri= Uri.fromFile(file);
        in.setDataAndType(uri,"plain/text");
        startActivity(in);
    }catch(Exception ex){
        Log.e("tag","No file browser installed. "+ex.getMessage());
    }

}

@Override
public void onInit(int arg0) {
    startRecognizer.setEnabled(true);
}
private void startMqtt() {
    mqttHelper = new MQTTHelper(getApplicationContext());
    mqttHelper.setCallback(new MqttCallbackExtended() {
        @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());
        }
        //something
        @Override
        public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

        }
    });
}

}

这是MQTThelper.class

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.DisconnectedBufferOptions;
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.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

public class MQTTHelper extends Service{
public MqttAndroidClient mqttAndroidClient;
public static String userID;
Context context;
String readData;
final String serverUri = "tcp://m12.cloudmqtt.com:10133";

final String clientId = "ExampleAndroidClient";
final String subscriptionTopic = "sensor/+";

final String username = "tiswwmgq";
final String password = "gSDAucu0fU_E";
public MQTTHelper(){} //removes error in manifest file. Seems optional
public MQTTHelper(Context context){
    mqttAndroidClient = new MqttAndroidClient(context, serverUri, clientId);
    mqttAndroidClient.setCallback(new MqttCallbackExtended() {
        @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(MqttCallbackExtended 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();
                publishtopic();
            }

            @Override
            public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                Log.w("Mqtt", "Failed to connect to: " + serverUri + exception.toString());
            }
        });


    } catch (MqttException ex){
        ex.printStackTrace();
    }
}
public void readFromSD()
{
    File root=android.os.Environment.getExternalStorageDirectory();
    File dir=new File(root.getAbsolutePath() + "/VoiceReader");
    File myfile = new File(dir,"Output.txt");

    FileInputStream fis= null;
    try {
        fis = getApplicationContext().openFileInput("Output.txt");
        InputStreamReader isr =new InputStreamReader(fis);
        BufferedReader br=new BufferedReader(isr);
        try {
            readData=br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }


}

private void subscribeToTopic() {

    try {
        mqttAndroidClient.subscribe(subscriptionTopic, 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("Exceptions at subscribing");
        ex.printStackTrace();
    }
}
public int onStartCommand(Intent intent, int flags, int startId) {
    //super.onStartCommand(intent,flags,startId); //I added dis
    //String userID = intent.getStringExtra("name");
    readFromSD();
    //Toast.makeText(getApplicationContext(),userID, Toast.LENGTH_LONG).show();
    Toast.makeText(this,readData, Toast.LENGTH_LONG).show();
    return START_STICKY;

}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

private void publishtopic()
{



    try {
        mqttAndroidClient.publish("sensor/t",new MqttMessage(readData.getBytes()));
    } catch (MqttException e) {
        e.printStackTrace();
    }
}


} 

这是AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.aisha">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_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=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <service android:name="org.eclipse.paho.android.service.MqttService" />
    <service android:enabled="true" android:name="helpers.MQTTHelper" />
</application>

</manifest>

这是build.gradle(Module:app)

apply plugin: 'com.android.application'

android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
    applicationId "com.example.aisha"
    minSdkVersion 15
    targetSdkVersion 25
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

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.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'

    compile 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.0'
    compile 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'
}

这是我使用意图或文件时出现的错误。

12-22 11:25:13.201 32311-32311/com.example.aisha E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.aisha, PID: 32311
  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.aisha/com.example.aisha.MainActivity}: java.lang.IllegalArgumentException: Service Intent must be explicit: Intent { act=helpers.MQTTHelper (has extras) }
   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
   at android.app.ActivityThread.-wrap12(ActivityThread.java)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
   at android.os.Handler.dispatchMessage(Handler.java:102)
   at android.os.Looper.loop(Looper.java:154)
   at android.app.ActivityThread.main(ActivityThread.java:6119)
   at java.lang.reflect.Method.invoke(Native Method)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
 Caused by: java.lang.IllegalArgumentException: Service Intent must be explicit: Intent { act=helpers.MQTTHelper (has extras) }
   at android.app.ContextImpl.validateServiceIntent(ContextImpl.java:1345)
   at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1374)
   at android.app.ContextImpl.startService(ContextImpl.java:1358)
   at android.content.ContextWrapper.startService(ContextWrapper.java:613)
   at com.example.aisha.MainActivity.onCreate(MainActivity.java:51)
   at android.app.Activity.performCreate(Activity.java:6720)
   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
   at android.app.ActivityThread.-wrap12(ActivityThread.java) 
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477) 
   at android.os.Handler.dispatchMessage(Handler.java:102) 
   at android.os.Looper.loop(Looper.java:154) 
   at android.app.ActivityThread.main(ActivityThread.java:6119) 
   at java.lang.reflect.Method.invoke(Native Method) 
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 

1 个答案:

答案 0 :(得分:0)

在代码中使用This is a HTML page Design

Intent serviceIntent = new Intent(MainActivity.this, MQTTHelper.class);  

而不是

Intent serviceIntent = new Intent(MQTTHelper.class.getName());

更多Explicit Intent