- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这是我的MQTTCONECTION类
public class MQTTService extends Service {
private static final String TAG = "MQTTService";
private static boolean hasWifi = false;
private static boolean hasMmobile = false;
private Thread thread;
private ConnectivityManager mConnMan;
private volatile IMqttAsyncClient mqttClient;
private String deviceId;
class MQTTBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
IMqttToken token;
boolean hasConnectivity = false;
boolean hasChanged = false;
NetworkInfo infos[] = mConnMan.getAllNetworkInfo();
for (int i = 0; i < infos.length; i++){
if (infos[i].getTypeName().equalsIgnoreCase("MOBILE")){
if((infos[i].isConnected() != hasMmobile)){
hasChanged = true;
hasMmobile = infos[i].isConnected();
}
Log.d(TAG, infos[i].getTypeName() + " is " + infos[i].isConnected());
} else if ( infos[i].getTypeName().equalsIgnoreCase("WIFI") ){
if((infos[i].isConnected() != hasWifi)){
hasChanged = true;
hasWifi = infos[i].isConnected();
}
Log.d(TAG, infos[i].getTypeName() + " is " + infos[i].isConnected());
}
}
hasConnectivity = hasMmobile || hasWifi;
Log.v(TAG, "hasConn: " + hasConnectivity + " hasChange: " + hasChanged + " - "+(mqttClient == null || !mqttClient.isConnected()));
if (hasConnectivity && hasChanged && (mqttClient == null || !mqttClient.isConnected())) {
//Log.d(TAG, "Llama a la función doConnect");
doConnect();
} else if (!hasConnectivity && mqttClient != null && mqttClient.isConnected()) {
Log.d(TAG, "doDisconnect()");
try {
token = mqttClient.disconnect();
token.waitForCompletion(1000);
} catch (MqttException e) {
e.printStackTrace();
}
}
}
};
public class MQTTBinder extends Binder {
public MQTTService getService(){
return MQTTService.this;
}
}
@Override
public void onCreate() {
IntentFilter intentf = new IntentFilter();
setClientID();
intentf.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(new MQTTBroadcastReceiver(), new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
mConnMan = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
Log.d(TAG, "onConfigurationChanged()");
android.os.Debug.waitForDebugger();
super.onConfigurationChanged(newConfig);
}
private void setClientID(){
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wInfo = wifiManager.getConnectionInfo();
deviceId = wInfo.getMacAddress();
if(deviceId == null){
deviceId = MqttAsyncClient.generateClientId();
}
}
private void doConnect(){
IMqttToken token;
MqttConnectOptions options = new MqttConnectOptions();
options.setCleanSession(true);
//StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
try {
mqttClient = new MqttAsyncClient("tcp://192.168.0.9:1883", deviceId, new MemoryPersistence());
token = mqttClient.connect();
token.waitForCompletion(3500);
mqttClient.setCallback(new MqttEventCallback());
token = mqttClient.subscribe("test", 0);
token.waitForCompletion(5000);
token.setActionCallback(new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.d(TAG, "Si se conecto");
/*String mensaje = "Conchita";
byte[] mensajeB = mensaje.getBytes(UTF_8);
MqttMessage mqttMessage = new MqttMessage(mensajeB);
try {
mqttClient.publish("test", mqttMessage);
} catch (MqttException e) {
e.printStackTrace();
}*/
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.d(TAG, "Que nel");
}
});
} catch (MqttSecurityException e) {
e.printStackTrace();
} catch (MqttException e) {
switch (e.getReasonCode()) {
case MqttException.REASON_CODE_BROKER_UNAVAILABLE:
Log.d(TAG, "The broker was not available to handle the request.");
break;
case MqttException.REASON_CODE_CLIENT_ALREADY_DISCONNECTED:
Log.d(TAG, "The client is already disconnected.");
break;
case MqttException.REASON_CODE_CLIENT_CLOSED:
Log.d(TAG, "The client is closed - no operations are permitted on the client in this state.");
break;
case MqttException.REASON_CODE_CLIENT_DISCONNECT_PROHIBITED:
Log.d(TAG, "Thrown when an attempt to call MqttClient.disconnect() has been made from within a method on MqttCallback.");
break;
case MqttException.REASON_CODE_CLIENT_DISCONNECTING:
Log.d(TAG, "The client is currently disconnecting and cannot accept any new work.");
break;
case MqttException.REASON_CODE_CLIENT_EXCEPTION:
Log.d(TAG, "Client encountered an exception.");
System.out.println("Cause of Exception: "
+ e.getCause());
break;
case MqttException.REASON_CODE_CLIENT_NOT_CONNECTED:
Log.d(TAG, "The client is not connected to the server.");
break;
case MqttException.REASON_CODE_CLIENT_TIMEOUT:
Log.d(TAG, "Client timed out while waiting for a response from the server.");
break;
case MqttException.REASON_CODE_CONNECT_IN_PROGRESS:
Log.d(TAG, "A connect operation in already in progress, only one connect can happen at a time.");
break;
case MqttException.REASON_CODE_CONNECTION_LOST:
Log.d(TAG, "The client has been unexpectedly disconnected from the server.");
break;
case MqttException.REASON_CODE_DISCONNECTED_BUFFER_FULL:
Log.d(TAG, "The Client has attempted to publish a message whilst in the 'resting' / ");
break;
case MqttException.REASON_CODE_FAILED_AUTHENTICATION:
Log.d(TAG, "Client encountered an exception.");
break; //
case MqttException.REASON_CODE_INVALID_CLIENT_ID:
Log.d(TAG, "The server has rejected the supplied client ID");
break;
case MqttException.REASON_CODE_INVALID_MESSAGE:
Log.d(TAG, "Protocol error: the message was not recognized as a valid MQTT packet.");
break;
case MqttException.REASON_CODE_INVALID_PROTOCOL_VERSION:
Log.d(TAG, "The protocol version requested is not supported by the server.");
break;
case MqttException.REASON_CODE_MAX_INFLIGHT:
Log.d(TAG, "A request has been made to send a message but the maximum number of inflight messages has already been reached.");
break;
case MqttException.REASON_CODE_NO_MESSAGE_IDS_AVAILABLE:
Log.d(TAG, "Internal error, caused by no new message IDs being available.");
break;
case MqttException.REASON_CODE_NOT_AUTHORIZED:
Log.d(TAG, "ot authorized to perform the requested operation");
break;//--
case MqttException.REASON_CODE_SERVER_CONNECT_ERROR:
Log.d(TAG, "Unable to connect to server");
break;
case MqttException.REASON_CODE_SOCKET_FACTORY_MISMATCH:
Log.d(TAG, "Server URI and supplied SocketFactory do not match.");
break;
case MqttException.REASON_CODE_SSL_CONFIG_ERROR:
Log.d(TAG, "SSL configuration error.");
break;
case MqttException.REASON_CODE_SUBSCRIBE_FAILED:
Log.d(TAG, "Error from subscribe - returned from the server.");
break;
case MqttException. REASON_CODE_TOKEN_INUSE:
Log.d(TAG, "A request has been made to use a token that is already associated with another action.");
break;
case MqttException.REASON_CODE_UNEXPECTED_ERROR:
Log.d(TAG, "An unexpected error has occurred.");
break;//--
case MqttException.REASON_CODE_WRITE_TIMEOUT:
Log.d(TAG, "Client timed out while waiting to write messages to the server.");
break;//--
/*case MqttException.REASON_CODE_SERVER_CONNECT_ERROR:
Log.d(TAG, "c" +e.getMessage());
e.printStackTrace();
break;
case MqttException.REASON_CODE_FAILED_AUTHENTICATION:
Intent i = new Intent("RAISEALLARM");
i.putExtra("ALLARM", e);
Log.d(TAG, "b"+ e.getMessage());
break;*/
default:
Log.e(TAG, "a_" + e.getMessage());
}
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.v(TAG, "onStartCommand()");
return START_STICKY;
}
private class MqttEventCallback implements MqttCallback {
@Override
public void connectionLost(Throwable arg0) {
}
@Override
public void deliveryComplete(IMqttDeliveryToken arg0) {
}
@Override
@SuppressLint("NewApi")
public void messageArrived(String topic, final MqttMessage msg) throws Exception {
Log.i(TAG, "Message arrived from topic" + topic);
Handler h = new Handler(getMainLooper());
h.post(new Runnable() {
@Override
public void run() {
Intent launchA = new Intent(MQTTService.this, MainActivity.class);
launchA.putExtra("message", msg.getPayload());
//TODO write somethinkg that has some sense
if(Build.VERSION.SDK_INT >= 11){
launchA.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_REORDER_TO_FRONT|Intent.FLAG_ACTIVITY_NO_ANIMATION);
} /*else {
launchA.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}*/
startActivity(launchA);
Toast.makeText(getApplicationContext(), "MQTT Message:\n" + new String(msg.getPayload()), Toast.LENGTH_SHORT).show();
}
});
}
}
public String getThread(){
return Long.valueOf(thread.getId()).toString();
}
@Override
public IBinder onBind(Intent intent) {
Log.i(TAG, "onBind called");
return null;
}
}
这是我的MainActivity:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent mymqttservice_intent = new Intent(this, MQTTService.class);
startService(mymqttservice_intent);
}
}
和 list 文件:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.serviciomqtt_2">
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:usesCleartextTraffic="true"
android:theme="@style/AppTheme">
<service
android:enabled="true"
android:name="MQTTService"
/>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Iam也使用API 29,MOsquitto mqtt代理处于 Activity 状态
最佳答案
代替:
<uses-permission android:name="android.permission.ACCESS_INTERNET"/>
和:
<uses-permission android:name="android.permission.INTERNET"/>
关于java - MQTT服务错误 “socket failed: EPERM”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62722052/
我正在使用 titanium 和 genymotion 作为 android 模拟器。我收到以下错误:- [错误] 触发“执行后”事件时出错[错误] 错误:EPERM,不允许操作 'C:\Users\
我用谷歌搜索 EPERM: operation not permitted 我在 npm 问题和这个错误上得到了很多点击。 这不是我的情况(不是重复的),因为我没有运行 npm,我正在运行我自己的 N
我使用 ngBoilerplate 作为我的应用程序的基础。ngbp 使用 ngAnnotate 和 grunt-ng-annotate 来很好地注释应用程序。 一切都工作正常,直到我必须格式化我的计
我知道这是 node 的常见错误,但我所有的故障排除技术似乎都失败了。 Windows 7(32 位) Node@0.10.10 npm@1.2.25 尝试运行 bower 和 yo (Yeoman)
我在尝试使用 Bower 安装“jQuery”时遇到以下错误堆栈跟踪。有人可以提供帮助吗? C:\study\meanApp>bower install jquery --save b
使用 gulp 和新的 Microsoft bash shell,我正在尝试设置一个 gulp watch 来将我的 scss 编译成 css,这样当编译出错时 watch 不会停止。 我已经设置了一
在Windows 10中使用VS代码时,我一直遇到很多权限问题。 尝试移动文件夹时: 错误:EPERM:不允许进行操作,请重命名“路径a”->“路径b” 删除文件夹时: 它静默失败,该文件夹已从解决方
这是我的MQTTCONECTION类 public class MQTTService extends Service { private static final String T
尝试运行 https://github.com/jakearchibald/wittr 时在 Windows bash 上,我收到以下错误,非常感谢帮助修复或调试它: Development ser
我正在使用 Multer 在我的 fs 中上传图像。 Multer 不允许您动态设置 fs 中的位置,因此我始终在同一文件夹中上传,然后使用 fs.renamesynch 更改文件夹的名称。 我使用同
我已经全局安装了pm2sudo pm2 install -gpm2 启动server.js pm2 状态(给出这个输出)┌──────────┬──────┬────────┬────────┬───
我正在使用我正在编写的内核模块劫持一个特定的系统调用。替换代码是这样的: asmlinkage int custom_setxattr(const char* __user path, const c
我正在尝试为我的项目构建一个 android APK 文件 C:\myApp>cordova build android cp: copyFileSync: could not write to de
我已经将自己的 ext4 磁盘挂载到/mnt/sdb 并将其更改为 777。 但是,当启动数据节点时: /etc/init.d/hadoop-hdfs-datanode 启动 我在日志中收到以下错误(
我很难在我的 Windows 机器上使用 nodejs fs.watch 观看文件夹。删除监视的文件夹时会引发异常。 fs.watch('somedir', function (event,
我有一个 Qt 项目,它使用一个在我的系统上编译良好的插件接口(interface)。然而,当同一个项目在 docker 中编译时,它停止使用 Qt 5.10.1,给出消息错误:未定义的接口(inte
{ 错误:EPERM:不允许操作,打开 'C:\Users\Vivek Sharma\apps\testApp\www\assets\imgs\Thumbs.db’ **错误号:-4048, 代码:‘
目前我正在尝试使用 Webstorm 开发一个 ionic-app。但是 gulp 正在制造一些麻烦。 已安装的包: "gulp": "^3.5.6", "gulp-concat": "^2.2.0"
如果尝试在 USB 设备上构建 node.js 应用程序时在我的树莓派上使用 npm 时遇到一些问题。 package.json 看起来像这样: { "name" : "node-todo",
EACCES 和 EPERM 到底有什么区别? EPERM 描述 here作为“不是 super 用户”,但我通常会将其与 EACCES 联系起来。事实上,我不记得在现实生活中见过 EPERM。 最佳
我是一名优秀的程序员,十分优秀!