Android: how to launch my app upon receiving a specific Broadcast? - android

I am trying to get my app automatically launched when the phone gets connected to wifi. Here's the code I am using to both set the Broadcast receiver and to specify that once the broadcast is received I want the "Connected" activity to be launched:
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
receiver = new BroadcastReceiver(){
public void onReceive(Context context, Intent intent){
Intent intent2 = new Intent(getApplicationContext(),com.example.package.Connected.class);
startActivity(intent2);
}
};
registerReceiver(receiver,intentFilter);
Unfortunately it's not working. The logcat says my activity has "leaked IntentReceiver".
Does anyone know how I can solve this?
EDIT: I also tried to register the receiver via the Manifest file. I added this code to the manifest:
<receiver android:name="com.example.package.receiver">
<intent-filter>
<action android:name="android.net.wifi.STATE_CHANGE" />
</intent-filter>
</receiver>
And then this code to my main activity:
private BroadcastReceiver receiver = new BroadcastReceiver(){
public void onReceive(Context context, Intent intent){
Intent intent2 = new Intent(getApplicationContext(),com.example.package.Connected.class);
context.startActivity(intent2);
}
};
But now my app crashes once the phone connects to wifi. Logcat says "RuntimeException: Unable to instantiate receiver".
Any ideas how to solve it?

I am trying to get my app automatically launched when the phone gets connected to wifi.
Register your BroadcastReceiver in the manifest, using a <receiver> element, and have the receiver call startActivity() on the Context supplied in the onReceive() method.
Note that users may not appreciate your popping up an activity just because the device connected to WiFi.

as Per link and Activity has leaked IntentReceiver
Unregister the Broadcast Receiver that you created in the onCreate()
In the onRestart() re-register a brand new Broadcast Receiver.

Related

Sending broadcast from one process to another process

This is my requirement.
I have an application which can be force kill by user. I want this application to receive broadcast from other app to execute some task even it is forced kill.
I am trying to make another app with service which will send a broadcast in event 1 mins to my first application.
My first application should receive this broadcast even it is forced kill.
This is what I am trying to do.
in First app:
BroadcastReceiver dummy = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.e("broadcast Received","broadcast Received");
}
};
IntentFilter filter = new IntentFilter("com.action.blockapp");
registerReceiver(dummy,filter);
In my second app.
Intent intent = new Intent("com.action.blockapp");
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
intent.setPackage("com.example.myapplication2");
sendBroadcast(intent);
I am not able to receive the broadcast when my app is forced kill.
Please suggest.
My point . You need to declare revice in the service running in the background. Your specific revice declared in the manifest<receiver android:name=".service.NotifyReceiver" />
</application>
When the service is run. You can get notifications from revice like below
Intent intent1 = new Intent(context, NotifyReceiver.class);
intent1.setAction(action);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
Hope to help you!
You have registered your BroadcastReceiver dynamically, in code. When your app is force stopped, that code is no longer running and your BroadcastReceiver no longer exists. It is no longer registered.
You will need to create a proper class that extends BroadcastReceiver and create a manuifest entry <receiver> for that with an <intent-filter> that matches the broadcast Intent you are broadcasting.

Screen ON/OFF receiver in android [duplicate]

