How to bring application from background to foreground via BroadcastReceiver - android

I have two classes which are MainActivity and MyBroadcastReceiver. BroadcastReceiver detects whether phone screen is on or off. My desire is to launch my application whenever screen lock is released. I mean that I want to bring my application to the front when phone lock releases.
Here is my activity class:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerReceiver();
}
private void registerReceiver(){
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new MyPhoneReceiver();
registerReceiver(mReceiver, filter);
}
}
And here is my broadcast receiver:
public class MyPhoneReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
if(pm.isScreenOn()){
//Bring application front
}
}
}
What am I supposed to do in order to perform this operation in my broadcast receiver?

Try to use FLAG_ACTIVITY_REORDER_TO_FRONT or FLAG_ACTIVITY_SINGLE_TOP

Do the following in your onReceive method of the BroadcastReceiver
#Override
public void onReceive(Context context, Intent intent) {
Intent newIntent = new Intent();
newIntent.setClassName("com.your.package", "com.your.package.MainActivity");
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
context.startActivity(newIntent);
}
You need the flag "FLAG_ACTIVITY_NEW_TASK" for your intent otherwise there will be a fatal exception being thrown.
The flag "FLAG_ACTIVITY_SINGLE_TOP" is to bring your MainActivity to the front and you can proceed to do whatever you want from there by overriding the onNewIntent method in MainActivity.
#Override
protected void onNewIntent(Intent intent) {
// continue with your work here
}

Do this inside your onReceive method:
Intent activityIntent = new Intent(this, MainActivity.class);
activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(activityIntent);
You might need to tweak the addFlags call for your specific needs!

Related

Can a Broadcast Receiver send information to an Activity only if it is active without starting a new Activity?

I have a broadcast receiver that gets triggered on geofencing events and either "clocks in" or "clocks out" with the server. If my application's "Attendance" activity is already open I would like it to display the clocking status change but I don't want the Broadcast Receiver to start the activity if it's not open - in other words display the change "live" while the activity is open only.
The way I imagine doing this is with the Broadcast Receiver sending an Intent to the activity but name "startActivity()" doesn't sound encouraging unless there are any special flags I can pass to prevent starting an Activity that isn't already open - I can't seem to find any.
The other option would be to constantly poll the value while the activity is open but it doesn't seem optimal so I would only use it if there wasn't another way and I can't think of a reason why it couldn't be possible with Intents.
There are several different ways to accomplish the same task. One is registering a listener like the following example:
MainActivity
public class MainActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Receiver.setOnReceiveListener(new Receiver.OnReceiveListener() {
public void onReceive(Context Context, Intent intent)
{
//Do something.
}
});
}
#Override
protected void onDestroy()
{
super.onDestroy();
Receiver.setOnReceiveListener(null);
}
}
Receiver
public class Receiver extends BroadcastReceiver
{
private static OnReceiveListener static_listener;
public static abstract interface OnReceiveListener
{
public void onReceive(Context context, Intent intent);
}
public static void setOnReceiveListener(OnReceiveListener listener)
{
static_listener = listener;
}
#Override
public final void onReceive(Context context, Intent intent)
{
if(static_listener != null) {
static_listener.onReceive(context, intent);
}
}
}
Just have your BroadcastReceiver send a broadcast Intent. Your Activity should register a listener from this broadcast Intent and if it gets triggered, it can update the UI.
Here's an example:
Declare a private member variable in your Activity:
private BroadcastReceiver receiver;
In Activity.onCreate(), register the BroadcastReceiver:
IntentFilter filter = new IntentFilter();
filter.addAction("my.package.name.CLOCK_STATUS_CHANGE");
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Here you can update the UI ...
}
};
registerReceiver(receiver, filter);
And in onDestroy() you can unregister it (probably not necessary, but cleaner):
if (receiver != null) {
unregisterReceiver(receiver);
receiver = null;
}
In your BroadcastReceiver that detects the geofencing event, you should create and send a broadcast Intent:
Intent broadcastIntent = new Intent("my.package.name.CLOCK_STATUS_CHANGE");
sendBroadcast(broadcastIntent);

android recognize if call has been answered

I'm trying to add to my broadcast receiver an if, so I will start a different activity if a call has been answered, to the regular activity I start usually, if the screen has just been turned on.
Now as you can see down here I have the class screenJump starting when the user wakes up phone.
I would like to start a phoneActivity I wrote when the user wakes up phone, but only when a call has been answered.
This is my service now.
public class MyService extends Service {
BroadcastReceiver bd;
public MyService() {
}
class ScreenReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent startupIntent = new Intent(context, ScreenJump.class);
startupIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(startupIntent);
}
public ScreenReceiver()
{
}
}
#Override
public void onCreate()
{
super.onCreate();
IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
bd = new ScreenReceiver();
registerReceiver(bd, filter);
}
}

