Toggle Background/Foreground Modes - java

I'm trying to make it so that when you press the power button to turn off the android, my app goes into background mode. When you press the power button to turn on the android, my app should go into foreground mode.
The error I get is:
java.lang.RuntimeException: Error receiving broadcast Intent {
act=android.intent.action.SCREEN_ON flg=0x50000010 }
The error comes from the intent with FLAG_ACTIVITY_CLEAR_TOP
Here's the MainActivity:
public class MainActivity extends AppCompatActivity {
#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);
BroadcastReceiver mReceiver = new ScreenReceiver(MainActivity.this, this);
registerReceiver(mReceiver, filter);
moveTaskToBack(true);
}
}
Here's the BroadcastReceiver:
public class ScreenReceiver extends BroadcastReceiver {
MainActivity mainAct;
Context ctx;
public ScreenReceiver(MainActivity act, Context con) {
mainAct = act;
ctx = con;
}
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
mainAct.moveTaskToBack(true);
System.out.println("OFF");
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
Intent i = new Intent(ctx, ScreenReceiver.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
mainAct.startActivity(i);
System.out.println("ON");
}
}
}
I'm using code from the following tutorial:
https://thinkandroid.wordpress.com/2010/01/24/handling-screen-off-and-screen-on-intents/

The mistake was passing ScreenReceiver.class instead of MainActivity.class into the intent. Here's the corrected version:
public class ScreenReceiver extends BroadcastReceiver {
MainActivity mainAct;
Context ctx;
public ScreenReceiver(MainActivity act, Context con) {
mainAct = act;
ctx = con;
}
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
mainAct.moveTaskToBack(true);
System.out.println("OFF");
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
Intent i = new Intent(ctx, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
mainAct.startActivity(i);
System.out.println("ON");
}
}
}

Related

How to update the UI with BroadcastReceiver onReceive in Android?

I want to update the UI according to the WiFi status in my Android app in Java. I am unable to update the UI to show the new string. Please help me.
Here is my code
public class MainActivity extends AppCompatActivity {
IntentFilter intentFilter = new IntentFilter();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(new NetworkConnectionReceiver(), intentFilter);
TextView displayStatus = findViewById(R.id.displayStateTextView);
}
}
class NetworkConnectionReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
Log.i("MyReceiver", Boolean.toString(wifiManager.isWifiEnabled()));
}
}
Use this code:
public class MainActivity extends AppCompatActivity {
...
BroadcastReceiver br = new BroadcastReceiver(){
#Override
public void onReceive( Context context, Intent intent ){
//update UI here directly
View view = findViewById( R.id.example );
}
};
#Override
protected void onResume(){
super.onResume();
// Check state here
...
IntentFilter filter = new IntentFilter();
filter.addAction( ConnectivityManager.CONNECTIVITY_ACTION );
registerReceiver( br, filter);
}
#Override
protected void onPause(){
super.onPause();
unregisterReceiver( br );
}
...
}
You can do it using interface
interface WifiStateListener{
void onStateChanged(Boolean enabled);
}
Then add a constructor to pass the WifiStateListener to BroadcastReceiver
class NetworkConnectionReceiver extends BroadcastReceiver {
private WifiStateListener mWifiStateListener;
public NetworkConnectionReceiver(WifiStateListener wifistateListener){
mWifiStateListener = wifistateListener;
}
#Override
public void onReceive(Context context, Intent intent) {
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
if(mWifiStateListener != null){
mWifiStateListener.onStateChanged(wifiManager.isWifiEnabled());
}
Log.i("MyReceiver", Boolean.toString(wifiManager.isWifiEnabled()));
}
}
And in Activity, while registering receiver you can pass the interface
registerReceiver(new NetworkConnectionReceiver(enabled -> {
//do based on wifi state change
}), intentFilter);
Other options are to use EventBus, Observables etc
You can user LocalBroadCastManager.
First write broadCastReceiver in activity
register that broadcast with LocalBroadCastManager in onResume
unregister that broadcast with LocalBroadCastManager in onPause as well
than write Broadcast of internet connection and call LocalBroadCastManager which you register in activity
private BroadcastReceiver broadCastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction() == "local_broadcast_update_UI"){
updateUI()
}
}
};
#Override
protected void onResume(){
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver( broadCastReceiver, new
IntentFilter("local_broadcast_update_UI"));
}
#Override
protected void onPause(){
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver("local_broadcast_update_UI");
}
public class NetworkChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent intent) {
final ConnectivityManager connMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
final android.net.NetworkInfo wifi = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final android.net.NetworkInfo mobile = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isAvailable() || mobile.isAvailable()) {
LocalBroadcastManager.getInstance(context).sendBroadcast(new
Intent("local_broadcast_update_UI"));
}
}
}

Is there a solution that access MainActivity from other Activity class?

