Download the NEP Java library using the next link:
This tutorial needs NEP-CLI to version 0.2.0 or above, or NEP+ App 0.0.5 or above.
Include .jar library
Copy .jar to the "libs" Directory: Navigate to the apps/libs directory in the Android Studio project and copy and paste the .jar file, such as the figure below.
Include the required .jar file in Your Project: In Android Studio open build.gradle(Module:app) located in Grandle Scripts -> build.gradle and the next dependencies:
Sync Gradle Files: Click on the "Sync Project with Gradle Files" button in the toolbar. This action ensures that the newly added library is properly included in your project's build configuration.
Verify the Gradle Sync: Once the Gradle sync is complete, verify that there are no errors in the Gradle console.
Configure Network Permissions: Since your app will be using network sockets, you need to ensure that your AndroidManifest.xml file includes the necessary permissions. Add the following permission to your manifest file:
To the previous code, we will add a background thread or AsyncTask to perform socket communication operations. AsyncTask is a convenient way to perform background tasks and update the UI thread with the results.
Here's an example of how you can define an AsyncTask to handle socket communication:
public class SubscriberTask extends AsyncTask<Void, String, Void> {
private Node node;
private Subscriber sub;
// Constructor to initialize the node
public SubscriberTask(Node node) {
this.node = node;
}
@Override
protected Void doInBackground(Void... params) {
// Perform socket communication operations here
// This method runs on a background thread
// Create a new subscriber with the topic <'test'>
sub = node.new_sub("test", "json", nepMasterIP);
while (!isCancelled()) {
String msg = null; // Message obtained as an String
try {
msg = sub.listen();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (!"{}".equals(msg)) // If message is not {}
{
System.out.println(msg);
// Then, convert string to Java object
Gson gson = new Gson();
JsonValue obj = gson.fromJson(msg,JsonValue.class);
// Print message
System.out.println(obj.result);
}
}
// Clean up resources when finished
sub.close();
return null;
}
@Override
protected void onProgressUpdate(String... values) {
// Update the UI with the received message
String message = values[0];
// Handle the received message as needed
}
}
After defining the AsyncTask, you can create an instance of it and execute it to start listening to the subscriber. You can execute the AsyncTask in the onCreate() method of your Activity or wherever appropriate.
Ensure that you properly handle cleanup when your AsyncTask is no longer needed. You can cancel the AsyncTask and clean up resources in the onDestroy() method of your Activity or wherever appropriate.