Two ACR122U NFC readers on Raspberry Pi3 Android - java

I'm trying to work with two NFC ACR122u readers connected to my Raspberry Pi3 under Android IoT.
I'm utilizing native acssmc-1.1.3.jar library provided by ASC.
Everything is working fine with one reader connected, I'm able to get tagId, turn on/off buzzer/light, but I'm unable to communicate with second reader when both are connected.
So, I'm able to power on both of them, initialize BroadcastReceiver, but when it comes to reader state change listener onCreate method from Reader class in debugger log I see that one reader was closed with message D/UsbDeviceConnectionJNI: close.
The code below initialize and power on both readers. But can't get reader state for both readers, only for one of them 'cause one will be closed right after initialization.
I thought that I have to initialize Reader class for each reader individually, but have no luck with this try as well.
I'm lost at this part. Any help would be really appreciated!
public class MainActivity extends AppCompatActivity {
private static final String ACTION_USB_PERMISSION = "com.android.reader.USB_PERMISSION";
private List<UsbDevice> active_devices = new ArrayList<>(2);
private PendingIntent mPermissionIntent;
private Reader mReader;
private UsbManager mManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mManager = (UsbManager) getSystemService(Context.USB_SERVICE);
Map<String, UsbDevice> connectedDevices = mManager.getDeviceList();
mReader = new Reader(mManager);
int i = 0;
for (UsbDevice device : connectedDevices.values()) {
if (mReader.isSupported(device)) {
active_devices.add(device);
Reader[] Reader = new Reader[2];
Reader[i] = new Reader(mManager);
Reader[i].setOnStateChangeListener(new Reader.OnStateChangeListener() {
#Override
public void onStateChange(int slotNum, int prevState, int currState) {
Log.i("STATE CHANGE", String.valueOf(currState));
if (currState < com.acs.smartcard.Reader.CARD_UNKNOWN || currState > com.acs.smartcard.Reader.CARD_SPECIFIC) {
currState = 0;
}
if (currState == com.acs.smartcard.Reader.CARD_PRESENT) {
Log.i("CARD PRESENT", String.valueOf(slotNum));
}
}
});
i++;
}
}
this.mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_USB_PERMISSION);
filter.addAction("android.hardware.usb.action.USB_DEVICE_DETACHED");
registerReceiver(mReceiver, filter);
powerUp();
}
public void powerUp(UsbManager manager) {
for (UsbDevice device: active_devices) {
manager.requestPermission(device, this.mPermissionIntent);
}
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (MainActivity.ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (!intent.getBooleanExtra("permission", false)) {
Log.i("Permission denied ", device.getDeviceName());
} else if (device != null) {
Log.i("Opening reader:", device.getDeviceName());
new OpenTask().execute(device);
}
}
} else if ("android.hardware.usb.action.USB_DEVICE_DETACHED".equals(action)) {
synchronized (this) {
UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (device != null && device.equals(mReader.getDevice())) {
Log.i("Closing...", "Closing...");
new CloseTask().execute();
}
}
}
}
};
private class CloseTask extends AsyncTask<Void, Void, Void> {
private CloseTask() {
}
protected Void doInBackground(Void... params) {
mReader.close();
return null;
}
protected void onPostExecute(Void result) {
}
}
private class OpenTask extends AsyncTask<UsbDevice, Void, Exception> {
private OpenTask() {
}
protected Exception doInBackground(UsbDevice... params) {
try {
mReader.open(params[0]);
return null;
} catch (Exception e) {
return e;
}
}
protected void onPostExecute(Exception result) {
if (result != null) {
Log.i("Post Execute Result: ", result.toString());
} else {
try{
Log.i("Reader name: ", mReader.getReaderName());
} catch (Exception e){
Log.w("Error", e.getMessage());
}
int numSlots = mReader.getNumSlots();
Log.i("Number of slots: ", String.valueOf(numSlots));
}
}
}
}

Related

How to stop app from accessing the internet when a blacklisted app is installed

