Detect USB in Broadcastreceiver - what am I missing? - android

My code misses something, need your eyes to locate.
I created a USBOnReciever broadcastreceiver.
public class USBOnReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
Toast.makeText(context, "Phone was connected to power" ,Toast.LENGTH_LONG).show();
Log.d("tag", "Phone was connected to power");
}
}
My manifest is:
<application>
<receiver android:name=".USBOnReceiver" android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.UMS_CONNECTED" />
</intent-filter>
</receiver>
</application>
and here is when I stuck.
nothing appears to happen when connecting the USB ( I also tried with power_connected).
I understand I can register the BR either through the manifest or programmaticaly. But not sure how to implement.
In my activity I added
USBOnReceiver myReceiver = new USBOnReceiver();
But it looks so unconnected and useless :-/
Will appreciate your eyes here.

Your code is seems complete. If im not mistaken,
the only issue you have is: You wrote reciever inside your manifest instead of receiver.
So the BroadcastReceiver never got registered correctly.
To the topic of registering in code:
Yeah thats possible. Just create an instance of your receiver
and use Context.registerReceiver(mReceiver, new IntentFilter(...)).
If you have registered in your manifest, there is no need to do that.
BroadcastReceivers only live for the execution of onReceive(). Therefore
the system creates the instances and kills them afterwards.

Related

Android job scheduler not persisted on reboot

I have implemented Job scheduler in my project and it works fine in the case if the app is in background or if the app is killed. But it is not working if the device is rebooted. I have included
JobInfo.Builder mBuilder = new JobInfo.Builder(TASK_ID, mComponentName);
mBuilder.setPersisted(true);
in my builder and
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
in application manifest file.This is how I have added my service to manifest
<service
android:name="com.xxx.xxxx.service.MyJobService"
android:permission="android.permission.BIND_JOB_SERVICE" />
Is there anything else to be included?
Thanks in advance
Register a BroadCastReciever for detecting BOOT_COMPLETED.
<receiver android:name="com.example.startuptest.StartUpBootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
And in your BroadcastReceiver:
public class StartUpBootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
Log.d("startuptest", "StartUpBootReceiver BOOT_COMPLETED");
...
}
}
}
Once a user runs any activity in your app once, you will receive the BOOT_COMPLETED broadcast after all future boots.
I know it is an old question, and you probably already have the solution, but the issue likely was, that JobService caches the UUIDs of the apps that have the permission. You will need to reinstall your app and it is gonna be alright.
Source:
https://android.googlesource.com/platform/frameworks/base/+/5d34605/services/core/java/com/android/server/job/JobSchedulerService.java
You need to call the setPersisted(boolean isPersisted) method.
You can find it in the doc https://developer.android.com/reference/android/app/job/JobInfo.Builder.html#setPersisted(boolean)

Android Receivers not doing as expected

