W/System: A resource failed to call release. Broadcast receiver - java

When I try to get broadcast for incomming call:
BroadcastReceiver br = new MyBroadcastReceiver();
IntentFilter filter = new IntentFilter(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
filter.addAction(Intent.ACTION_SCREEN_OFF);
MainApplication.getAppContext().registerReceiver(br, filter);
I got an error when doing or receiving a call:
W/System: A resource failed to call release.
The ACTION_SCREEN_OFF works fine, but ACTION_PHONE_STATE_CHANGED do not. My APP has a webRTC connection open. In other APP that dosen't work with webRTC, ACTION_PHONE_STATE_CHANGED works fine.
I'm trying to make the audio back to speaker after a incomming call.
Some clue? Thanks!

The problem was that I haven't set uses-permission in the manifest.
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
And of course, you have to ask the user to use the PHONE_STATE.
React-native way:
(async () => {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.READ_PHONE_STATE,
{
'title': 'ReactNativeCode Location Permission',
'message': 'ReactNativeCode App needs access to your phone state '
}
)
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
Alert.alert("Location Permission Granted.");
}
else {
Alert.alert("Location Permission Not Granted");
}
} catch (err) {
console.warn(err)
}
})()

Related

How can i disable any android app such that it cannot be opened until i change/press some button in app?