I have an app which automatically fetch data online whenever it is opened. I would like to make it a way that the app will only check for update online when a blacklisted app is not detected.
This is the update core.
public class UpdateCore extends AsyncTask<String, String, String> {
private static final String TAG = "NetGuard.Download";
private Context context;
private Listener listener;
private PowerManager.WakeLock wakeLock;
private HttpURLConnection uRLConnection;
private InputStream is;
private TorrentDetection torrent;
private BufferedReader buffer;
private String url;
public interface Listener {
void onLoading();
void onCompleted(String config) throws Exception;
void onCancelled();
void onException(String ex);
}
public UpdateCore(Context context, String url, Listener listener) {
this.context = context;
this.url = url;
this.listener = listener;
}
#Override
protected void onPreExecute() {
listener.onLoading();
}
#Override
protected String doInBackground(String... args) {
try {
String api = url;
if(!api.startsWith("http")){
api = new StringBuilder().append("http://").append(url).toString();
}
URL oracle = new URL(api);
HttpClient Client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(oracle.toURI());
HttpResponse response = Client.execute(httpget);
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
in, "iso-8859-1"), 8);
//BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
str.append(line);
}
in.close();
return str.toString();
} catch (Exception e) {
return "error";
} finally {
if (buffer != null) {
try {
buffer.close();
} catch (IOException ignored) {
}
}
if (is != null) {
try {
is.close();
} catch (IOException ignored) {
}
}
if (uRLConnection != null) {
uRLConnection.disconnect();
}
}
}
#Override
protected void onCancelled() {
super.onCancelled();
// Log.i(TAG, "Cancelled");
// pd.dismiss();
listener.onCancelled();
}
#Override
protected void onPostExecute(String result) {
// wakeLock.release();
//nm.cancel(1);
// pd.dismiss();
try
{
if (result.equals("error"))
{
listener.onException(result);
}
else {
listener.onCompleted(result);
}
}
catch (Exception e)
{
listener.onException(e.getMessage());
}
}
}
This is the detection code
public class TorrentDetection
{
private Context context;
private String[] items;
private TorrentDetection.TorrentListener listener;
private Timer timer;
private Handler handler;
public interface TorrentListener {
public void detected(ArrayList pkg);
}
public TorrentDetection(Context c, String[] i, TorrentListener listener) {
context = c;
items = i;
this.listener = listener;
}
private boolean check(String uri)
{
PackageManager pm = context.getPackageManager();
boolean app_installed = false;
try
{
pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
app_installed = true;
}
catch (PackageManager.NameNotFoundException e)
{
app_installed = false;
}
return app_installed;
}
void check() {
ArrayList arrayList2 = new ArrayList();
for (String pack : items)
{
if(check(pack)){
arrayList2.add(pack);
}
}
if (arrayList2.size() > 0)
{
listener.detected(arrayList2);
stop();
}
}
public void start() {
handler = new Handler();
timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run()
{
handler.post(new Runnable() {
public void run()
{
check();
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 3000);
}
public void stop() {
if(timer != null){
timer.cancel();
timer = null;
}
if(handler != null){
handler = null;
}
}
}
The torrent detection code checks if the following apps are installed and returns a message that an unsupported app is installed.
public class Constraints
{
public static String updater = "https://pastenord.org/raw/random";
public static String[] torrentList = new String[]{
"com.guoshi.httpcanary",
"com.adguard.android.contentblocker"};
}
In my MainActivity this initiates the detection before the online update is done with torrent.start();
void update() {
torrent.start();
new UpdateCore(this, Constraints.updater, new UpdateCore.Listener() {
#Override
public void onLoading() {
}
#Override
public void onCompleted(final String config) {
try {
final JSONObject obj = new JSONObject(MilitaryGradeEncrypt.decryptBase64StringToString(config, Constraints.confpass));
if (Double.valueOf(obj.getString("Version")) <= Double.valueOf(conts.getConfigVersion())) {
} else {
new SweetAlertDialog(MainActivity.this, SweetAlertDialog.CUSTOM_IMAGE_TYPE)
.setTitleText("Update")
.setContentText("\n" + obj.getString("Message"))
.setConfirmText("Yes,Update it!")
.setCustomImage(R.drawable.ic_update)
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sDialog) {
sDialog.dismissWithAnimation();
welcomeNotif();
restart_app();
try {
db.updateData("1", config);
sp.edit().putString("CurrentConfigVersion", obj.getString("Version")).commit();
} catch (JSONException e) {}
}
})
.show();
}
} catch (Exception e) {
// Toast.makeText(MainActivity.this, e.getMessage() , 0).show();
}
}
#Override
public void onCancelled() {
}
#Override
public void onException(String ex) {
}
}).execute();
}
}
It then makes a popup when an unsupported app is detected with this.
torrent = new TorrentDetection(this, Constraints.torrentList, new TorrentDetection.TorrentListener() {
#Override
public void detected(ArrayList pkg)
{
stopService();
new AlertDialog.Builder(MainActivity.this)
.setTitle("unsupported App!")
.setMessage(String.format("%s", new Object[]{TextUtils.join(", ", (String[]) pkg.toArray(new String[pkg.size()]))}))
.setPositiveButton("OK", null)
//.setAnimation(Animation.SLIDE)
.setCancelable(false)
.create()
//.setIcon(R.mipmap.ic_info, Icon.Visible)
.show();
}
});
I would like the make the app only check for online update only when done of the blacklisted apps are installed. Any form of help is welcomed and appreciated.
use this method to check if an application is installed or not
public boolean isPackageInstalled(String packageName, PackageManager packageManager) {
try {
packageManager.getPackageInfo(packageName, 0);
return true;
} catch (PackageManager.NameNotFoundException e) {
return false;
}
}
then to check, simply call:
PackageManager pm = context.getPackageManager();
boolean isInstalled = isPackageInstalled("com.somepackage.name", pm);
// simply put an if statemement
if(!isInstalled){
//do your update here
}
else{
//display you have installed a blacklisted app
}
sidenote, if you are targeting android 11 and above, you need to provide the information about the packages you want to find out about in the manifest like this
<queries>
<!--Add queries here-->
<package android:name="com.somepackage.name" />
</queries>

