Janusz
Janusz

Reputation: 189554

How to only check the Networkstatus if the needed permission is avaiable?

I work on a library that does some tricks if the user is not online. For this I request the network status like this:

ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = connectivityManager.getActiveNetworkInfo();
boolean isConnected = !(info == null || !info.isConnected());

How can I only do this check if the permission

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

is available?

I don't want to force all downstream projects of the lib to require this permission only for the tricks in the library.

Upvotes: 0

Views: 67

Answers (1)

I think you should use checkPermission utility.

http://developer.android.com/reference/android/content/pm/PackageManager.html#checkPermission%28java.lang.String,%20java.lang.String%29

int res = getContext().checkCallingOrSelfPermission(Manifest.permission.ACCESS_NETWORK_STATE);
return (res == PackageManager.PERMISSION_GRANTED);   

Upvotes: 1

Related Questions