Well honestly, they aren't doing anything at all. Let me start by saying that I know that Android reworked receivers in 3.1, specifically boot control. I know that they made it so that ACTION_BOOT_COMPLETED cannot be used unless the application has been previously launched by the user. However, people have been successful in using them in current application, yet I am never hitting my receivers for my BOOT_COMPLETED or my SHUTDOWN.
Quick Edit - Please look at the bottom of this post for corrected Shutdown Receiver, I have gotten it to work and am now just stuck in my efforts to get BOOT_COMPLETED to work.
My manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.smashingboxes.speedblock"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="12"
android:targetSdkVersion="18" />
<!-- PERMISSIONS -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
...
<!-- RECEIVERS -->
<receiver android:name=".BootReceiver"
android:enabled="true" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<receiver android:name=".ShutdownReceiver" >
<intent-filter>
<action android:name="android.intent.action.SHUTDOWN" />
</intent-filter>
</receiver>
Now my implemented receiver classes are fairly straight forward:
BOOT_COMPLETED Receiver (the one that isn't working)
public class BootReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context c, Intent i) {
Intent starterIntent = new Intent(c, LaunchActivity.class);
// Start the activity (by utilizing the passed context)
starterIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
c.getApplicationContext().startService(starterIntent);
}
}
I have tried different things based on what I have seen as far as solutions, such as altering my launching activity to include
/* May need this, as of 3.1 we can't call BOOT_COMPLETED until the app has been run successfully */
Intent intent = new Intent("com.smashingboxes.speedblock.intent");
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
this.sendBroadcast(intent);
or including this in my boot receiver intent-filter in my manifest
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
Nothing seems to work. When Logs are inserted into my receiver methods they are never hit. Apparently people are still using these two receivers fairly regularly, which is why I am having trouble understanding why neither of them work. Have I missed something with my registration or something?
--EDIT--
I have solved the problem with my shutdown receiver. First, I foolishly forgot the ACTION_ portion of the tag. Secondly, HTC has separate shutdown methods, in my case I needed to add an intent-filter to my Receiver request:
<receiver android:name=".ShutdownReceiver" >
<intent-filter>
<action android:name="android.intent.action.ACTION_SHUTDOWN" />
<action android:name="android.intent.action.QUICKBOOT_POWEROFF" />
</intent-filter>
</receiver>
Now my Shutdown Receiver works, still no luck on the Boot Completed Receiver though.
I found the answer and I think that it is actually important to note, as it seems like an issue others will run into at some point. My issue was that I was launching a "Launcher Activity" called just that, LauncherActivity. Basically, it acted as my gateway to start up services, receivers, and such when the application was launched. It is a very simple Activity class:
public class LaunchActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
/* May need this, as of 3.1 we can't call BOOT_COMPLETED until the app has been run successfully */
Intent intent = new Intent("com.smashingboxes.speedapp.intent");
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
this.sendBroadcast(intent);
}
#Override
protected void onStart(){
super.onStart();
Intent serviceIntent = new Intent(this, MainService.class);
startService(serviceIntent);
// NOTE: It is VERY, VERY important that we DO NOT finish this activity.
// If we do, our BootReceiver will no longer receive its broadcast and
// we won't auto-start on boot
//finish();
}
}
Note that I was calling finish() on the LaunchActivity. The problem with this is that it seemed to tell Android that the application was in the stopped state, meaning that it won't allow the reception of the BOOT_COMPLETED broadcast, even though I had a number of services running in the background. The LauncherActivity MUST stay active throughout the entire life-cycle or the BOOT_COMPLETED receiver becomes useless. Something that I haven't really seen mentioned before, but again something I think is worth noting.

How do I use the intent action USER_PRESENT?

I have a clock widget application, and I need to recognize when the phone has been unlocked or not, I believe I can use action USER_PRESENT for that, but I can't get it to launch in the BroadcastReceiver class, I set it in the manifest like this:
<receiver
android:name="com.myApp.myApp.MyWidgetIntentReceiver"
android:exported="false"
android:label="widgetBroadcastReceiver" >
<intent-filter>
<action android:name="android.intent.action.USER_PRESENT" >
</action>
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="#xml/demo_widget_provider" />
</receiver>
And this is how I trying to get it in the BroadcastReceiver:
public class MyWidgetIntentReceiver extends BroadcastReceiver{
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(Intent.ACTION_USER_PRESENT){
Log.i("TICK", intent.getAction());
}
}
}
It's not firing after I unlock the phone, can you help me out or provide me a better way to check when the phone has been unlocked? thanks!
Remove android:exported="false"
android:exported:
Whether or not the broadcast receiver can receive messages from sources outside its application — "true" if it can, and "false" if not. If "false", the only messages the broadcast receiver can receive are those sent by components of the same application or applications with the same user ID.
Source : developer.android.com
Remove android:exported="false". That worked for me on Stock Android 5
I got it to work by using registerReceiver in the onUpdate method of the AppWidgetProvider class and passing an instance of the BroadcastReceiver class to register the Intent.ACTION_USER_PRESENT, since adding it only in the Manifest was not doing anything. Thank you!

PACKAGE_ADDED BroadcastReceiver doesn't work

