Keep changes made by BroadcastReceiver - java

I'm stuck at this point:
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
String number = bundle.getString("Time");
GameTime.setText("" +number + " hours");
}
};
In another Activity, when a Button is pressed, the MainActivity get's an int.
Whenever I open the Activity, I cannot see the GameTime TextView with the number variable in it.
I know that the OnReceive method works, beacause I had put a toast in it, and I could see the toast after sending the int from the other Activity.
How can I keep the changes made to the TextView while changing Activities?
Thank you.

One way:
Define an interface in your activity & Implement the interface inside your activity and pass its reference to the other class and call that reference whenever you need.
Example:
a) Create an interface
public interface MyBroadcastListener{
public void doSomething(String result);
}
b) Initialize BroadCastReceiver
public class TestNotifAlarm extends BroadcastReceiver {
private MyBroadcastListener listener;
#Override
public void onReceive(Context context, Intent intent) {
listener = (MyBroadcastListener)context;
listener.doSomething("Some Result");
}
}
c) Implement the interface in Activity
public YourActivity extends AppCompatActivity implements MyBroadcastListener{
// Your Activity code
public void updateTheTextView(String t) {
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(t);
}
#Override
public void doSomething(String result){
updateTheTextView(result); // Calling method from Interface
}
}
Another Way :
a) Put a Receiver inside your Activity class
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
textView.setText(intent.getStringExtra("extra"));
}
};
b) Register BroadCastReceiver
registerReceiver(broadcastReceiver , new IntentFilter("trigger_broadcust"));
c) Call sendBroadcast
Intent intent = new Intent("trigger_broadcust");
intent.putStringExtra("extra", "data");
sendBroadcast(intent);

Related

Pass int to another Activity

Before you flame me:
I know there are uncountable tutorials out there, and I know myself how to pass data to another ACtivity, just like that.
In my case that's diffrent tho. "Usually" data is passed to another activity through Intents, Bundles ecc and the other Activity is started.
Here's my case:
I have an Item with 4 parameters (Image, String,String, int)
In an AdapterClass I have a PopUpView which retakes those 4 parameters.
What I'd like to achieve is the following:
With the click of a button, the 4th parameter, the int should be sent to the Main activity and inserted in a textView inside the MainActivity, without (here's the main diffrence between this and the other questions)launching the Main Activity.
How can this be done?
TIA.
use BroadcastReceiver to send that 4th int to MainActivity
in PopupView do these:
Intent intent = new Intent("SOMEACTION");
intent.putExtra("4th_int", value);
activity.sendBroadcast(intent);'
//In MainActivity:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IntentFilter filter = new IntentFilter("SOMEACTION");
this.registerReceiver(mReceiver , filter);
}
#Override
public void onDestroy() {
super.onDestroy();
this.unregisterReceiver(this.mReceiver );
}
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction() == "SOMEACTION") {
// retrieve the 4th int value and update something in MainActivity
}
}
};

How to check internet connectivity using broadcast receiver and Change the intent

I am working on an Android application which requires constant listener of Internet connectivity. I am using Broadcast listener and successfully applied it. But my code only shows the Toast message.
I want to stop the current activity and show a default XML file which says "No Internet Connection". and whenever it connect the Internet, previous activity resumes.
ExampleBradcastReceiver.java
public class ExampleBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
boolean noConnectivity = intent.getBooleanExtra(
ConnectivityManager.EXTRA_NO_CONNECTIVITY, false
);
if (noConnectivity) {
Toast.makeText(context, "Disconnected", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Connected", Toast.LENGTH_SHORT).show();
}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
ExampleBroadcastReceiver exampleBroadcastReceiver = new ExampleBroadcastReceiver();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onStart() {
super.onStart();
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(exampleBroadcastReceiver, filter);
}
#Override
protected void onStop() {
super.onStop();
unregisterReceiver(exampleBroadcastReceiver);
}
}
In the place of Toast Message, I want to show a default XML file whenever disconnected and resume activity whenever connected.
You can move ExampleBroadcastReceiver to MainActivity as an inner class. And since in Java inner classes have access to their parent classes' methods and fields, you can in onReceive method consider showing/hiding the Internet disconnected view.
public class MainActivity extends AppCompatActivity {
ExampleBroadcastReceiver exampleBroadcastReceiver = new ExampleBroadcastReceiver();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onStart() {
super.onStart();
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(exampleBroadcastReceiver, filter);
}
#Override
protected void onStop() {
super.onStop();
unregisterReceiver(exampleBroadcastReceiver);
}
private void showInternetDisconnectedView(boolean disconnected){
// show or hide based on 'disconnected'
}
private class ExampleBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
boolean noConnectivity = intent.getBooleanExtra(
ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
showInternetDisconnectedView(noConnectivity);
}
}
}
}
You need to move Broadcast receiver code into Activity and on receiving internet connection events you can stop current in progress activity and make internet failure layout visible there only as it is part of Activity class. If it is required through out the Application, then create Base activity and handle this there to avoid duplicating code on every screen.