finish my current background activity when call ringing android

I have application that use audio device of the phone, I want my activity to be finish when any call come to my device
This is the code
public class PhoneStateReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context mContext, Intent intent) {
if (intent.getAction().equals("android.intent.action.PHONE_STATE")) {
if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_RINGING)) {
// Send local broadcast to set pin code in the dialog
Intent broadcast = new Intent();
broadcast.setAction(ThurayaConstants.INCOMING_CALL);
mContext.sendBroadcast(broadcast);
}
}
}
}
I have added this class to listen to global receiver in the manifest file to detect when any call come to my device.
and in my fragment I register the following receiver
private BroadcastReceiver mIncomingCallReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
getActivity().finish();
}
};
The problem that my activity is not closed , can any one help here ???

Starting my activity when power button has been pressed

I am trying to develop an app which starts flashlight when user presses power button.
In that process I got to know how to listen to power button by catching Intent.ACTION_SCREEN_OFF and Intent.ACTION_SCREEN_ON intents.
Now I am trying to start my activity after receiving these intents.
I am using this code in my receiver to catch intents
public class IReciever extends BroadcastReceiver{
private Activity acti = null;
public IReciever(Activity act) {
acti = act;
}
#Override
public void onReceive(Context ctxt, Intent intent) {
if(intent.getAction().equals(Intent.ACTION_SCREEN_ON)){
Intent i = new Intent(acti, MainActivity.class);
acti.startActivity(i);
Toast.makeText(ctxt, "MAIN ACTIVITY IS BEING CALLED ", Toast.LENGTH_SHORT).show();
Log.e("In on receive", "In Method: ACTION_SCREEN_ON");
}
}
}
Here is the code of my MainActivity
public class MainActivity extends Activity {
private Camera camera;
private boolean isFlashOn;
private boolean hasFlash;
Parameters params;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
IReciever mReceiver = new IReciever(this);
registerReceiver(mReceiver, filter);
}
}
The app shows toasts and I am able to see logs which confirms that I am able to receive intents.
But I doesn't start my MainActivity. Please help me
Register your receiver in manifest not in the activity.
and use below code to start your activity
Intent in = new Intent(context, MainActivity.class);
in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
in.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
in.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
in.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
context.startActivity(in);
write this code in onreceiver..where you checked for power on and off.

How to Start same activity with different data from Broadcast Receiver?

I have 1 activity that I would like to start at different times with different variables from a Broadcast Receiver.
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equalsIgnoreCase("tv.abcd.v4.ORIGINAL_VIDEO_SCENE")){
channelName = intent.getExtras().getString("com.abcd.Channel");
JSONObject json = new JSONObject(intent.getExtras().getString("com.abcd.Data"));
String incomingScene = json.getString("url");
scene.putExtra("channel", channelName);
scene.putExtra("url", incomingScene);
scene.addFlags(Intent.FLAG_FROM_BACKGROUND);
scene.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
scene.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(scene);
}
I have the code to start the activity via Intent and in the activity receiver the extras to make data appear.
Intent intent = getIntent();
sceneUrl = intent.getStringExtra("url");
Log.d("Image.incomingscene.url",sceneUrl);
channelName = intent.getStringExtra("channel");
Log.d("Image.incomingSceneAvatar",networkAvatar);
image = (ImageView)findViewById(R.id.imageView1);
image.setScaleType(ScaleType.FIT_CENTER);
progressBar = (ProgressBar)findViewById(R.id.progressBar1);
Picasso.with(this).load(sceneUrl).skipMemoryCache().fit().into(image, new EmptyCallback() {
});
Now after that I want to start the same activity again from the Broadcast Reciever with different data. So i want the previous activity to get out the way and allow this new instance to start up.
How to accomplish this feat?
register another broadcast receiver from the activity. Then, when you want to kill it, send a broadcast message from the broadcast receiver that you mentioned .
In your broadcastReceiver do something like the following :
public static final String CLOSE_Activity= "com.mypackage.closeactivity";
and in yopr OnReceive method do like the following :
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("HIT OUTGOING");
Intent i = new Intent();
i.setAction(CLOSE_Activity);
context.sendBroadcast(i);
}
then in your activity craete a receviver and register it in the onResume method and unregeister it in the onPause method , like the following :
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(RECEIVER_Class.CLOSE_Activity)) {
finish();
}
}
}
activity onResume method :
#Override
public void onResume() {
registerReceiver(broadcastReceiver, new IntentFilter(RECEIVER_Class.CLOSE_Activity));
}
activity onPause method :
#Override
public void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
Please give me some feedback
Hope that helps .

Categories

Resources