I am trying to build a parental control app. So now i want to disable or lock app (like Whatsapp, Facebook, etc). I have tried using PackageManager.setComponentEnabledSetting(). But it is throwing java.lang.SercurityException.
So how can I make a parental control app such that I can disable any app I want without root.
my code is
pm.setComponentEnabledSetting(new ComponentName(temp.activityInfo.packageName,
temp.activityInfo.name+".class"),
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
my error was this
java.lang.SecurityException: Permission Denial: attempt to change component state from pid=11537, uid=10067, package uid=10029
You must add below permissions to manifest.
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS"/>
but , these permissions are for System apps and you can not use. :(
You can not write a app to lock or close another app.this is a policy in Google.
for lock a app you must check running apps repeatedly, if specific app is open,then show a activity over that.
while(!Thread.currentThread().isInterrupted())
{
String topActivity = getFrontApp();
if(topActivity.isEmpty())
{
threadSleep(500);
continue;
}
if(topActivity.equals("lockApp"))
{
showLockActivity();
}
threadSleep(500);
}
// for Api21+ need permission
public static String getFrontApp()
{
if (Build.VERSION.SDK_INT >= 21)
{
UsageStatsManager usageManager = SystemMaster.getUsageStatsManager();
long now = System.currentTimeMillis();
List<UsageStats> localList = usageManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, now - 900_000L, now);
String str = "";
if (localList != null)
{
SortedMap<Long,UsageStats> mySortedMap = new TreeMap<>();
for(UsageStats usageStats : localList)
mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
if(!mySortedMap.isEmpty())
str = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
}
return str;
}
else
{
ActivityManager am = (ActivityManager) getApplication().getSystemService(Context.ACTIVITY_SERVICE);
return am.getRunningTasks(1).get(0).topActivity.getPackageName();
}
above code is very simple , for real app must write more.

Security Exception: Permission Denial

The app used to run. However, just recently it began to stop working. The device is running Android Nutella. Below is the LogCat.
java.lang.SecurityException: Permission Denial: reading com.google.android.music.store.ConfigContentProvider uri content://com.google.android.music.ConfigContent/one-key/2/ExplicitRestrictedByParentControl from pid=2500, uid=10373 requires the provider be exported, or grantUriPermission()
The app crashes in the the following code snippet on the last line(contained in a SongParser method).
String[] projection2 = {MediaStore.Audio.Media.ARTIST};
Uri songUri=null;
try {
songUri = Uri.parse("content://com.google.android.music.MusicContent/audio");
} catch (NullPointerException e){
e.printStackTrace();
}
if (songUri!=null) {
CursorLoader cl2 = new CursorLoader(context,
songUri, projection2, null, null, null);
cursor = cl2.loadInBackground();
I grant the Uri permissions in the following method after asking for permissions through the runtime permissions methods.
private void startService() {
//start intent to RssService for feedback
intent = new Intent(getActivity(), SongService.class);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
getContext().grantUriPermission("xxx.xxx.xxx.SongService",Uri.parse("content://com.google.android.music.MusicContent/audio"),Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.putExtra(SongService.RECEIVER, resultReceiver);
getActivity().startService(intent);
}
Here is where SongService calls SongParser.
#Override
protected void onHandleIntent(Intent intent) {
List<String> eventItems= null;
if (haveNetworkConnection()) {
parser = new SongParser();
eventItems = parser.getAllArtists(getApplicationContext());
}
Bundle bundle = new Bundle();
bundle.putSerializable(ITEMS, (Serializable) eventItems);
ResultReceiver receiver = intent.getParcelableExtra(RECEIVER);
receiver.send(0, bundle);}}
I have contained the permissions in the manifest as well. Again, this exception seemingly happened on its own.
<permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
What's happening is that for some reason, the (exported) MusicContent provider will redirect to ConfigContentProvider, which is not exported.
It seems that the way to solve it is to open Google Play Music. If you haven't launched it in a while, it will redirect to com.google.android.music.store.ConfigContentProvider and trigger a SecurityException. It's kind of problematic but at least I can tell my users what to do. Let me know if you can come up with something better.
It might also be a good idea to file a bug.
You do not have access to that ContentProvider. It is not exported, and that app did not pass you a Uri that you can use to access it.
Since presumably the Uri is from an app that you did not write, apparently an update to that app changed this behavior.

Add android.permission.MANAGE_USB permission to existing system application

We have an application installed on a rooted device as a system application. The latter doesn't have the android.permission.MANAGE_USB and we want to add it to a newer version so that the permission is given to the user automatically. I have followed the post:
bypass android usb host permission confirmation dialog
More specifically, the answer marked as correct from the user d_d_t.
Why doesn't it work? I mean, I have taken this newer version, directly installed it as our original system application and it works perfectly! But when I update the existing version with no usb permission with the newer version it just doesn't work. The new one is just an update. Same certificate and all.
I'm at a loss. Any thoughts?
Our code below:
AndroidManifest.xml.
<uses-permission
android:name="android.permission.MANAGE_USB"
android:protectionLevel="signature" />
Java class.
try {
PackageManager pm = getApplicationContext().getPackageManager();
ApplicationInfo ai = pm.getApplicationInfo(getApplicationContext().getPackageName(), 0);
if (ai != null) {
UsbManager manager = (UsbManager) getApplicationContext().getSystemService(Context.USB_SERVICE);
IBinder b = ServiceManager.getService(Context.USB_SERVICE);
IUsbManager service = IUsbManager.Stub.asInterface(b);
HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
while (deviceIterator.hasNext()) {
UsbDevice device = deviceIterator.next();
if (device.getVendorId() == 0x0403) {
service.grantDevicePermission(device, ai.uid);
service.setDevicePackage(device,getApplicationContext().getPackageName(), 0);
}
}
}
} catch (Exception e) {
Log.e("UsbReceiver", "exception " + e);
e.printStackTrace();
}

Sometimes Android BroadcastReceiver does not work

After reading a lot of topics on SOF & blog post, I have got the BroadcastReceiver working. But I have noticed sometime it does not work, specially when I am on call. I just want to know, does BroadcastReceiver work if I get SMS in-between the call ? or there is something is wrong in the code.
SmsReceiver.java
public class SmsReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Log.d("SmsReceiver Broadcast", "OK");
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
Log.d("Network is connected. Executing TheTask()", "OK");
new TheTask().execute("http://somedomain.tld/index.php?userId=12345678");
}
if (networkInfo == null) {
Log.d("Network is NOT connected.", "FAIL");
}
}
class TheTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... arg0) {
String text = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(arg0[0]);
HttpResponse resp = httpclient.execute(httppost);
HttpEntity ent = resp.getEntity();
text = EntityUtils.toString(ent);
} catch (Exception e) {
e.printStackTrace();
}
return text;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
String tocheck = "Some text";
if(result.contains(tocheck))
{
Log.d("string contains some text", result);
}
}
}
}
AndroidManifest.xml
<receiver android:name=".SmsReceiver" android:enabled="true" >
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
I am using 3G network. It may be due to network disconnects. If so, is there any workaround to execute AsyncTask when my phone again get data network ?
EDIT:
Wrapped the AsyncTask into isConnected. Now if the phone is not connected to Internet & I get SMS the AsyncTask will not be executed. In that situation I want to use ScheduledExecutorService to schedule AsynckTask to be executed 4 times at the interval of 5 minutes within next 20 minutes. I will be highly obliged anyone can help me in this.
I cannot be sure about the disconnects since you haven't provided any stack trace. But I am pretty sure the SMS_RECEIVED broadcast action is being broadcasted system-wide when you receive sms. Now if you do not receive SMS due to bad connection or no connection at all it's perfectly logical for the system not to trigger an SMS_RECEIVED action since no SMS was received.
As for the
is there any workaround to execute AsyncTask when my phone again get
data network
you can implement another Broadcast Receiver that will listen for network changes but that doesn't seem such a good idea. You should try and reproduce the problem and check for any exceptions in your stack trace.
is something is wrong in the code.
Your receiver seems to be properly registered in your manifest,
the onReceive() method seems to be properly launching the AsyncTask,
the doInBackground doesn't seem to have any problem and onPostExecute (although the official example seems to omit any call to super) seems to be just fine.
Conclusion: Try to reproduce the problem and gather data from the stack trace as to what might cause the error (network overhead might be one the causes but that's just speculation).

Android Send SMS Crash

I want to sent SMS with my Application with :
Intent smsIntent = new Intent(Intent.ACTION_VIEW);
smsIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
smsIntent.setData(Uri.parse("smsto:" + sms));
smsIntent.putExtra("smsto", sms);
smsIntent.putExtra("sms_body", "MYSMSBOBY");
mActivity.startActivity(smsIntent);
It's work fine in devices that there is SMS Application, but in some devices i get this crash error:
No Activity found to handle Intent { act=android.intent.action.VIEW dat=smsto:xxxxxxxxxx flg=0x10000000 (has extras) }
Any idea how i can recognize if SMS Application installed on the device?
Any idea how i can recognize if SMS Application installed on the device?
While you can use PackageManager to see if there's any app to handle your intent, that's should not be really of your concern at all. What you should take care of is just the crash itself, so instead of just:
mActivity.startActivity(smsIntent);
you should at least have generic exception handling code:
try {
mActivity.startActivity(smsIntent);
} catch ( Exception e ) {
e.printStackTrace();
// show toast or something so user knows why it is not working
}
and catch any failure of startActivity(). You may also want to make create separate catch for this particular type of exception, ActivityNotFoundException
<!-- SMS -->
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
/**
* Test if device can send SMS
* #param context
* #return
*/
public static boolean canSendSMS(Context context) {
return context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELEPHONY);
}

Categories