Call method of new activity from MainActivity

There are two Activities..
1. Open SecondActivity from MainActivity
2. When event comes into MainActivity, call testMethod of SecondActivity
But how to do call this testMethod?
public class MainActivity extends Activity implements someListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Launch SecondActivity here!!
Intent intent = new Intent();
intent.setClass(MainActivity.this, SecondActivity.class);
startActivityForResult(intent, ID_PlayerActivity);
}
//trigger by JNI, it's in the other thread, not main thread.
void onEventCome() {
//How to call testMethod() in SecondActivity?
}
}
public class SecondActivity extends Activity {
void testMethod() {
//execute something...
}
}
If you open the SecondActivity, your MainActivity becomes inactive. I don't believe it is a good idea to call some activity method from other inactive/stopped activity.
I suggest to use observer pattern. Create a global long-lived object like EventProducer and register all activities as observer. So your EventProducer can inform all Activities about new event.
Example:
public class SecondActivity extends Activity implements MyEventListener {
#Override
public void onResume(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventProducer.instance().register(this);
}
#Override
public void onPause(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventProducer.instance().unregister(this);
}
void testMethod(){
//just doit
}
#Override
void onMyEventCome() {
testMethod();
}
}
First you need an event aware listener that will capture such an event happening. Your class seems ill equipped to do so.
Since you have a valid question, here goes:
void onEventCome() {
SecondActivity secondActivity = new SecondActivity();
secondActivity.testMethod();
}
There are many ways.
For eg:
Create the method as static and use class name and call it.
public static void onEventCome() {
}
In MainActivity:
MainActivity.onEventCome();
This is one method. Another method is create an object for MainActivity.
public void onEventCome() {
}
MainActivity main;
main = new MainActivity();
main.onEventCome();
You don't have a content view for your second activity. If you don't need to see the operation happen, you could remove your
Intent intent = new Intent();
intent.setClass(MainActivity.this, SecondActivity.class);
startActivityForResult(intent, ID_PlayerActivity);
remove extends Activity in SecondActivity and add a constructor public SecondActivity(Context context) and invoke the test method from your first activity like #Dragan example:
void onEventCome() {
SecondActivity secondActivity = new SecondActivity(MainActivity.this);
secondActivity.testMethod();
}

Call a method of an Activity from another Activity

I have two Activities A and B. B has a method searchDevices. I want to access that method from A 's onCreate method. How can I do it with Intent?
I tried this :
public void onCreate(Bundle savedInstanceState)
{
try{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MY_UUID= UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
//Function enbling Bluetooth
enableBluetooth();
///Function to initialize components
init();
//Calling AvailableDevices class's method searchDevice to get AvailableDevices
Intent intent=new Intent(this,AvailableDevices.class);
int x=10;
intent.putExtra("A", x);
}catch(Exception e){Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();}
}
You can also create a base activity that both ActivityA and ActivityB extends and put searchDevices() method in it.
For ex:
public class BaseActivity extends Activity{
public void searchDevices(){
}
}
public class ActivityB extends BaseActivity{
onCreate..
{
...
searchDevices();
}
}
public class ActivityA extends BaseActivity{
onCreate..
{
...
searchDevices();
}
}
if ActivityA is in a class called class1 make a method in class1 like this
public static void method1(){
}
then in activity 2 call the method by doing this ActivityA.method1()
Why don't use StartActivityForResult.
As per my understanding You can start AvailableDevices Activity for result with Intent having extra data and call searchDevice to get AvailableDevices and return the result to calling Activity.
[Edit]
In Class A
//Calling AvailableDevices class's method searchDevice to get AvailableDevices
Intent intent=new Intent(this,AvailableDevices.class);
int x=10;
intent.putExtra("A", x);
startActivityForResult(intent , searchDevicesRequestCode); //searchDevicesRequestCode = 100
Also override onActivityResult()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == searchDevicesRequestCode) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// Manipulate searchDevicesResult from Intent data
}
}
}
In Class B
#override
onCreate()
{
//call searchDevices()
String result = searchDevices(); // save result to send in any form
// Create intent to deliver some kind of result data
Intent intentResult = new Intent("RESULT_ACTION");
intentResult.putExtra("key",result);
setResult(Activity.RESULT_OK, intentResult);
finish();
}

