Start Activity When Foreground Service Stop - android

I am trying to open new activity and pass some data from service to activity when the foreground service stops even if the app is killed.
My service class tried this thing in onDestroy
#Override
public void onDestroy() {
Intent intent = new Intent("UsedTime");
intent.putExtra("Status", "1500");
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
Intent i = new Intent(this, UsedTimeActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.setAction(Intent.ACTION_MAIN);
startActivity(i);
}
and here is My UsedTimeActivity
public class UsedTimeActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vpnused_time);
LocalBroadcastManager.getInstance(context).registerReceiver(
mMessageReceiver, new IntentFilter("UsedTime"));
}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
String message = intent.getStringExtra("Status");
Log.i("TAGUSEDTIME", "onReceive: " + message);
}
};
}
It doesn't work when the app is killed from the background and works fine when the user interacting with the user
Tested Device - Redmi9A (Android 10) & RedmiNote10Pro (Android 12)

Related

Broadcast data from FCM while app is in foreground not getting in BroadcastReceiver

I am using firebase push notification in my app,In case of app in foreground, i am broadcasting an intent to another activity on receiving the message. But i am not getting the intent in the BroadcastReceiver written in the directed activity.
sending intent is like
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
if (isAppIsInBackground(this)){
int dbcount = Integer.parseInt(dbHelper.getPushCount());
int i = count;
int current = dbcount +4;
dbHelper.updatePushCount(Integer.toString(current));
} else {
Intent intent = new Intent(this, NavigationHome.class);
intent.setAction("new.pushMessage");
intent.putExtra("count", count.toString());
sendBroadcast(intent);
}
}
and receiver in the activity in which i want to get the intent is
public class NavigationHome extends BaseActivity
implements NavigationView.OnNavigationItemSelectedListener {
int count=0;
Context context;
private BroadcastReceiver LandingBr = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.e("received",""+1);
NavigationHome.this.update();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation_home);
dbhelper = new DBHelper(this);
...................
update() function is not getting called, How can i get the intent in the Activity?
Create MyReceiver class extending BroadcastReceiver in activity.
class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// do your stuff here
}
}
and than register your BroadcastReceiver in onCreate() of Particular activity . use following code for that.
MyReceiver myReceiver =new MyReceiver();
IntentFilter intentFilter= new IntentFilter(Constants.ACTION);
registerReceiver(myReceiver,intentFilter);

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 .

sending intent extras from service to activity

