In my Android Studio, I would like to connect the Mqtt Android client to my laptop host (in the same machine). I make it similar to this guide
https://www.hivemq.com/blog/mqtt-client-library-enyclopedia-paho-android-service/
Then, I found that the Android 12 (API 32 in my case) may not support the org.eclipse.paho:org.eclipse.paho.android.service:1.1.1 dependency. So, I followed this solution below, by imported the serviceLibrary-release.aar library from github provided instead. (The problem appear in this link was the same of my case)
Android paho mqtt crashes Android 12 - Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE
After that, I ran into another error.
error: constructor MqttAndroidClient in class MqttAndroidClient cannot be applied to given types;
MqttAndroidClient client = new MqttAndroidClient(MainActivity.this, "tcp://10.0.2.2:1883", clientId);
^
required: Context,String,String,Ack
found: MainActivity,String,String
reason: actual and formal argument lists differ in length
So I'm not sure that the library from the solution above can be applied to my old code, or, do I need to modify some code?
Here is my code and the gradle file.
repositories
maven {
url "https://repo.eclipse.org/content/repositories/paho-releases/"
}
Dependencies
implementation files('libs/serviceLibrary-release.aar')
implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.5'
Android Manifest (Added permission below)
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<service android:name="info.mqtt.android.service.MqttService"/>
Main Activity
import info.mqtt.android.service.MqttAndroidClient;
public class MainActivity extends AppCompatActivity {
private Button buttonConnect;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonConnect = findViewById(R.id.buttonConnect);
buttonConnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String clientId = MqttClient.generateClientId();
Toast.makeText(MainActivity.this, clientId, Toast.LENGTH_SHORT).show();
MqttAndroidClient client = new MqttAndroidClient(MainActivity.this, "tcp://10.0.2.2:1883", clientId);
try {
IMqttToken token = client.connect();
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.d("Debug", "onSuccess");
Toast.makeText(MainActivity.this, "onSuccess", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.d("Debug", "onFailure");
Toast.makeText(MainActivity.this, "onFailure", Toast.LENGTH_SHORT).show();
exception.printStackTrace();
}
});
} catch (MqttException e) {
e.printStackTrace();
}
}
});
}
}
The error appear in this line (when the button is clicked)
MqttAndroidClient client = new MqttAndroidClient(MainActivity.this, "tcp://10.0.2.2:1883", clientId);
From the error message prompted above. I think that's because the constructor's parameter of this class require a type Ack also, but I have no idea on that.
From output you provided, it seems you only need to specify Ack as the last parameter of your constructor.
It's acknowledgment that you received a message. According to official description, there is two modes available.
First, MqttAndroidClient.Ack.AUTO_ACK, which acknowledge automatically as soon as you received a message.
And then you have MqttAndroidClient.Ack.MANUAL_ACK, which requires you to manually acknowledge by doing MqttAndroidClient.acknowledgeMessage(String)
You can test it simply by adding the auto for now, and if it's ok then you can manually acknowledge yourself with custom rules.
Related
I'm trying to build an app which integrates the Spotify App Remote SDK. However, when I try to connect to Spotify using the SDK, the CouldNotFindSpotifyApp error is thrown even though the Spotify app is installed on the device.
I found other solutions on stackoverflow that asked me to add a queries in the manifest
`
<queries>
<package android:name="com.spotify.music" />
</queries>
`
But that doesn't work and gives me the same error
I tried to connect to the spotify api using this code:
`
ConnectionParams connectionParams =
new ConnectionParams.Builder(CLIENT_ID)
.setRedirectUri(REDIRECT_URI)
.showAuthView(true)
.build();
SpotifyAppRemote.connect(this, connectionParams,
new Connector.ConnectionListener() {
#Override
public void onConnected(SpotifyAppRemote spotifyAppRemote) {
mSpotifyAppRemote = spotifyAppRemote;
Log.d("MainActivity", "Connected! Yay!");
// Now you can start interacting with App Remote
connected();
}
#Override
public void onFailure(Throwable error) {
if (error instanceof NotLoggedInException || error instanceof UserNotAuthorizedException) {
Log.d("MainActivity", "Other Error");
} else if (error instanceof CouldNotFindSpotifyApp) {
Log.d("MainActivity", "User Not Found");
}
}
});
`
And instead of connecting it gave me an error
CouldNotFindSpotifyApp
I am trying to send a crash report from an android application and it is opening a email client and entering com.x.x Crash Report in the email body. I cant seem to be able to get any other information in the email. The docs dont have a complete email example and i have reportContent added (but APP_VERSION is not resolving). I have also updated my manifest file with READ_PHONE_STATE
I'm referencing this https://github.com/ACRA/acra/wiki/AdvancedUsage#choosing-which-fields-to-be-included-in-reports.
Any help would be appreciated
Manifest
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
Application
#AcraCore(
reportContent = { /*APP_VERSION,*/ ANDROID_VERSION, PHONE_MODEL, CUSTOM_DATA, STACK_TRACE, LOGCAT}
)
#AcraMailSender(mailTo = "X#protonmail.com")
public class MyApplication extends Application {
#Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
ACRA.init(this);
}
I know this is dead post, nevertheless there's mistake in ACRA's site, example should be reading:
#AcraCore(
buildConfigClass = org.acra.BuildConfig.class,
logcatArguments = {"-t", "200", "-v", "time"},
reportFormat= StringFormat.JSON,
reportContent = {
ReportField.USER_COMMENT,
ReportField.APP_VERSION_NAME,
ReportField.APP_VERSION_CODE,
ReportField.ANDROID_VERSION,
ReportField.PHONE_MODEL,
ReportField.CUSTOM_DATA,
ReportField.STACK_TRACE,
ReportField.LOGCAT }
)
#AcraMailSender(
mailTo = "email#domain.com"
)
I used Crashlytics instead as suggested by #gabe-sechan
I'm using the jmdns.jar from this project https://github.com/twitwi/AndroidDnssdDemo in my Android project.
I'm currently trying to find all services on my network. I can't use Android NSD, so please avoid suggesting it as a solution.
protected Object doInBackground(Object[] params) {
try {
WifiManager wifi = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
final InetAddress deviceIpAddress = InetAddress.getByName(Formatter.formatIpAddress(wifi.getConnectionInfo().getIpAddress()));
multicastLock = wifi.createMulticastLock(getClass().getName());
multicastLock.setReferenceCounted(true);
multicastLock.acquire();
jmDNS = JmDNS.create(deviceIpAddress, "Android Device Discovery");
jmDNS.addServiceListener("_http._tcp.local.", new ServiceListener() {//_services._dns-sd._udp _http._tcp.local. _workstation._tcp.local.
#Override
public void serviceAdded(ServiceEvent serviceEvent) {
jmDNS.requestServiceInfo("", "", 1000);
}
#Override
public void serviceRemoved(ServiceEvent serviceEvent) {
}
#Override
public void serviceResolved(ServiceEvent serviceEvent) {
System.out.println(serviceEvent.getInfo().getHostAddress());
System.out.println(serviceEvent.getInfo().getName());
}
});
}catch(IOException e) {
Log.e(TAG, e.getMessage(), e);
}
}
The above code gives me the address and name of a printer on my network. That's great. What I would like is a TYPE that will catch all the services being broadcasted on my network. Android NSD had a _services._dns-sd._udpthat could be used for the type of service and find all services on the network. This doesn't work with jmDNS. I can't find anything in the limited documentation about this.
Do I need to go through and add all the service types myself? That is not a very clean solution.
I have the proper perms in my AndroidManifest.
Try adding the dot at the end, my jmdns app crashed without it..
Also try adding the .local. by yourself with the service type.
I am trying to make an android chat application. I am thinking about making it with aws. But the problem is that I am unable to find any good tutorial for doing this and I have no idea how to do it.
So could anyone please suggest some tutorial for sending push notification or on how to make a chat application?
Firebase is well suited to this due to its "realtime database" feature. Here's a few tutorials I found by Googling
https://code.tutsplus.com/tutorials/how-to-create-an-android-chat-app-using-firebase--cms-27397
http://myapptemplates.com/simple-android-chat-app-tutorial-firebase-integration/
https://codelabs.developers.google.com/codelabs/firebase-android/#0
Check Socket.IO for android. ( https://github.com/socketio/socket.io-client-java )
Its really easy to write a chat application. But you need a server side.
Easy to write a simple server for this chat app.
Server reveice the all message from clients and broadcast the message, to all.
Gradle:
compile 'com.github.nkzawa:socket.io-client:0.5.1'
Android manifest:
<uses-permission android:name="android.permission.INTERNET" />
Java
public static Socket mSocket;
try {
mSocket = IO.socket("http://192.168.1.104:4444");
mSocket.connect();
} catch (URISyntaxException e) {
e.printStackTrace();
}
Send messsage to server:
MainActivity.mSocket.emit("message","Text here...");
Create a listener for another message:
MainActivity.mSocket.on("newMessage", onMessageArrive); // Oncreate
private Emitter.Listener onMessageArrive = new Emitter.Listener() {
#Override
public void call(final Object... args) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
String data = (String)args[0];
// Here is all message. add it to list :) Or Push notif
}
});
}
};
// Server side:
var http = require('http');
var express = require('express'),
app = module.exports.app = express();
var io = require('socket.io').listen(app.listen(4444));
io.on('connection', function (socket) {
socket.on("message",function(msg){
io.sockets.emit('newMessage', msg);
});
});
Run:
npm install express
npm install socket.io
node filename.js
Just dont forget to check you IP! :)
Done! You have a Real Time Chat!!
I want to sent SMS with my Application with :
Intent smsIntent = new Intent(Intent.ACTION_VIEW);
smsIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
smsIntent.setData(Uri.parse("smsto:" + sms));
smsIntent.putExtra("smsto", sms);
smsIntent.putExtra("sms_body", "MYSMSBOBY");
mActivity.startActivity(smsIntent);
It's work fine in devices that there is SMS Application, but in some devices i get this crash error:
No Activity found to handle Intent { act=android.intent.action.VIEW dat=smsto:xxxxxxxxxx flg=0x10000000 (has extras) }
Any idea how i can recognize if SMS Application installed on the device?
Any idea how i can recognize if SMS Application installed on the device?
While you can use PackageManager to see if there's any app to handle your intent, that's should not be really of your concern at all. What you should take care of is just the crash itself, so instead of just:
mActivity.startActivity(smsIntent);
you should at least have generic exception handling code:
try {
mActivity.startActivity(smsIntent);
} catch ( Exception e ) {
e.printStackTrace();
// show toast or something so user knows why it is not working
}
and catch any failure of startActivity(). You may also want to make create separate catch for this particular type of exception, ActivityNotFoundException
<!-- SMS -->
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
/**
* Test if device can send SMS
* #param context
* #return
*/
public static boolean canSendSMS(Context context) {
return context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELEPHONY);
}