NullPointerExceptoin when passing value from activity to broadcast receiver

I have an easy question.
I have declared text view in main activity, and created it from XML (findViewById). I would like to pass this value to a subclass of broadcast receiver. Following is my Broadcast constructor:
public Broadcast(TextView text_dBm) {
this.text_dBm = text_dBm;
}
In my main activity I create a new broadcast object and pass my textview value inside, like this:
new Broadcast(text_dBm);
But I'm still getting null pointer exception on my text_dBm. Is there anyway (besides static methods) to pass values between activites and broadcast receiver?
Oh and yes. My broadcast receiver is registered programmatically (in service), and its running perfectly.
Thank you for your time!
P.S: I already checked some threads here in SO, but i didn't find an answer:
How to pass value from an activity in an broadcast receiver?
Main activity class:
public class MainActivity extends Activity {
TextView text_dBm, text_time, text_rssi;
Intent startServiceFromActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text_dBm = (TextView) findViewById(R.id.textView_dBm);
new Broadcast(text_dBm);
startServiceFromActivity = new Intent(this, WifiService.class);
startService(startServiceFromActivity);
}
}
Broadcast receiver class:
public class Broadcast extends BroadcastReceiver {
WifiInfo wifiInfo;
WifiManager wifiManager_service;
TextView text_dBm;
public Broadcast(WifiManager wifiManager_service) {
this.wifiManager_service = wifiManager_service;
}
public Broadcast(TextView text_dBm) {
this.text_dBm = text_dBm;
}
#Override
public void onReceive(Context context, Intent intent) {
Log.d("RECEIVER", "Receiver running"); // LOG
text_dBm.setText("textview"); // nullpointerexception
}
}
You can't pass around views using Intents. To do what you want to do, you will need your broadcast receiver to be an inner class of your activity. The receiver should be registered when activity is started and unregistered when activity is stopped. Else you will leak memory. That means that you will only be able to receive your messages when actually on the activity screen itself.
If you need to be able to receive broadcasts outside the activity, you will need to:
register your receiver in the manifest for a given action (or in a service, but don't forget to unregister it)
start the activity and pass the message to show in the textview using an intent extra
when the activity starts, check if the intent contains anything to show in the textview and do the necessary
From your comment:
Create the receiver as an inner class of the activity (not a static one so it can access the activity's TextView instance)
register the receiver in onStart
unregister the receiver in onStop
In the onReceive method of your receiver do: textView.setText(intent.getStringExtra("dbm"));
Service sends the broadcast by passing an intent extra called "dbm" and containing the text you want to display
-
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbmView = (TextView) findViewById(R.id.textView_dBm);
}
#Override
protected void onStart() {
super.onStart();
IntentFilter intentFilter = new IntentFilter("com.example.broadcasts.DBM_UPDATE");
registerReceiver(receiver, intentFilter);
}
#Override
protected void onStop() {
unregisterReceiver(receiver);
super.onStop();
}
private TextView dbmView;
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
dbmView.setText(intent.getStringExtra("dbm"));
}
}
}
In the service:
Intent i = new Intent("com.example.broadcasts.DBM_UPDATE");
i.putExtra("dbm", "it works!");
sendBroadcast(i);
Pass data Through intent
Activity -
Intent i = new Intent(Activity.this, Broadcast.class);
Bundle b = new Bundle();
b.putString("key", "value");
i.putExtras(b);
startActivity(i);
In your broadcast receiver class onReceive method
#Override
public void onReceive(Context context, Intent intent)
{
String result = intent.getString("key");
// your method
}

Categories