Send a string through WiFi-Direct between two android devices

It is now over a month that I'm trying to send a string using WiFi-Direct between two android devices, but I'm still struggling hard to understand what I'm doing wrong.
I've looked around forums but they often don't give much detail on how to achieve what I want.
I also went through those two guides from the android developer's website:
Create P2P connections with Wi-Fi Direct
Wi-Fi Direct (peer-to-peer or P2P) overview
I'm using one activity - ActivityConnection - where I toggle the visibility of views depending on whether the user previously chose to send or to receive the string.
Immediatly, on the client side, discoverPeers() looks for any device with WiFi-Direct turned on and displays them on a ListView. Once the user chooses a device and presses the send button, the connection makes itself and the string is sent.
On the server side, the server is immediatly launched using my AsyncServerTask class. There, it waits for a client to connect and to retrieve its sent string.
My main problem is that, after choosing the device and tapping on the send button, the server side isn't receiving anything.
My second problem is that, sometimes, devices aren't being discovered and the listview stays empty.
Am I missing something? Or maybe doing something wrong?
Here's my current code.
I took the liberty to get rid of any line I thought to be out of context to make it easier to read.
ActivityConnection
public class ActivityConnection extends AppCompatActivity implements NewPeersListener {
public static final String CONNECTION_ACTOR = "actor";
public static final String SEND_INFO = "send";
public static final String RECEIVE_INFO = "receive";
ListView listViewDevices;
private IntentFilter intentFilter;
private WifiP2pManager manager;
private WifiP2pManager.Channel channel;
private WiFiDirectBroadcastReceiver receiver;
public List <WifiP2pDevice> listDevices;
private WifiP2pDevice selectedDevice;
#Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
confirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
connectToSelectedDevice();
}
});
Intent intent = this.getIntent();
String actor = intent.getStringExtra(CONNECTION_ACTOR);
this.intentFilter = new IntentFilter();
this.intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
this.intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
this.intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
this.intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
this.manager = (WifiP2pManager) this.getSystemService(Context.WIFI_P2P_SERVICE);
this.channel = this.manager.initialize(this, this.getMainLooper(), null);
this.receiver = new WiFiDirectBroadcastReceiver(this.manager, this.channel, this);
this.listDevices = new ArrayList <> ();
if (actor.equals(SEND_INFO)) {
DeviceAdapter adapter = new DeviceAdapter(ActivityConnection.this, R.layout.device_item, this.listDevices);
this.listViewDevices.setAdapter(adapter);
this.listViewDevices.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectedDevice = listDevices.get(position);
}
});
this.discoverPeers();
}
else if (actor.equals(RECEIVE_INFO)) {
new ServerAsyncTask(this).execute();
}
}
#Override
protected void onResume() {
super.onResume();
this.receiver = new WiFiDirectBroadcastReceiver(this.manager, this.channel, this);
this.registerReceiver(this.receiver, this.intentFilter);
}
#Override
protected void onPause() {
super.onPause();
this.unregisterReceiver(this.receiver);
}
public void resultReceived (String result) {
Toast.makeText(ActivityConnection.this, "Received! :)", Toast.LENGTH_SHORT).show();
}
private void discoverPeers () {
manager.discoverPeers(channel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
// The discovery process succeeded
}
#Override
public void onFailure(int reason) {
// The discovery process DID NOT succeed
Toast.makeText(ActivityConnection.this, "Discovery process DID NOT succeed. Please verify that WiFi-Direct is active.", Toast.LENGTH_LONG).show();
}
});
}
private void connectToSelectedDevice () {
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = this.selectedDevice.deviceAddress;
this.manager.connect(this.channel, config, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
// Send string
Intent serviceIntent = new Intent(ActivityConnection.this, TransferService.class);
serviceIntent.setAction(TransferService.ACTION_SEND_STRING);
serviceIntent.putExtra(TransferService.EXTRAS_GROUP_OWNER_ADDRESS, getMacAddress());
serviceIntent.putExtra(TransferService.EXTRAS_GROUP_OWNER_PORT, 8090);
startService(serviceIntent);
onBackPressed();
}
#Override
public void onFailure(int reason) {
Toast.makeText(ActivityConnection.this, "Connection failed. Try again.", Toast.LENGTH_SHORT).show();
}
});
}
#NonNull
private String getMacAddress () {
try {
List <NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface nif : all) {
if (!nif.getName().equalsIgnoreCase("wlan0")) continue;
byte[] macBytes = nif.getHardwareAddress();
if (macBytes == null) {
return "";
}
StringBuilder result = new StringBuilder();
for (byte b : macBytes) {
result.append(String.format("%02X:",b));
}
if (result.length() > 0) {
result.deleteCharAt(result.length() - 1);
}
return result.toString();
}
} catch (Exception e) {
}
return "02:00:00:00:00:00";
}
#Override
public void newPeers (WifiP2pDeviceList wifiP2pDeviceList) {
this.listDevices = new ArrayList <> (wifiP2pDeviceList.getDeviceList());
DeviceAdapter adapter = new DeviceAdapter(ActivityConnection.this, R.layout.device_item, this.listDevices);
this.listViewDevices.setAdapter(adapter);
}
}
WiFiDirectBroadcastReceiver
public class WiFiDirectBroadcastReceiver extends BroadcastReceiver {
private WifiP2pManager manager;
private WifiP2pManager.Channel channel;
private ActivityConnection activity;
private List <NewPeersListener> listeners;
public WiFiDirectBroadcastReceiver(WifiP2pManager manager, WifiP2pManager.Channel channel, ActivityConnection activity) {
super();
this.manager = manager;
this.channel = channel;
this.activity = activity;
this.listeners = new ArrayList <> ();
this.listeners.add(activity);
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
// Wi-Fi P2P is enabled
} else {
// Wi-Fi P2P is not enabled
Toast.makeText(this.activity, "Please turn on WiFi-Direct (or WiFi-P2P).", Toast.LENGTH_SHORT).show();
}
} else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
// Request available peers from the wifi p2p manager.
if (this.manager != null) {
this.manager.requestPeers(this.channel, new WifiP2pManager.PeerListListener() {
#Override
public void onPeersAvailable(WifiP2pDeviceList peers) {
for (NewPeersListener listener : listeners) {
listener.newPeers(peers);
}
}
});
}
} else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
// Respond to new connection or disconnections
} else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
// Respond to this device's wifi state changing
}
}
}
ServerAsyncTask (server)
public class ServerAsyncTask extends AsyncTask<Void, Void, String> {
private ServerSocket serverSocket;
private Socket clientSocket;
private DataInputStream stream;
private WeakReference <Context> contextWeakReference;
ServerAsyncTask (Context context) {
this.contextWeakReference = new WeakReference <> (context);
}
#Override
protected String doInBackground (Void... params) {
try {
this.serverSocket = new ServerSocket(8090);
this.clientSocket = this.serverSocket.accept();
this.stream = new DataInputStream(this.clientSocket.getInputStream());
String received = this.stream.readUTF();
this.serverSocket.close();
return received;
} catch (IOException e) {
Log.e(TransferService.TAG, Objects.requireNonNull(e.getMessage()));
return null;
} finally {
if (this.stream != null) {
try {
this.stream.close();
} catch (IOException e) {
Log.e(TransferService.TAG, Objects.requireNonNull(e.getMessage()));
}
}
if (this.clientSocket != null) {
try {
this.clientSocket.close();
} catch (IOException e) {
Log.e(TransferService.TAG, Objects.requireNonNull(e.getMessage()));
}
}
if (this.serverSocket != null) {
try {
this.serverSocket.close();
} catch (IOException e) {
Log.e(TransferService.TAG, Objects.requireNonNull(e.getMessage()));
}
}
}
}
/*
* (non-Javadoc)
* #see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
#Override
protected void onPostExecute (String result) {
super.onPostExecute(result);
((ActivityConnection) this.contextWeakReference.get()).resultReceived(result);
}
}
TransferService (client)
public class TransferService extends IntentService {
public static final String TAG = "WIFI_DIRECT";
private static final int SOCKET_TIMEOUT = 5000;
public static final String ACTION_SEND_STRING = "sendString";
public static final String EXTRAS_GROUP_OWNER_ADDRESS = "go_host";
public static final String EXTRAS_GROUP_OWNER_PORT = "go_port";
public TransferService (String name) {
super(name);
}
public TransferService () {
super("TransferService");
}
#Override
protected void onHandleIntent (Intent intent) {
Context context = getApplicationContext();
if (intent.getAction().equals(ACTION_SEND_STRING)) {
String toSend = "string to send";
String host = intent.getExtras().getString(EXTRAS_GROUP_OWNER_ADDRESS);
int port = intent.getExtras().getInt(EXTRAS_GROUP_OWNER_PORT);
Socket socket = null;
DataOutputStream stream = null;
try {
// Create a client socket with the host, port, and timeout information.
socket = new Socket();
socket.bind(null);
socket.connect((new InetSocketAddress(host, port)), SOCKET_TIMEOUT);
Log.d(TAG, "Client connected socket - " + socket.isConnected());
// Send string
stream = new DataOutputStream(socket.getOutputStream());
stream.writeUTF(toSend);
stream.close();
Toast.makeText(context, "Sent! :)", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Log.e(TAG, Objects.requireNonNull(e.getMessage()));
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null) {
if (socket.isConnected()) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
}
In the ActivityConnetion class, I was giving a MAC address instead of an IP address. I don't know why I didn't see this, nor why I did it in the first place. So I looked around this forum and found out how to get the IP address of the WiFi-Direct's group owner: Wifi Direct Group Owner Address .
To get the code running, I went into the ActivityConnetion class, delete the getMacAddress() method and replaced this line:
serviceIntent.putExtra(TransferService.EXTRAS_GROUP_OWNER_ADDRESS, getMacAddress());
with this line:
serviceIntent.putExtra(TransferService.EXTRAS_GROUP_OWNER_ADDRESS, "192.168.49.1");
As the group owner's IP is always the same, one can write it down directly. As doing so can stop working if the IP changes, I would recommend looking for the group owner's IP instead. The link above show's how to do it.

Can't download from Google Play Store when VPN connection is active

I`m trying to implement "Change DNS programmatically logic" in my app. Everything working well but when i try to download/update app thru Google play it's doesn't start only progressing without stop. When i stop my service everything working well and i can download/update apps without any problem.
This is my Service:
public class VPNService extends VpnService {
private VpnService.Builder builder = new VpnService.Builder();
private ParcelFileDescriptor fileDescriptor;
private Thread mThread;
private boolean shouldRun = true;
private DatagramChannel tunnel;
public static final String ACTION_CONNECT = VPNService.class.getName() + ".START";
public static final String ACTION_DISCONNECT = VPNService.class.getName() + ".STOP";
#Override
public void onDestroy() {
if (mThread != null) {
mThread.interrupt();
}
super.onDestroy();
}
#Override
public void onCreate() {
super.onCreate();
startForeground(999, new Notification());
}
private void setTunnel(DatagramChannel tunnel) {
this.tunnel = tunnel;
}
private void setFileDescriptor(ParcelFileDescriptor fileDescriptor) {
this.fileDescriptor = fileDescriptor;
}
#Override
public int onStartCommand(final Intent intent, int flags, int startId) {
if (intent != null && ACTION_DISCONNECT.equals(intent.getAction())) {
onDestroy();
return Service.START_NOT_STICKY;
}
mThread = new Thread(() -> {
try {
setFileDescriptor(builder.setSession(VPNService.this.getText(R.string.app_name).toString()).
addAddress("192.168.0.1", 24).addDnsServer("94.155.240.3").addDnsServer("212.50.87.211").establish());
setTunnel(DatagramChannel.open());
tunnel.connect(new InetSocketAddress("127.0.0.1", 8087));
protect(tunnel.socket());
while (shouldRun)
Thread.sleep(100L);
} catch (Exception exception) {
exception.printStackTrace();
} finally {
if (fileDescriptor != null) {
try {
fileDescriptor.close();
setFileDescriptor(null);
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
mThread.start();
return Service.START_STICKY;
}
public static void startVService(Context context) {
VPNService.prepare(context);
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
ContextCompat.startForegroundService(context,new Intent(context, VPNService.class).setAction(ACTION_CONNECT));
else
context.startService(new Intent(context, VPNService.class).setAction(ACTION_CONNECT));
}catch (RuntimeException e){
Log.d("VPNService","Not allowed to start service Intent",e);
}
}
}
You may have to exclude playstore from the vpn.
https://www.reddit.com/r/ProtonVPN/comments/bzh6ir/apps_not_downloadingupdating_via_google_play/
vpnBuilder.addDisallowedApplication(packageName); // where package name is com.android.vending (Play store)

onPostExecute in AsyncTask with BroadcastReceiver is throwing null pointer exception

When the new message is received, message should be passed to the internet for my further business logic.
To receive the new messages I used onReceive of broadcastreceiver and to process the internet business logics in background I used AsyncTask.
I am getting the null pointer exception in onPostExecute method of AyncTask, I read many stackoverflow and other website solutions and created the interface and initialized it in the AsyncTask extended class constructor. But getting only nullpointer.
My Full code:
MainActivity:
public class SmsActivity extends Activity implements ParseURL.OnAsyncRequestComplete {
private static SmsActivity inst;
public static final String SMS_BUNDLE = "pdus";
public static SmsActivity instance() {
return inst;
}
#Override
public void onStart() {
super.onStart();
inst = this;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sms);
}
#Override
public void processResp(String output){
String outpu1 = output+" in main";
}
}
BroadCastReceiver:
public class SmsBroadcastReceiver extends BroadcastReceiver{
public static final String SMS_BUNDLE = "pdus";
public void onReceive(Context context, Intent intent) {
Bundle intentExtras = intent.getExtras();
if (intentExtras != null) {
Object[] sms = (Object[]) intentExtras.get(SMS_BUNDLE);
String smsMessageStr = "";
boolean rechargeResult = false;
for (int i = 0; i < sms.length; ++i) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i]);
String smsBody = smsMessage.getMessageBody().toString();
String address = smsMessage.getOriginatingAddress();
smsMessageStr += "SMS From: " + address + "\n";
if (smsBody != null) {
String[] splitValues = smsBody.split(" ");
if (splitValues != null && splitValues.length > 0) {
String siteURL = "SITE_URL";
try {
ParseURL.OnAsyncRequestComplete procesInterf = null;
ParseURL urlParse = new ParseURL(procesInterf);
Toast.makeText(context, siteURL, Toast.LENGTH_LONG).show();
new ParseURL(procesInterf).execute(new String[]{siteURL});
} catch (Exception e) {
Toast.makeText(context, "123 "+e.getMessage(), Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(context, "split values is null", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(context, "smsbody is null", Toast.LENGTH_LONG).show();
}
}
}
}
}
}
ParseURL:
public class ParseURL extends AsyncTask<String, Void, String> {
ProgressDialog progressDialog;
OnAsyncRequestComplete caller;
//Context context;
public ParseURL(OnAsyncRequestComplete a) {
caller = a;
// context = a;
}
public interface OnAsyncRequestComplete {
public void processResp(String response);
}
#Override
protected void onPreExecute()
{
progressDialog.setMessage("WAIT...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected String doInBackground(String... strings) {
String responseStatus = "";
try {
if(strings!=null) {
if (null != strings[0]) {
Document doc = Jsoup.connect(strings[0]).timeout(0).get();
if (doc != null) {
String result = doc.select("body").text();
if (null != result) {
if (result.toLowerCase().contains("FAILED".toLowerCase())) {
responseStatus = result;
} else if (result.toLowerCase().contains("SUCCESS".toLowerCase())) {
responseStatus = "SUCCESS";
} else {
responseStatus = "FAILED";
}
} else {
responseStatus = "google";
}
} else {
responseStatus = "facebook";
}
} else {
responseStatus = "youtube";
}
}else{
responseStatus = "ebay";
}
} catch (Throwable t) {
t.printStackTrace();
}
return responseStatus;
}
#Override
protected void onPostExecute(String s) {
caller.processResp(s);
}
}
I tried many solutions which is shared in the stackoverflow and other sites. But I could not solve it. Please do not mark this as duplicate.
Thanks in advance.
Ohh maaan...
ParseURL.OnAsyncRequestComplete procesInterf = null;
ParseURL urlParse = new ParseURL(procesInterf);
public ParseURL(OnAsyncRequestComplete a) {
caller = a;
}
#Override
protected void onPostExecute(String s) {
caller.processResp(s);
}
Are You see mistake?
You pass null to the ParseUrl constructor, so on PosteExecute() tries to call a method of a null callback.
I suspect that you would like to do that
ParseURL.OnAsyncRequestComplete procesInterf = SmsActivity.this;
But it will work, if your SmsBroadcastReceiver class is a inner class of SmsActivity.
You never initialize caller. Basically you set it to null, then you pass it to your AsyncTask, then you try to use it.
You already use the singleton pattern in your Activity, so you were probably after
ParseURL.OnAsyncRequestComplete procesInterf = SmsActivity.instance();

Passing value from Android application and displaying on the console

In Mainactivity.java, I am taking signal strength from wifi 5 times and appending into a service. I pass the arraylist through Intent. I get the value through Intent in the other file. Now, I want to pass this value to java desktop server. I call asynctask method in onStart in Intent. I do not get any error. But no value is getting displayed.
When I do log cat, the value is getting displayed.
Would you please tell me where I am wrong
Main Activity.Java
public class MainActivity extends Activity {
TextView mTextView;
private WifiManager wifiManager;
int count =0; String data ="";
ArrayList<String> arr = new ArrayList<String>();
private String messsage;
private static final IntentFilter FILTER = new IntentFilter(
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.text_id);
wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
registerReceiver(scanReceiver, FILTER);
wifiManager.startScan();
}
#Override
public void onStart() {
super.onStart();
// Register the scan receiver
registerReceiver(scanReceiver, FILTER);
}
#Override
public void onStop() {
super.onStop();
// Unregister the receiver
unregisterReceiver(scanReceiver);
}
public void onClickRefresh(View v) {
count=0;
wifiManager.startScan();
}
BroadcastReceiver scanReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if(count<5){
final StringBuilder sb = new StringBuilder();
List<ScanResult> wifiScanList = wifiManager.getScanResults();
for (ScanResult result : wifiScanList) {
if (result.SSID.equals("Dal")) {
sb.append(""+result.level);
}
}
mTextView.setText("caled" +count + sb + " length is" + sb.length());
arr.add(sb.toString());
count++;
wifiManager.startScan();
}
else if (count==5)
{
Intent i= new Intent(context, javaServiceClass.class);
i.putExtra("stock_list", arr);
context.startService(i);
}
}
};
JavaServiceClass.java
public class javaServiceClass extends Service {
public void onStart(Intent intent, int startId) {
ArrayList<String> stock_list = (ArrayList<String>) intent.getExtras().get("stock_list");
System.out.println(stock_list.get(1) );
messsage = stock_list.get(0);
new Asynctask1().execute(messsage);
}
public class Asynctask1 extends AsyncTask<String, Void, Void> {
private PrintWriter printwriter;
protected Void doInBackground(String... messages) {
final String IP_ADDRESS = "134.190.162.165";
final int DEST_PORT = 4444;
if(messsage !=null){
//Socket client = null;
try {
Socket client = new Socket(IP_ADDRESS, DEST_PORT); // connect to server
printwriter = new PrintWriter(client.getOutputStream(), true);
printwriter.write(messsage); // write the message to output stream
printwriter.flush();
printwriter.close();
client.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
else
{ System.out.println(messsage);}
return null;
I think You should return your value to onPostExecute() method of AsyncTask class and there try print your value, some thing like this:
#Override
protected void onPostExecute(String messsage) {
System.out.println(messsage);
}
just return your message and print It here

Categories