I have a broadcast receiver registered in Manifest:
<application ...>
<receiver android:name="com.some.pkg.NewAppReceiver" >
<intent-filter>
<action android:name="android.intent.action.PACKAGE_ADDED" />
</intent-filter>
</receiver>
</appcication>
And the receiver:
public class NewAppReceiver extends BroadcastReceiver {
private static final String TAG = "NewAppReceiver";
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "Intent: " + intent.getAction());
}
}
And nothing is received when I install APK manually or from the Android Market. Why?
Did you run the app that contains this broadcastReceiver before installing the other apps?
Starting at some API version, broadcastReceivers will not work till you execute the app. Put an activity and execute it.
Also , don't forget to add the following into the broadcastReceiver:
<data android:scheme="package" />
EDIT: On Android 8 and above, if your app targets API 27 or more, it will work partially, so you have to register to those events in code and not in manifest. Here's a list of intents that are still safe to use in manifest: https://developer.android.com/guide/components/broadcast-exceptions.html .
The rest should be used in code. More info here
Since android.intent.action.PACKAGE_ADDED is a System Intent (note that your own app will not receive it at its installation), your BroadcastReceiver will receive messages from sources outside your app. Thus, check you did NOT put: android:exported="false"
You also may need to add:
<data android:scheme="package" />
So, your BroadcastReceiver in your AndroidManifest.xml should look like this:
<application ...>
<receiver android:name=".NewAppReceiver" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.PACKAGE_ADDED" />
<data android:scheme="package" />
</intent-filter>
</receiver>
</appcication>
If it still doesn't work, you may try to put an higher priority, such as: android:priority="1000"
Take a look at: http://developer.android.com/guide/topics/manifest/receiver-element.html
Registering receiver from manifest would not work from API 26(android 8). Because it had performance impact on older versions.
But we can register receiver from java code and receive updates of removed and added applications.
val intentFilter = IntentFilter()
intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED)
intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED)
intentFilter.addDataScheme("package")
registerReceiver(YourBroadcastReceiver(), intentFilter)
Are you trying to receive the intent in the application you are installing? The documentation for ACTION_PACKAGE_ADDED says:
Note that the newly installed package does not receive this broadcast.
Another possibility is that this intent might not be delivered to components registered via the manifest but only manually (as described in an answer by Mark Murphy to Stack Overflow question Can't receive broadcasts for PACKAGE intents).
If you try to receive some other package it must be worked.
(As #Savvas noted) If you try to receive your own package's addition you can't receive it. Even if your broadcast receiver has action.PACKAGE_ADDED, receiver's onReceive method isn't triggered.
In this case your best bet is saving this data. By using sharedPreferences, add a key something like "appIsWorkedBefore", and on your launcher Activity's onCreate method set this variable as "true". And you can make your works with respect to this Boolean.
This intent action is no longer available for applications.
This is a protected intent that can only be sent by the system.
https://developer.android.com/reference/android/content/Intent#ACTION_PACKAGE_ADDED

Broadcast intents not received by a service

I have an Android service which sends broadcast intents. I'm trying to get those intents in another application, which is an Android service. I wrote this in my manifest:
<!-- Service -->
<service android:enabled="true" android:name="...MyService"></service>
<!-- Receiver -->
<receiver android:name="...MyReceiver">
<intent-filter>
<action android:name="..."></action>
<action android:name="..."></action>
</intent-filter>
</receiver>
and this in my MyReceiver class:
public class ScannerBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// Process action.
Log.d(Globals.LOG_TAG, "Intent received.");
...
Unfortunately I never get the onReceive method invoked. Any idea why?
I start this service from another test application, so this is set as an Android library. The service is correctly started but this receiver is receiving nothing. Any idea what I'm doing wrong?
Thanks!
In manifest must be: android:name=".[package].ScannerBroadcastReceiver"
I solved the problem and I suppose it is due to the fact that this project was set as a library. If I don't set it this way the intent is correctly received. I haven't read about this anywhere.

Categories

Resources