I want to call function below.
mobileView.loadUrl("javascript:setUserId () ");
And mobileView is in MainActivity.
public class MainActivity extends AppCompatActivity {
private WebView mobileView;
}
I want to call function above after SecondActivity is finished.
public class SecondActivity extends AppCompatActivity {
...
private void getUserId () {
...
finish();
}
}
And SecondActivity starts from AReceiver.
public class AReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
...
Intent i = new Intent(context, SecondActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
...
context.startActivity(i);
}
}
And AReceiver is called by below code...
class MainActivity {
...
private void userId () {
...
intent = new Intent(MainActivity.this, AReceiver.class);
pendingIntent = PendingIntent.getBroadcast(
MainActivity.this,
alarmID,
intent,
PendingIntent.FLAG_UPDATE_CURRENT
);
alarmManager.set(
AlarmManager.RTC_WAKEUP,
mCalendar.getTimeInMillis(),
pendingIntent
);
...
}
...
}
But I don't know how to access mobileView from SecondActivity.
Is there any solution?
What I've tried...
change variable from
private webView mobileView
to
public webView mobileView
2.
call from SecondActivity Using
MainActivity.mobileView
It doesn't work for me.
You can try This option
Intent
..............
You opened the new activity from another activity with startActivityForResult. In that case you can just call the finishActivity() function from your code and it'll take you back to the previous activity.
it work only if you start the second activity from main activity
I solved this problem using local broad cast manager! :D
Thank you #Shripad Jadhav who help this answer.
Below description is solution! Hope it helpes somebody. :D
MainActivity.java
public class MainActivity extends AppCompatActivity {
private WebView wv;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
LocalBroadcastManager.getInstance(this)
.registerReceiver(mBroadcastReceiver, new IntentFilter("webview-filter"));
...
}
...
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
mv.loadUrl("javascript: loadMainData ()");
}
};
#Override
protected void onDestroy() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcastReceiver);
super.onDestroy();
}
}
SecondActivity.java
public class SecondActivity extends AppCompatActivity {
private void someFunction () {
sendMessage ();
}
...
private void sendMessage() {
Log.d("sender", "Broadcasting message");
Intent intent = new Intent("webview-filter");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
...
}

How to close an Activity using push Notification in Firebase?

I am working on Firebase Push Notification and i want to close MainActivity. Application should finish when onMessageReceived() is called. I am also passing the Context but its not working. In this case, I'll send notification when application is opend. My code:
MainActivity.java
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new FirebaseMessagingService(MainActivity.this);
}
}
FirebaseMessagingService.java
public class FirebaseMessagingService extends
com.google.firebase.messaging.FirebaseMessagingService {
Context context;
public FirebaseMessagingService(Context ctx) {
this.context = ctx;
}
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
context.finish();
}
}
You could define a BroadcastReceiver in MainActivity, that calls finish() when triggered:
private final BroadcastReceiver finishReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
finish();
}
};
Register/unregister it when appropriate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ...
LocalBroadcastManager.getInstance(getApplicationContext())
.registerReceiver(finishReceiver,
new IntentFilter(FirebaseMessagingService.ACTION_FINISH));
}
#Override
protected void onDestroy() {
LocalBroadcastManager.getInstance(getApplicationContext())
.unregisterReceiver(finishReceiver);
super.onDestroy();
}
And then you just simply have to send a local broadcast from onMessageReceived():
public static final String ACTION_FINISH = "yourpackagename.ACTION_FINISH";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
LocalBroadcastManager.getInstance(getApplicationContext())
.sendBroadcast(new Intent(ACTION_FINISH));
}
(FirebaseMessagingService is a Context subclass, there is no need to pass another Context instance to it)

Without Button click How to call MyService class in MainActivity in android studio

Without Button click How to call MyService class in MainActivity. My issue is to call MyService class in MainActivity class because when app start notification automatically started.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyService my = new MyService();
}
}
MyService.Java
public class MyService extends Service {
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
showNotification();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
private void showNotification() {
NotificationCompat.Builder mBuilder =
(NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_loc)
.setContentTitle("Welcome to Brillio")
.setContentText("Hello Mansur, Welcome to Brillio! You'll be shortly attended by Renji! ")
.setPriority(2)
.setOnlyAlertOnce(false);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mBuilder.setSound(alarmSound);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(2001, mBuilder.build());
}
}
Without any user interaction you can start service like when your activity is open you can start service intent
#Override
public void onResume() {
super.onResume();
startService(new Intent(this, MyService.class));
}
Add this to onCreate() method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, MyService.class));
}

how to extract the string value in Android services from an activity?

how to extract the string value in Android services from an activity?
My activity has a edit text, the entered string must be received in my services.
TempLaunch.java :
public class TempLaunch extends Activity {
private EditText text;
private Button okbtn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.templaunch);
addListenerOnButton();
}
public void addListenerOnButton() {
text = (EditText) findViewById(R.id.edittext_newid);
okbtn = (Button) findViewById(R.id.button_newid);
okbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(TempLaunch.this, "In Temp launch class ",Toast.LENGTH_SHORT).show();
Toast.makeText(TempLaunch.this, text.getText(),Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
Toast.makeText(TempLaunch.this, "I am in Main activity class ",Toast.LENGTH_SHORT).show();
startActivity(intent);
}
});
Intent i = new Intent(this, MusicService.class);
i.putExtra("DD_URL", text.getText().toString());
//startActivity(i);
}
}
MusicService.java
public class MusicService extends Service {
#Override
public void onCreate() {
super.onCreate();
String url = null;
Intent intent = getIntent();
String id = intent.getStringExtra("DD_URL");
System.out.println("Rosh :" + id);
Toast.makeText(MusicService.this, "I am in Service:"+ id,Toast.LENGTH_SHORT).show();
...
Please help me out with this regard.
Thanks in advance
You may use sendBroadcast(intent); which will broadcast the EditText from your Activity A.
Then you need to call onReceive(Context context, Intent intent) within your Service class. This method is called when the BroadcastReceiver is receiving an Intent broadcast, in your case will be sent from Activity A.
private final BroadcastReceiver receiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
// Do something
}
};
//Register your receiver in onResume:
#Override
protected void onResume()
{
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction("SOME_ACTION");
registerReceiver(receiver, filter);
}
//Unregister the receiver in onPause:
#Override
protected void onPause()
{
super.onPause();
unregisterReceiver(receiver);
}

Categories

Resources