Howto getExtras from a local broadcast Intent in react-native - java

in my React-Native opened project,
I want to receive the data (extra text) sent by another local service app named "scanservice" on its intent output (broadcast) on a Action named "scanservice.data" ,
and I do not know how to start & write that : someone can help me please?
I have tried without success HeadlessJs, Linking solutions.

I put some more info I got and I please ask for some corrections since I am null in Java writting :
I want to make a native Android module (in java) (as described on RN site : https://reactnative.dev/docs/native-modules-android)
to catch the text ('extra_text') sent by an intent of another app, named "manuf".
The class 'scan_intent.java' I wrote here has many mistakes (with "//error":
package com.intent_scan;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import org.w3c.dom.Text;
public class ScanIntent extends ReactContextBaseJavaModule {
//constructor
// normaly : "public class ScanIntent extends BroadcastReceiver" : how to add this ?
public ScanIntent(ReactApplicationContext reactContext) {
super(reactContext);
}
#Override
public String getName() {
return "ScanIntent";
}
//Custom function that we are going to export to JS
#ReactMethod
public void onReceive(Context context, Intent intent, String extra_text){
if ("manuf.scanservice.data".equals(intent.getAction()))
{
getReactApplicationContext().registerReceiver //error on registerR...
try {
Bundle extras = intent.getExtras();
if (extras != null) {
extra_text = extras.getString("text"); //error : this value will be returned ?
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}}
thank you !

Related

Unable to communicate between Android client and Node.js socket.io server

I've looked at many tutorials on this yet none of them seem to work so no idea whether it's the server, client or potentially something on my network that's stopping it I don't know, so I come here for help.
Just for reference this is the tutorial that this is mainly based on: https://socket.io/blog/native-socket-io-and-android/
So this is my server. All it's supposed to do at the moment is detect when a user connects and then detect users sending messages and send them back to all the clients.
index.js
const express = require("express");
const app = express();
const path = require("path");
const server = require("http").createServer(app);
const io = require("socket.io")(server);
server.listen(3000, () => {
console.log("Server listening at 3000");
});
app.use(express.static(path.join(__dirname, "public")));
io.on("connection", (socket) => {
console.log("User connected");
socket.on("new message", (data) => {
console.log("New message" + data)
socket.emit("new message", {
message: data
});
})
});
My Android client is made up of 3 classes. But to try and keep this shorter I'll only include 2 of them as if the problem can be found in these it's fixable in the 3rd.
This is what's launched at the start and simply pressing the button brings you to the main 'chat' part, but on clicking the button the server should log the connection but nothing appears in the console. So I can only assume the socket connection isn't working for some reason. Also you can ignore the nickname, I've not implemented that yet, been trying to get the main part working first.
MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import io.socket.client.Socket;
public class MainActivity extends AppCompatActivity {
private EditText nickname;
private Button enterChat;
private Socket mSocket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nickname = findViewById(R.id.nickname);
enterChat = findViewById(R.id.enterChat);
ChatApplication app = (ChatApplication) getApplication();
mSocket = app.getSocket();
mSocket.connect();
enterChat.setOnClickListener(v -> {
mSocket.emit("connection");
Intent i = new Intent(MainActivity.this, ChatActivity.class);
i.putExtra("name", nickname.getText().toString());
startActivity(i);
});
}
}
This is just to be able to get the Socket from any other activity.
ChatApplication.java
import android.app.Application;
import java.net.URISyntaxException;
import io.socket.client.IO;
import io.socket.client.Socket;
public class ChatApplication extends Application {
private Socket mSocket;
{
try {
//My IPv4 address here
mSocket = IO.socket("http://xxx.xxx.x.xxx:3000");
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
public Socket getSocket() {
return mSocket;
}
}
Any help appreciated :)
Found the problem, I need to add this to the AndroidManifest.xml
<application
...
android:usesCleartextTraffic="true"
...
</application>

When I run the Codename One HelloWorld Java Program from the Codename One HelloWorld Tutorial, I get an error

When I run the Codename One HelloWorld Java Program from the Codename One HelloWorld Tutorial video, I get this error:
java: cannot find symbol
symbol: class Button
location: class com.acmecorp.appname.AppName
I think I'm missing an import for class Button. How do I add the import statement for class Button so that the compilation won't have this error?
Here is my source code:
package com.acmecorp.appname;
import static com.codename1.ui.CN.*;
import com.codename1.ui.Display;
import com.codename1.ui.Form;
import com.codename1.ui.Dialog;
import com.codename1.ui.Label;
import com.codename1.ui.plaf.UIManager;
import com.codename1.ui.util.Resources;
import com.codename1.io.Log;
import com.codename1.ui.Toolbar;
import java.io.IOException;
import com.codename1.ui.layouts.BoxLayout;
import com.codename1.io.NetworkEvent;
/**
* This file was generated by Codename One for the purpose
* of building native mobile applications using Java.
*/
public class AppName {
private Form current;
private Resources theme;
public void init(Object context) {
// use two network threads instead of one
updateNetworkThreadCount(2);
theme = UIManager.initFirstTheme("/theme");
// Enable Toolbar on all Forms by default
Toolbar.setGlobalToolbar(true);
// Pro only feature
Log.bindCrashProtection(true);
addNetworkErrorListener(err -> {
// prevent the event from propagating
err.consume();
if(err.getError() != null) {
Log.e(err.getError());
}
Log.sendLogAsync();
Dialog.show("Connection Error", "There was a networking error in the connection to " + err.getConnectionRequest().getUrl(), "OK", null);
});
}
public void start() {
if(current != null){
current.show();
return;
}
Form hi = new Form("Hi World", BoxLayout.y());
hi.add(new Label("Hi World"));
Button b = new Button("Show Dialog");
hi.add(b);
b.addActionListener((e) -> Dialog.show("Dialog Title", "Hi", "OK", null));
hi.show();
}
public void stop() {
current = getCurrentForm();
if(current instanceof Dialog) {
((Dialog)current).dispose();
current = getCurrentForm();
}
}
public void destroy() {
}
}
I guess this com.codename1.ui.Button might works for u.

How do put each AsyncTask class in a separate file?

I have a few asynstask that are definined inside of my main activity. I tried to make the code more modular by putting each one of these classes on a separate file. Unfortunately I keep getting some errors such as not being able to get the intents to work. How do I connect this code with my main activity. By the way if I place this code as is(without the imports) in the mainActivity it works just fine. Thanks
package com.example.food4thought;
import java.net.URL;
import twitter4j.TwitterException;
import twitter4j.auth.RequestToken;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
// Starts an intent that loads up a web browser and asks the user to log in to twitter
// and get a pin#
public class TwitterLogin extends AsyncTask<URL, Integer, RequestToken> {
protected RequestToken doInBackground(URL... arg0) {
try {
requestToken = twitter.getOAuthRequestToken();
Log.i("Got Request Token", "food4thought");
} catch (TwitterException e) {
Log.i("Failed to get Request Token", "food4thought");
}
//Log.i(requestToken.getAuthorizationURL(), "food4thought");
//requestToken.getAuthorizationURL();
//log_in.setText();
try {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthorizationURL()));
startActivity(browserIntent);
}
catch(NullPointerException e) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Unable to log in, No access to the Internet.", Toast.LENGTH_LONG).show();
}
});
}
return null;
}
}
To do that you need to understand what dependencies your AsyncTask has.
To fire Intents you need Context intance. I also see some twitter variable.
So you need declare appropriate fields and to pass those objects to your TwitterLogin constructor.
Something like that:
public class TwitterLogin extends AsyncTask<URL, Integer, RequestToken> {
private Context context;
//other fields here
public TwitterLogin(Context context, ...){ // other variables here
this.context = context;
//other fields assignment
}
}
Later you can fire Intent:
context.startActivity(browserIntent);
What's important to understand is that all those methods like startActivity are not some "global functions", rather they are methods of some class instance, and you can't just call those methods from AsycTask instance.