I was just wondering if it is possible to register a broadcast receiver that detects Screen ON/OFF in the application manifest.
The reason why I don't like the programmable method is that it requires the app to be running in order to detect such a thing, while:
"Applications with Broadcast Receivers registered in the manifest don’t have to be running when the Intent is broadcast for the receivers to execute" (source: Professional Android 2 Application Development book)
My app is actually a lockscreen app which by using the programmable way needs to be running all the time :S
Is there a way around it?
I'm trying the following in the manifest:
<receiver android:name=".MyBroadCastReciever">
<intent-filter>
<action android:name="android.intent.action.SCREEN_OFF"/>
<action android:name="android.intent.action.SCREEN_ON"/>
</intent-filter>
</receiver>
and simple MyBroadCastReciever class:
public class MyBroadCastReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
Log.i("Check","Screen went OFF");
Toast.makeText(context, "screen OFF",Toast.LENGTH_LONG).show();
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
Log.i("Check","Screen went ON");
Toast.makeText(context, "screen ON",Toast.LENGTH_LONG).show();
}
}
}
The two actions for screen on and off are:
android.intent.action.SCREEN_OFF
android.intent.action.SCREEN_ON
But if you register a receiver for these broadcasts in a manifest, then the receiver will not receive these broadcasts.
For this problem, you have to create a long running service, which is registering a local broadcast receiver for these intents. If you do this way, then your app will look for screen off only when your service is running which won't irritate user.
PS: start the service in foreground to make it running longer.
A simple code snippet will be something like this:
IntentFilter screenStateFilter = new IntentFilter();
screenStateFilter.addAction(Intent.ACTION_SCREEN_ON);
screenStateFilter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(mScreenStateReceiver, screenStateFilter);
Don't forget to unregister the receiver in the Service's onDestroy:
unregisterReceiver(mScreenStateReceiver);
Just in case for people who are asking why the receiver does not work with the declare broadcasts in manifest for ACTION_SCREEN_ON and ACTION_SCREEN_OFF:
https://developer.android.com/reference/android/content/Intent.html#ACTION_SCREEN_ON https://developer.android.com/reference/android/content/Intent.html#ACTION_SCREEN_OFF
You cannot receive this through components declared in manifests, only
by explicitly registering for it with Context.registerReceiver().
This is a protected intent that can only be sent by the system.
You need to create a background service to check for it. Then you can set it programmatically.

Send broadcast from one apk/package to another apk/package