I have a service that listens for (ON_BATTERY_CHANGE), then onReceive service sends a Broadcast to My MainActivity. The problem is that I somehow can't get them from service to my main activity. Code: Main Activity:
public class MainActivity extends Activity
private BroadcastReceiver batteryReceiverService;
private TextView text2;
....
protected void onCreate(Bundle savedInstanceState) {
text2=(TextView)findViewById(R.id.TV_text2);
batteryReceiverService = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
text2.setText("left: "+intent.getStringExtra("H")+" hours "+intent.getStringExtra("M")+" minute(s)");
Log.e("text2","text2 HHH " +intent.getStringExtra("H")); //log shows 0
Log.e("text2","text2 MMM " +intent.getStringExtra("H")); // log shows 0
}
};
registerReceiver(batteryReceiverService, new IntentFilter(UltimateBatterySaverService.BROADCAST_ACTION));
....
#Override
protected void onDestroy() {
unregisterReceiver(batteryReceiverService);
super.onDestroy();
}
Service:
public class UltimateBatterySaverService extends Service {
private Intent intent;
static final String BROADCAST_ACTION = "lt.whitegroup.ultimatebatterysaver";
private BroadcastReceiver batteryLevelReceiver;
....
public void onCreate() {
super.onCreate();
intent = new Intent(BROADCAST_ACTION);
}
#Override
public void onDestroy() {
unregisterReceiver(batteryLevelReceiver);
super.onDestroy();
}
IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
batteryLevelReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent){
// Receiving data, calculating and etc
averageChargingH=timeAllInHours;
averageChargingM=timeAllInMinutes;
// to put extras and send broadcast
does();
......
public void does(){
String strLong = Long.toString(averageChargingH);
String strLong2 = Long.toString(averageChargingM);
Log.e("cccccc","strLong h "+strLong); // getting good value not 0(everything ok)
Log.e("cccccc","strLong2 m"+strLong2); // getting good value not 0(everything ok)
intent.putExtra("H", strLong);
intent.putExtra("M", strLong2);
sendBroadcast(intent);
}
Any ideas why my information is not transfered correctly?
The does() method seems to be using variables in the same scope as onReceive so I'm guessing that the intent variable in does() is actually the Intent passed in from onReceive.
Try adding some logging before sending the broadcast to check if the action of the intent is correct, or simply create the broadcast intent in the onReceive method and name it intent2.

how to start different activities with one background service

I'm new to Android and I'm stuck on a conception problem.
I have an application with several activities, some of those activities are critical and require the user to be logged in a webApp.
When the user clicks a button to reach one of those critical activities, I call a background Service which ask if the user is still connected to the webApp (not timeout). If the user is logged in, the activity is started, otherwise a dialog pops up and ask for username and password. The problem is that there is several protected activities, and I want to use the same service to do the verification. The way I do it for the moment works but it's kind of kludgy.
public class A_Activity extends Activity {
Context context;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getApplicationContext();
setButtonClickListener();
}
private void setButtonClickListener() {
button_1 = (Button)findViewById(R.id.button1);
button_1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intentCall = new Intent(context,com.them.cp.ConnexionManagerService.class);
intentCall.putExtra("WHO_IS_CALLED","FIRST_ACTIVITY");
context.startService(intentCall);
}
});
button_2 = (Button)findViewById(R.id.button2);
button_2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intentCall = new Intent(context,com.them.cp.ConnexionManagerService.class);
intentCall.putExtra("WHO_IS_CALLED","SECOND_ACTIVITY");
context.startService(intentCall);
}
});
}
}
And my service
public class ConnexionManagerService extends Service{
public class IsConnectedAsync extends AsyncTask<String , Void, Void>{
protected Void doInBackground(String... whoIsCalled) {
String redirectedURL = getRedirectedURL();
if(redirectedURL.equalsIgnoreCase(IF_NOT_CONNECTED_URL)){
if(whoIsCalled[0].equalsIgnoreCase("FIRST_ACTIVITY")){
Intent trueIntent = new Intent(getBaseContext(), FirstActivity.class);
trueIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(trueIntent);
}
else if(whoIsCalled[0].equalsIgnoreCase("SECOND_ACTIVITY")){
Intent trueIntent = new Intent(getBaseContext(), SecondActivity.class);
trueIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(trueIntent);
}
}
else{
Intent falseIntent = new Intent(getBaseContext(), PopUpLoginActivity.class);
falseIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(falseIntent);
}
}
return null;
}
}
#Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d("service onCreate", "onCreate");
}
public int onStartCommand(Intent intent, int flags, int startId){
String whoIsCalled = intent.getStringExtra("WHO_IS_CALLED");
new IsConnectedAsync().execute(whoIsCalled);
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
with my little knowledge I wish i could just send an intent, but it seems that it's not possible as it's not the UI thread.
My question is: What can I do to make this service more generic ?
I want to use the same service to do the verification.
If you don't destroy the service it will be the same service object. If an activity which started your service finishes or stops the service it could be destroyed if it was the unique activity that started the service. If you want to ensure that the service reminds on background start it on you application class (extending Application) and in each activity you need. When an activity stops the service or finishes the service will not be destroyed because your application class is still connected.
EDIT:
To avoid write putExtra again and again:
public class StartOrder1 extends Intent {
public StartOrder(Context ctx, String activity_name){
super(ctx, ServiceName.class);
if(activity_name != null)
super.putExtra("WHO", activity_name);
else
super.putExtra("WHO", "UNKNOWN");
}
public String getWho(){
reurn.getIntExtra("WHO");
}
}
To start it:
this.startService(new StartOrder1(this, "My activity name"));
The best solution:
public class StartOrder2 extends Intent {
public StartOrder(Activity a){
super(a, ServiceName.class);
super.putExtra("WHO", a.toString());
}
public String getWho(){
reurn.getIntExtra("WHO");
}
}
And you can override toString method in each Activity passing the activity name, class name, whatever you want. Then when you start an intent:
this.startService(new StartOrder2(this));
Or extends Activity with this utility:
public class EnhancedActivity extends Activity{
protected startMyService(String name){
Intent i = new Intent(this, MyService.class);
i.putExtra("who", name);
startService(i);
}
}
And call it on your final activity
[...]
super.startMyService("activity_name");
[...]

Categories

Resources