Android - Java - No Activity Found to Handle Intent

I am trying to create an Android / Java plugin for the cross-platform program Phonegap / Cordova 3.2. I am following several tutorials but can't get the simplest plugin to work.
Currently I am working on the idea that my Java code is just wrong somewhere.
Could someone please review the following code and advise if there is something obviously wrong?
The error I keep getting is
Exception: No Activity found to handle Intent { act=android.intent.action.MEDIA_SCANNER_SCAN_FILE dat=file:///{"fullPath":"media\/test.mp3"} }
Here is my .java file
package org.media.scan;
import java.io.File;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import android.content.Intent;
import android.net.Uri;
public class Scan extends CordovaPlugin {
#Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
try {
if ( action.equals("addRemove") ) {
String filePath = args.getString(0);
filePath = filePath.replaceAll("^file://", "");
if (filePath.equals("")) {
callbackContext.error("null path passed");
return false;
}
File file = new File(filePath);
Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
scanIntent.setData(Uri.fromFile(file));
this.cordova.getActivity().startActivity( scanIntent );
callbackContext.success("good");
return true;
} else {
callbackContext.error("invalid action phrase");
}
return false;
} catch(Exception e) {
System.err.println("Exception: " + e.getMessage());
callbackContext.error(e.getMessage());
return false;
}
}
}
I am calling my Java code with this .js code
var Scan = {
createEvent:function (fullPath, successCallback, errorCallback) {
cordova.exec(
successCallback, // success callback function
errorCallback, // error callback function
'Scan', // mapped to our native Java class
'addRemove', // with this action name
[
{
"fullPath":fullPath
}
]
);
}
}
module.exports = Scan;
It's a broadcast action not activity action, you should use the send broadcast method for this kind of action!
http://developer.android.com/reference/android/content/Intent.html#ACTION_MEDIA_SCANNER_SCAN_FILE
This is the wrong line in code " this.cordova.getActivity().startActivity( scanIntent );
"

