I have a class which extends BroadcastReceiver
. On receiving a SMS, I would like to pass information to my main activity class to display the text in a box (Append, if already text is present).
public class SmsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent)
{
Intent i = new Intent(context, MainActivity.class);
i.putExtra("updatedString","Hello");
context.startActivity(i);
}
}
MainActivity.java
public class MainActivity extends Activity{
private TextView results;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle extras = getIntent().getExtras();
if(extras!=null){
results = (TextView) findViewById(R.id.results);
results.setVisibility(View.VISIBLE);
results.append(extras.getString("updatedString"));
}
}
I have only one activity class (MainActivity.java
). However When i do this I get an exception Unable to pause Activity.
You have three ways:
1) You can define your broadcast inside your
MainActivity
like this:in
onCreate()
and define smsReciver in
MainActivity
define a runnable to update UI
and update method
2) Register a receiver between your Activity and BroadCastReceiver
3) Start your Activity with new Intent to update current open Activity
UPDATE :
explain method 2
MainActivity.class
in
onResume()
in
onDestroy()
local broadCast (broadcastReceiver, in MainActivity.class)
SmsReceiver.class
global attribute
in
onReceive()
define two method
Modify your code as below.