|
Did you ask for these permissions in the manifest file? Permissions granted there, are typically available for the device and you can "rely" on the fact that they are granted. Since you are requesting the permission on runtime, during the session it is likely that your application will require to request it again.
Also, note that moving upwards from Android 6.0 users can accept or deny permissions granted during install time as well, so there is very less that you can do other than PermissionManager object to always check if you have permissions, otherwise it will always end up with a runtime error. Control your app permissions on Android 6.0 and up - Google Play Help
There are even facts more to the story, read, Everything every Android Developer must know about new Android's Runtime Permission :: The Cheese Factory.
Post above: In Android 6.0 Marshmallow, application will not be granted any permission at installation time. Instead, application has to ask user for a permission one-by-one at runtime.
In other words, it is the only way to go as it guarantees that the code will execute in the case when you have the permission.
Also, this allows users to enable permissions by default in the settings, so in case your users are loving your application and they want to grant it some permissions they can (through this permissions model) go to the settings and allow permissions for the features they want your application to always work; read the Google Play Help link I provided.
Not recommended approach: You can create a singleton pattern in Android application and then request the permissions on the startup, then during the entire Android's awake period, it will have the permission but upon a restart it will request them again. But nonetheless, this is the least or not at all recommended approach from me.
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: Not recommended approach: You can create a singleton pattern in Android application and then ....
You are absolutely right. I am following this pattern. I don't exactly know why but I am using it (See PermissionManager ). I guess I wanted to seperate this part from MainActivity. Question is: WHY IS IT DOING IT? WHY IT IS ASKING FOR PERMISSIONS AGAIN???? WHAT IS THE SOLUTION??
|
|
|
|
|
Django_Untaken wrote: Question is: WHY IS IT DOING IT? WHY IT IS ASKING FOR PERMISSIONS AGAIN???? WHAT IS THE SOLUTION?? Instead of shouting, (which is never going to work here as we are not bound to do anything), just re-read the reply.
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: Instead of shouting,...
I did not shout. I would never. I just capitalized my questions. In the last 10 years as codeproject user, I never saw "A" telling "B" not to shout just because "B" wrote questions in capitals. However things can be misinterpreted when in written form.
|
|
|
|
|
Django_Untaken wrote: I did not shout. ... I just capitalized my questions.
Typing in ALL CAPS is the internet equivalent of shouting. This is common knowledge, and applies to the entire internet, not just CodeProject.
Django_Untaken wrote: In the last 10 years as codeproject user, I never saw "A" telling "B" not to shout just because "B" wrote questions in capitals.
Then you haven't been looking very hard. Every time someone posts a question in ALL CAPS, they have quickly been rebuked for shouting and, where possible, their message has been edited to the correct case.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
I want to check every second if /sys/bus/usb/devices/ directory is empty or it contain files because I want to make text inside app that says otg not connected if directory is empty or to say otg connected if directory contain files and I want to check that outside the app,while it runs in background! I need to check every second if directory is empty or it contain files?
I have crated detection using alarm manager but it doesn't work.It's just repeating "otg connected"
MainActivity.class
public class MainActivity extends AppCompatActivity
{
private Process suProcess;
private PendingIntent pendingIntent;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getRoot();
startAlarm();
}
private void getRoot()
{
try
{
suProcess = Runtime.getRuntime().exec("su");
}
catch (IOException e)
{
}
}
private void startAlarm()
{
Intent alarmIntent = new Intent(MainActivity.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
int interval = 1000;
manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
}
}
Alarm Receiver.class
public class AlarmReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context,Intent intent)
{
File[] listFiles = new File("/sys/bus/usb/devices").listFiles();
if (listFiles == null) Toast.makeText(context,"otg not connected",Toast.LENGTH_SHORT).show();
if (listFiles != null) Toast.makeText(context,"otg connected",Toast.LENGTH_SHORT).show();
}
}
|
|
|
|
|
|
Directory "/sys/bus/usb/devices" is empty when otg cable is not attached !!!!
|
|
|
|
|
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();
}
}
|
|
|
|
|