Is it possible to do a post on the Facebook user's wall and did not authorize, in each case?

Actually I have a problem - I did login to Facebook in my application. I can also do wall posts authorized by the user, but that I needed each time to call the authorization - it takes some time and leads to the fact that on the screen (for a short time), there is "the box" with a white background ( https://dl.dropbox.com/u/41114685/1.JPG ) that is generated (induced) Facebook. That's why I'm interested in whether it is possible to do a post on the user's wall does not cause, each time a method for authentication (to make posts out method onComplete())?
I hope for your help.
package expir.java.file;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
public class FacebookAuthorizeAndPost implements DialogListener{
FacebookAuthorizeAndPost(Activity activity){
this.activity = activity;
}
public void facebookAuthorize(){
facebookClient = new Facebook(APP_ID);
facebookClient.authorize(activity, new String[]{"publish_stream"}, Facebook.FORCE_DIALOG_AUTH, this);
}
public void onComplete(Bundle values) {
if (values.isEmpty())
{
return;
}
if (!values.containsKey("post_id"))
{
try
{
Bundle cont = new Bundle();
cont.putString("message", "bla-bla-bla");
cont.putString("name", "Testing facebook");
cont.putString("link", "www.????????.com");
cont.putString("description", "This is a funny real test!!! This is a funny real test!!! This is a funny real test!!! This is a funny real test!!!");
cont.putString("picture", "http://code.google.com/p/android-developer-scripts/logo?cct=1294556390");
//facebookClient.dialog(activity, "feed", cont, this);
facebookClient.request("me/feed", cont, "POST");
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
}
public void onFacebookError(FacebookError e) {
//
}
public void onError(DialogError e) {
//
}
public void onCancel() {
//
}
public Activity activity;
private final String APP_ID = "??????????????????";
private Facebook facebookClient;
}
You can use isSessionValid() method of Facebook class to check if a valid non-expired session exists, if it doesn't then call the authorize() method otherwise proceed with posting on user's wall.
Also please refer to this post here: http://blog.doityourselfandroid.com/2011/02/28/30-minute-guide-integrating-facebook-android-application/
I have just posted an example of this on another question a couple of mins ago.
See here - logging into facebook

Categories

Resources