I need to send broadcast from my one application to another applicaion.. any help!
my application package are 1)com.demo.database and 2)com.demo.list
Intent themesIntent = new Intent(ThemesManager.THEMES_UPDATED);
themesIntent.putExtra("package", packageName);
ctx.sendBroadcast(themesIntent);
not working..
Edits :
<receiver android:name="com.sample.ThemesUpdatedReceiver">
<intent-filter>
<action android:name="com.sample.THEMES_UPDATED"/>
</intent-filter>
</receiver>
#Ajit: Hi, Since Android API 3.0 [API level 11], If an application has never been started even once, then it's BroadcastReceiver can't receive events.As, in your case, your app has no launcher activity, so may be it is the case that causes rejection of event.
Along with that please try using below approach:
You have passed that constant value while creating Intent object. Instead pass it in method intent.setAction();
Hope this helps.
I figured that every sent broadcast is received by all applications except when you setPackage to the sending intent for specific package broadcast.
I am not receiving broadcast because my another app is not launched(that doesn't have launcher activity).
If you're going to broadcast, it generally follows you have a sender and receiver. You've posted what looks like the sender ..
sender (where ever you're sending from):
Intent toret = new Intent();
toret.setAction("com.myapp.foo");
toret.putExtra("bar", "fizzbuzz");
sendBroadcast(toret);
receiver (in eg onResume())
IntentFilter intentFilter = new IntentFilter("com.myapp.foo");
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// ... do something with the intent
}
// register the receiver
this.registerReceiver(receiver , intentFilter);
Sender always sends, receiver needs to register to listen for the intent.

How do I communicate information from a BroadcastReceiver to an Activity in Android

I'm trying to write something similar to a custom app store, and I'm having a very hard time hearing the results of the installation.
I've tried a variety of things, and none of them have functioned as it appears they should.
In my main activity class, I have the installation code as follows:
Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
intent.setDataAndType(Uri.fromFile(apkFile),
"application/vnd.android.package-archive");
intent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true);
intent.putExtra(Intent.EXTRA_INSTALLER_PACKAGE_NAME, getApplicationInfo().packageName);
startActivityForResult(intent, resultIndex);
That's pretty straightforward. The first thing I tried to get the result is to override the onActivityResult function in my main activity. That function never gets called (a logger statement on the first line never prints).
Hence, I tried creating a receiver in the manifest.
<receiver android:name=".PackageReceiver">
<intent-filter>
<action android:name="android.intent.action.PACKAGE_ADDED" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="package" />
</intent-filter>
</receiver>
And then in the PackageReceiver class, I overrode the onReceive function. This worked in the sense that the PackageReceiver's function did get called, but I'm now stuck with the problem of how to notify the main activity that something has happened (for the purposes of my project, I need to know). I can't instantiate the PackageReciever; Android does that for me because it's in the manifest.
I tried creating a new broadcast, so my PackageReceiver's onReceive function looks like this:
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_INSTALL_PACKAGE) ||
action.equals(Intent.ACTION_PACKAGE_ADDED) ||
action.equals(Intent.ACTION_PACKAGE_CHANGED) ){
logger.debug("Caught action of type " + action);
Intent i2 = new Intent();
i2.setAction("MY.CUSTOM.ACTION");
context.sendBroadcast(i2);
}
}
Then, over in my main activity, I created a new BroadcastReceiver:
BroadcastReceiver myReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
logger.warn("I made it!!!! HOORAY!!");
}
};
And registered that receiver in the onResume (and unregistered in the onPause) function, like this:
#Override
protected void onResume() {
IntentFilter filter = new IntentFilter();
filter.addAction("MY.CUSTOM.ACTION");
registerReceiver(myReceiver, filter);
logger.debug("Registering receiver in onResume.");
super.onResume();
}
It sounded like a nice solution, but "myReceiver" never has its onRecieve function called. I've tried making sure I don't unregister when I don't want to by simply removing the unregistration, moving the registration to the onCreate method of the activity, and none of that works. The net result there is that exceptions get thrown in the logger saying I've leaked an IntentFilter, "Did you forget to unregister?" (No, I very purposefully didn't unregister... but... nevermind).
I'm running out of ideas as to how to bridge this gap. Also, I can't just poll the installed applications and check version numbers. For reasons I can't get into here, we don't use version numbers. I need to know whether or not the user completed the installation that I kicked off.
How can I send information from the PackageReceiver to the main activity? Or, how can I catch the result of the installation in the main activity itself?
Thanks to all who give it a stab. I checked other stackoverflow questions, but none seem to have the answers I'm looking for.
If you register myReceiver in onResume() and unregister it in onPause() it will never get called because when the package installation occurs your app is paused.
You need to register MyReceiver in onCreate() and don't unregister it until onDestroy().
Also, you don't need so many components to do this. In your main activity, just before you go off to install a package you can register the receiver to listen for the package installer results:
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_PACKAGE_ADDED);
filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
filter.addCategory(Intent.CATEGORY_DEFAULT);
filter.addDataScheme("package");
registerReceiver(myReceiver, filter);
// Now launch the package installer...

Need to shut off a service when a call is coming in and when user dials a number

So, I have a service that runs in the background (it's super secret so I cant tell you what it is:) ) but I need to be able to shut it off when the user initiates a call or a call is coming in. So far, I have checked out the Intent.ACTION_ANSWER, but for some reason, my Broadcast receiver never detects it. I have also tried to use the PhoneStateListener, but in my case statements, I am failing to understand how to do anything with my service. To what context is a PhoneStateListener?
Some example code for my BroadcastReceiver:
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_ANSWER)) {
phoneRinging = true;
}
Intent i = new Intent(context, MyService.class);
i.putExtra("phone", phoneRinging);
context.startService(i);
}
Here is a snippet for starting a service via the PhoneStateListener.
Example: startService(new Intent(---CONTEXT---, MySuperSecretService.class))
And the receiver is in the manifest:
<receiver android:name=".PhoneReceiver" android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.ANSWER"></action>
</intent-filter>
</receiver>
WTH goes into the CONTEXT portion in this statement if I am in a PhoneStateListener?
Please check ACTION_PHONE_STATE_CHANGED instead of ACTION_ANSWER. ACTION_ANSWER is not broadcast intent for incoming call. It's a standard activity action.

Categories

Resources