|
Then use your debugger to find out what is happening. As we keep telling you.
|
|
|
|
|
What happens is that his directory is indeed there, but he does not check up against files or other stuff inside the directory. I tried to explain the process to him in the post below, as well as another suggestion that will make his application not throttle CPU every 1 second to check if the directory was modified or not.
The sh*t I complain about
It's like there ain't a cloud in the sky and it's raining out - Eminem
~! Firewall !~
|
|
|
|
|
Afzaal Ahmad Zeeshan wrote: I tried to explain Largely a waste of time it seems.
|
|
|
|
|
Richard MacCutchan wrote: Largely a waste of time it seems. By the number of his interactions in the forum, indeed.
The sh*t I complain about
It's like there ain't a cloud in the sky and it's raining out - Eminem
~! Firewall !~
|
|
|
|
|
First of all, my recommendation is to consider using the FileObserver in Android, instead of triggering that each second to check if there are files or not. That is a good approach towards going through what you want to do.
Secondly, as Richard mentioned, the reason is that the list object is not null, that doesn't mean its count or length or size is also zero. Just to show you what I really mean, here is a sample code,
File directory = new File("/path/to/folder");
File[] contents = directory.listFiles();
if(contents == null) {
} else if(contents.length == 0) {
} else {
}
You can update your code, to meet this structure and then show the Toast notifications in Android. So kindly implement these two things, first of all that service will help you not throttle CPU every second.
For an example of FileObserver please see: java - How do you implement a FileObserver from an Android Service - Stack Overflow.
file io - How to check if a directory is empty in Java - Stack Overflow
The sh*t I complain about
It's like there ain't a cloud in the sky and it's raining out - Eminem
~! Firewall !~
|
|
|
|
|
Now when I launch it shows otg not connected and it's repeating it many times and when I plug in otg cable it's still repeating "otg not connected" and after some time it shows "otg connected" !!!!
When I start app it shouldn't show anything, it should only show when I plug in or when I plug out otg cable.And it shouldn't repeat same message many times !!!!
public class AlarmReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context,Intent intent)
{
File directory = new File("/sys/bus/usb/devices");
File[] contents = directory.listFiles();
if(contents.length == 0)
{
Toast.makeText(context,"otg not connected",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(context,"otg connected",Toast.LENGTH_SHORT).show();
}
}
}
modified 29-Jan-17 9:54am.
|
|
|
|
|
That is because there are a few Toasts already in the queue, that need to be rendered. That is one of the backdrops of this timer trigger.
The sh*t I complain about
It's like there ain't a cloud in the sky and it's raining out - Eminem
~! Firewall !~
|
|
|
|
|
I don't understand!What should I do?
|
|
|
|
|
|
Pavlex4 wrote: I want to check every second if /sys/bus/usb/devices/ directory is empty or it contain files...I need to check every second if directory is empty or it contain files? Bad idea. All that does is needlessly tie up the CPU.
"One man's wage rise is another man's price increase." - Harold Wilson
"Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons
"You can easily judge the character of a man by how he treats those who can do nothing for him." - James D. Miles
|
|
|
|
|
Than what's the better way to do this?
|
|
|
|
|
FileObserver[^]
"One man's wage rise is another man's price increase." - Harold Wilson
"Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons
"You can easily judge the character of a man by how he treats those who can do nothing for him." - James D. Miles
|
|
|
|
|
Why it's not working?
public class MainActivity extends AppCompatActivity
{
private Process suProcess;
private static int conn_length = -1;
File directory = new File("/sys/bus/usb/devices");
File[] contents = directory.listFiles();
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getRoot();
FileObserver observer = new FileObserver("/sys/bus/usb/devices")
{
@Override
public void onEvent(int event, String file)
{
if(contents.length == conn_length){
return;
}
else{
conn_length = contents.length;
}
if(conn_length == 0)
{
Toast.makeText(MainActivity.this,"otg not connected",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this,"otg connected",Toast.LENGTH_SHORT).show();
}
}
};
observer.startWatching();
}
private void getRoot()
{
try
{
suProcess = Runtime.getRuntime().exec("su");
}
catch (IOException e)
{
}
}
}
|
|
|
|
|
Define "not working."
Since you asked for ALL_EVENTS , your event handler is potentially going to get called for a lot of events, yet you are not checking for any of them. Is that intentional?
You are calling listFiles() once before startWatching() . I would think that you'd want to call listFiles() only after a CREATE event.
"One man's wage rise is another man's price increase." - Harold Wilson
"Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons
"You can easily judge the character of a man by how he treats those who can do nothing for him." - James D. Miles
|
|
|
|
|
I have changed code to this but it still won't show message when cable is connected or disconnected !!!!
public class MainActivity extends AppCompatActivity
{
private Process suProcess;
private static int conn_length = -1;
File directory = new File("/sys/bus/usb/devices");
File[] contents;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getRoot();
FileObserver observer = new FileObserver("/sys/bus/usb/devices")
{
@Override
public void onEvent(int event, String file)
{
if(event == FileObserver.CREATE)
{
contents = directory.listFiles();
if (contents.length == conn_length)
{
return;
}
else
{
conn_length = contents.length;
}
if (conn_length == 0)
{
Toast.makeText(MainActivity.this, "otg disconnected", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this, "otg connected", Toast.LENGTH_SHORT).show();
}
}
}
};
observer.startWatching();
}
private void getRoot()
{
try
{
suProcess = Runtime.getRuntime().exec("su");
}
catch (IOException e)
{
}
}
}
|
|
|
|
|
Did you set a breakpoint in the event handler? Using the debugger, what is the value of event , contents , and conn_length ?
"One man's wage rise is another man's price increase." - Harold Wilson
"Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons
"You can easily judge the character of a man by how he treats those who can do nothing for him." - James D. Miles
|
|
|
|
|
How to use app to detect when otg cable is plugged in and when it's plugged out? Is there intent for otg cable like this for usb devices: "android.hardware.usb.action.USB_DEVICE_ATTACHED"
I have created app like this but I only detects flash drive not otg cable:
public class MainActivity extends AppCompatActivity
{
private TextView mInfo;
private Logger mLogger;
private HashMap<UsbDevice, UsbDataBinder> mHashMap = new HashMap<UsbDevice, UsbDataBinder>();
private UsbManager mUsbManager;
private PendingIntent mPermissionIntent;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mInfo = (TextView)findViewById(R.id.log);
mLogger = new Logger(this);
mLogger.setMode(Logger.MODE_TOAST);
mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
usbConnection();
}
private void usbConnection() {
IntentFilter filter = new IntentFilter(UsbManager.ACTION_USB_DEVICE_ATTACHED);
registerReceiver(mUsbAttachReceiver , filter);
filter = new IntentFilter(UsbManager.ACTION_USB_DEVICE_DETACHED);
registerReceiver(mUsbDetachReceiver , filter);
mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver, filter);
showDevices();
}
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mUsbDetachReceiver);
unregisterReceiver(mUsbAttachReceiver);
unregisterReceiver(mUsbReceiver);
};
BroadcastReceiver mUsbDetachReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (device != null) {
UsbDataBinder binder = mHashMap.get(device);
if (binder != null) {
binder.onDestroy();
mHashMap.remove(device);
Toast.makeText(MainActivity.this, "Attached!", Toast.LENGTH_SHORT).show();
}
}
}
}
};
BroadcastReceiver mUsbAttachReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
showDevices();
Toast.makeText(MainActivity.this, "Detached!", Toast.LENGTH_SHORT).show();
}
}
};
private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbDevice device = (UsbDevice) intent
.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(
UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if (device != null) {
UsbDataBinder binder = new UsbDataBinder(mUsbManager, device);
mHashMap.put(device, binder);
Toast.makeText(MainActivity.this, "Permission Granted!", Toast.LENGTH_SHORT).show();
}
} else {
}
}
}
}
};
private void showDevices() {
HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
while(deviceIterator.hasNext()){
UsbDevice device = deviceIterator.next();
mUsbManager.requestPermission(device, mPermissionIntent);
mLogger.log("usb", "name: " + device.getDeviceName() + ", " +
"ID: " + device.getDeviceId());
mInfo.append(device.getDeviceName() + "\n");
mInfo.append(device.getDeviceId() + "\n");
mInfo.append(device.getDeviceProtocol() + "\n");
mInfo.append(device.getProductId() + "\n");
mInfo.append(device.getVendorId() + "\n");
}
}
@Override
protected void onResume() {
super.onResume();
}
}
|
|
|
|
|
Why have you reposted this question? You have already been given a number of suggestions below.
|
|
|
|
|
Hello there. I am trying to make a simple http POST request using HttpUrlConnection. Problem is that response code is 200 but the response message NOT success.
You can see that I set all the necessary header parameters. I am supposed to get success message. But I get {"status":false,"message":"Invalid access"} with responseCode = 200.
Below is the code (I am developing against Lollipop)
protected SubmitRequestTask.ResponseObject doInBackground(Object... object)
{
String encodedStr = URLEncoder.encode(object.getDataToSendRAW(), "UTF-8");
BufferedReader reader = null;
int responseCode = -1;
try
{
URL url = new URL();
Map<String, String> headerParams = new HashMap<String, String>();
headerParams.put("Accept", "application/json");
headerParams.put("Content-Type", "application/json");
HttpUrlConnection networkConnection = MakeRequest(
url,
"POST",
headerParams,
null);
if(networkConnection == null)
return new ResponseObject(-1, "Uknown Error");
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(networkConnection.getInputStream()));
while ((response = reader.readLine()) != null)
sb.append(response + "\n");
response = sb.toString();
}
catch(Exception ex) {}
finally {
responseCode = networkConnection.getResponseCode();
networkConnection.disconnect();
}
return new ResponseObject(responseCode, response);
}
private HttpUrlConnection MakeRequest(URL url, String method, Map<String, String> headerParams, NetworkConfig config)
{
HttpURLConnection htp_url_connection = (HttpURLConnection) url.openConnection();
htp_url_connection.setRequestMethod(method);
if (headerParams != null && method.trim().toLowerCase().equals("post"))
{
htp_url_connection.setDoOutput(true);
for (Map.Entry<String, String> entry : headerParams.entrySet()) {
(htp_url_connection.setRequestProperty(entry.getKey(), entry.getValue());
}
if (encodedStr.trim().length() > 0) {
OutputStreamWriter writer = new OutputStreamWriter(htp_url_connection.getOutputStream());
writer.write(encodedStr);
writer.flush();
}
}
htp_url_connection.setConnectTimeout(5000);
int responseCode = htp_url_connection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK )
return htp_url_connection;
}
Sample JSON data (which I encode in doInBackground).
{
"plot_unique_id":"355618",
"plot_physical_address":"owner",
"plot_id":"355617",
"location":"31.475885,74.3422574",
"action_type":"1",
"plot_sub_id":"1",
"apk_version":"1.0",
"imei_no":"862037029044152",
"owners":[......]
}
What could be the problem?? Thanks for any input.
|
|
|
|
|
That is correct; the HTTP response is 200 telling you that the server responded with some data. The response data is a JSON reply which contains information about the JSON request. You need to contact the owners of the website, or the documentation, to find out why it returned the "Invalid access" status.
|
|
|
|
|
How to detect OTG Cable when plugged in inside micro usb port and enable switch inside app?
|
|
|
|
|
What was the answer given to you for your previous post? Just read the answer 1 thread below.
Never mind.
The sh*t I complain about
It's like there ain't a cloud in the sky and it's raining out - Eminem
~! Firewall !~
modified 21-Jan-17 18:59pm.
|
|
|
|
|
This has nothing to do with windows.I want to detect when OTG Cable is plugged inside inside android usb port and go to app and enable switch!!!
|
|
|
|
|
That was just an example to give you an example of how other devices can prevent your device from making changes, unless provided with enough permissions.
The sh*t I complain about
It's like there ain't a cloud in the sky and it's raining out - Eminem
~! Firewall !~
|
|
|
|
|
How to also give permission?
|
|
|
|