Reference view in another layout - android

Is this possible? I have 2 activities and 2 layouts, but I want to reference a view which belongs to another .xml and not the one being inflated by the current activity. How do I do this?
private ChildEventListener pendingListener;
private ChildEventListener matchesListener;
private ChildEventListener alertListener;
private ValueEventListener flightListener;
private ValueEventListener prefsListener;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
bLogout = (Button) findViewById(R.id.bLogout);
bLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
logout();
}
});
}
private void logout(){
if(pendingListener != null){
System.out.println(TAG +" pending listener removed");
mFirebaseRef
.child(FirebaseReference.CHILD_USERS)
.child(CURRENT_USER.getId())
.child(FirebaseReference.CHILD_PENDING).removeEventListener(pendingListener);
}
if(matchesListener != null){
System.out.println(TAG +" accept listener removed");
mFirebaseRef
.child(FirebaseReference.CHILD_USERS)
.child(CURRENT_USER.getId())
.child(FirebaseReference.CHILD_MATCHES).removeEventListener(matchesListener);
}
if(flightListener != null){
System.out.println(TAG + " flight listener removed");
mFirebaseRef
.child(FirebaseReference.CHILD_FLIGHTS)
.child(CURRENT_USER.getId()).removeEventListener(flightListener);
}
if(alertListener != null){
System.out.println(TAG + " alert listener removed");
mFirebaseRef.child(FirebaseReference.CHILD_USERS)
.child(CURRENT_USER.getId())
.child(FirebaseReference.CHILD_ALERTS).removeEventListener(alertListener);
}
if(prefsListener != null){
System.out.println(TAG + " prefsListener removed");
mFirebaseRef.child(FirebaseReference.CHILD_USERS)
.child(CURRENT_USER.getId())
.child(FirebaseReference.CHILD_PREFS).removeEventListener(prefsListener);
}
if(this.mAuthData != null){
mFirebaseRef.removeAuthStateListener(mAuthStateListener);
System.out.println(TAG + " authState listener removed");
}
// After logout, go to main activity
Intent intent = new Intent(MainScreen.this, loginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
The app crashes at .setOnClickListener. bLogout's id is defined in another layout, not main_screen

How to call Activity1 logout() function from Activity2
Create a Broadcast Receiver which call logout():
public class YourBroadcastReceiver extends BroadcastReceiver {
//local variables
private Context mContext;
public YourBroadcastReceiver(Context mContext){
this.mContext = mContext;
}
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if(action.equals("LOGOUT")) {
((YourActivity) mContext).logout();
}
}
}
Register BroadcastReceiver in Activity 1:
public mYourBroadcastReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//........
//Create an Intent Filter
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("LOGOUT");
mYourBroadcastReceiver = new YourBroadcastReceiver(this);
//Register receiver
registerReceiver(mYourBroadcastReceiver, intentFilter);
//.........
}
#Override
protected void onDestroy() {
super.onDestroy();
if (EcologDriverAIDApplication.DEBUG) {
Log.i(TAG, "onDestroy");
}
//Unregister receiver before destroy activity
unregisterReceiver(mYourBroadcastReceiver);
mYourBroadcastReceiver = null;
}
Broadcast logout:
final Intent intent = new Intent("LOGOUT");
sendBroadcast(intent);
Hope helps

Upon further research, this was simply solved by making logout public and writing the following for the onClickListener for bLogout in my fragment
//call logout in MainScreen
((MainScreen)getActivity()).logout();

Related

BroadcastReceiver is receiving like 1 of 10 intents

On button click I am opening activity(ActionListActivity) and sending intent to IntentService (later this service sends broadCast intent to ActionListActivity). But I am usually receiving only the first intent after launch. Is it real that intent is sent before the receiver is registred?
I want to get data providet by the intentService, and update my UI using it.
Scheme Activity->IntentService->BroadCastReceiver inside ActionListActivity
Activity:
private void selectDrawerItem(MenuItem menuItem)
{
switch (menuItem.getItemId()) {
case R.id.actions:{
Intent myIntent = new Intent(this, ActionListActivity.class);
this.startActivity(myIntent);
ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.show();
Intent dataIntent = new Intent(this, DatabaseWorkIntentService.class);
dataIntent.putExtra(Utils.INTENT_SERVICE_INVOKE, Utils.READ_ACTIONS_DATA);
startService(dataIntent);
progressDialog.dismiss();
}
}
}
IntentService:
private void readActionData(){
Log.e("read actions data","data");
List<Action> actionList;
actionList = Action.listAll(Action.class);
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(Utils.READ_ACTIONS_DATA);
broadcastIntent.putParcelableArrayListExtra(Utils.READ_ACTIONS_DATA, (ArrayList<? extends Parcelable>) actionList);
sendBroadcast(broadcastIntent);
}
ActionListActivity:
public class ActionListActivity extends BaseActivity {
boolean mIsReceiverRegistered = false;
DataBroadcastReceiver receiver;
TextView someTv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.action_list_activity);
this.initToolbarAndDrawerWithReadableName(getString(R.string.our_actions));
someTv = (TextView)findViewById(R.id.someTv);
}
public void someTvTest(Action action){
someTv.append(action.getName());
Log.e("data",action.getName());
}
#Override
protected void onPause() {
super.onPause();
if (mIsReceiverRegistered) {
unregisterReceiver(receiver);
receiver = null;
mIsReceiverRegistered = false;
}
}
#Override
protected void onResume() {
super.onResume();
if (!mIsReceiverRegistered) {
if (receiver == null)
receiver = new DataBroadcastReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(Utils.READ_ACTIONS_DATA);
receiver.setMainActivityHandler(this);
registerReceiver(receiver, filter);
mIsReceiverRegistered = true;
}
}
}
class DataBroadcastReceiver extends BroadcastReceiver{
ActionListActivity activity = null;
ArrayList<Action> list;
public void setMainActivityHandler(ActionListActivity main){
activity = main;
}
#Override
public void onReceive(Context context, Intent intent) {
Log.e("reciever","reciev");
list = intent.getParcelableArrayListExtra(Utils.READ_ACTIONS_DATA);
for (Action action:list){
if(activity!=null) {
activity.someTvTest(action);
}
}
}
}
You start activity and service async.
You need to start service inside ActionListActivity and wait for response.

How can i correctly unregister a receiver out of another activity?

i got trouble unregistering my receiver out of another activity. here it is:
Starting/Register the BroadcastReceiver in my launching Activity A.
Activity A:
public class ActivityA extends Activity {
private PowerButtonReceiver mPowerButtonReceiver = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (getPowerButtonReceiver() == null)
{
mPowerButtonReceiver(new PowerButtonReceiver());
registerReceiver(mPowerButtonReceiver, new IntentFilter("android.intent.action.SCREEN_ON"));
}
}
public void unregister() {
try {
unregisterReceiver(mPowerButtonReceiver);
} catch (NullPointerException e) {
e.printStackTrace();
}
if (mPowerButtonReceiver == null) {
Log.i(TAG,"unregistered PowerButtonReceiver!");
}
}
then i start Activity B inside the onReceive()-method of my receiver.
After this i step into the onCreate()-method of Activity B, do my stuff and at the end of onCreate() i want to unregister the BroadcastReceiver:
Activity B: (--> android:launchMode="singleTop")
public class ActivityB extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
[...do my stuff...]
//un-register PowerButtonReceiver --> call in Activity A
MainActivity m = new MainActivity();
m.getParent();
m.unregister();
}
my last line starts the call for unregister(), but there the Receiver is null and it looks like it is not getting the reference for it. Also the Receiver does not get unregistered and is still listening. I am pretty sure that my error is in doi9ng the reference/call; but i don't get how to do it right :/
What am i missing here? Can someone help me?
Pass your Activity A context to Activity B through intent.putExtra() method . Then instead of doing MainActivity m = new MainActivity(); do MainActivity m = ((MainActivity)(passedContext));.
I have tried something like this succesfully, see if this helps: I have a HeadSetTesTActivity , a Headsetconnectorreciever, ActivityB.
HEADSETTESTACTIVITY.JAVA
`public class HeadsettestActivity extends Activity {
/** Called when the activity is first created. */
Headsetconnectorreciever r;
static HeadsettestActivity activity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
activity=this;
Log.d("Inside activity ", "before broadcast reciever registered");
r = new Headsetconnectorreciever();
registerReceiver(r, new IntentFilter(Intent.ACTION_HEADSET_PLUG));
Log.d("Inside activity ", "after broadcast reciever registered");
}
public void unregister() {
try {
if(r!=null){
unregisterReceiver(r);
Log.i("HeadsettestActivity","Inside unregister ");
}
} catch (NullPointerException e) {
e.printStackTrace();
}
if (r == null) {
Log.i("HeadsettestActivity","unregistered PowerButtonReceiver!");
}
}
}`
Headsetconnectorreciever
`public class Headsetconnectorreciever extends BroadcastReceiver {
private boolean headsetConnected = false;
#Override
public void onReceive(Context context, Intent intent) {
Log.d("Inside broadcast reciever ", "Inside onrecieve");
// TODO Auto-generated method stub
if (intent.hasExtra("state")){
Log.d("Inside broadcast reciever ", "hasstate");
if (headsetConnected && intent.getIntExtra("state", 0) == 0){
headsetConnected = false;
Log.d("Inside broadcast reciever ", "disconnected");
Toast.makeText(context, "Headset is disconnected", Toast.LENGTH_SHORT).show();
}
else if (!headsetConnected && intent.getIntExtra("state", 0) == 1){
Log.d("Inside broadcast reciever ", "disconnected");
headsetConnected = true;
Intent intent2=new Intent(context, ActivityB.class);
context.startActivity(intent2);
}
}
}
}`
and finally my ACTIVITY B
public class ActivityB extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Toast.makeText(getApplicationContext(), "Headset is connected", Toast.LENGTH_SHORT).show();
HeadsettestActivity a = HeadsettestActivity.activity ;
a.unregister();
}
}
The code actually worked.
Since you are not closing the other activity i would had sent intent to Activity A,
Activity B
boolean unregister = true;
Intent intent = new Intent(this, Activity_A.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra("unregister",unregister);
startActivity(intent);
on Activity A you override onNewIntent
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (intent != null) {
if (intent.getBooleanExtra("unregister", false)) {
unregister();
}
}
}

android: how to get broadcasted messages from service when activity is in background

I have a service and an activity. in service I broadcast messages received from network and in the activity show these messages. this works fine. but all messages will lost when the activity is in the background.
How can I get last messages(if exists) from server, in activity onResume(or onCreate)?
EDIT :
in service:
public class server extends Service implements Runnable
{
#Override
public void onCreate()
{
}
#Override
public IBinder onBind(Intent arg0)
{
return null;
}
#Override
public void onStart(Intent intent, int startID)
{
//initializing socket and begining listen
new Thread(this).start();
}
public void run()
{
String readed;
while (true)
{
if(reader == null) continue;
try
{
if ((readed = reader.readLine()) != null)
{
Intent intent = new Intent(SEND_DATA_INTENT);
intent.putExtra("type", "message");
intent.putExtra("content", readed.substring(1));
sendBroadcast(intent);
Thread.sleep(100);
}
}
catch (Exception ee) { }
}
}
}
and in activity:
public class menhaj extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
#Override
protected void onResume()
{
if (dataUpdateReceiver == null) dataUpdateReceiver = new DataReciver();
IntentFilter intentFilter = new IntentFilter(server.SEND_DATA_INTENT);
registerReceiver(dataUpdateReceiver, intentFilter);
super.onResume();
};
#Override
protected void onPause()
{
if (dataUpdateReceiver != null) unregisterReceiver(dataUpdateReceiver);
super.onPause();
};
private class DataReciver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().equals(server.SEND_DATA_INTENT))
{
Bundle bdl = intent.getExtras();
String type = bdl.getString("type");
if (type.equals("message"))
{
String message = bdl.getString("content");
db.addMessage(message);
showMessage(message);
}
}
}
}
}
If that activity is in the background, the user probably doesn't want to see messages from it. Show notifications from your services instead. Generally, an activity should de-register itself onPause() and register again onResume() when it comes back to the foreground.
I would declare BroadcastReceivers , those can receive messages and bring back to from your avtivity / app

Start android activity from receiver (inside running service)

I want to display an alert when a sms is received, so my idea is to start a new activity that launch the alertdialog.
My service starts with no problem, and starts receiver as well..
I can receive sms and display toast alerts fine.. but i'd like to show a custom alertdialog instead.
This is the activity that starts my service (ServiceExampleActivity ):
public class ServiceExampleActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnStartService = (Button) findViewById(R.id.btnStart);
Button btnStopService = (Button) findViewById(R.id.btnStop);
btnStartService.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
StartMyService();
}
});
btnStopService.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
StopMyService();
}
});
}
private void StartMyService() {
Intent myServiceIntent = new Intent(this, ServiceTest.class);
startService(myServiceIntent);
}
private void StopMyService() {
Intent myServiceIntent = new Intent(this, ServiceTest.class);
stopService(myServiceIntent);
}
}
This is my Service (ServiceTest):
public class ServiceTest extends Service {
private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
private BroadcastReceiver myBroadcastReceiver = null;
#Override
public void onCreate() {
super.onCreate();
final IntentFilter theFilter = new IntentFilter();
theFilter.addAction(ACTION);
this.myBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
StartDialogActivity(context, intent);
}
};
this.registerReceiver(myBroadcastReceiver, theFilter);
}
#Override
public IBinder onBind(Intent arg) {
return null;
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.d("ServiceTest", "Started");
Toast.makeText(this, "Service started...", 3000).show();
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(myBroadcastReceiver);
Toast.makeText(this, "Service destroyed...", 3000).show();
}
private void StartDialogActivity(Context context, Intent intent) {
Intent dlgIntent = new Intent(context, DialogActivity.class);
dlgIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(dlgIntent);
}
}
And this is the activity i want to launch to display the alertdialog normally..
public class DialogActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog);
}
}
When it tries to start the activity, the app crashes..
Can you tell me were is the error..??
Like this, you want start activity from service
Intent dlgIntent = new Intent(context, DialogActivity.class);
dlgIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(dlgIntent );

register/unregister a service through the toggle button more than once

This is what my code is... and I am getting a problem because of registering and unregistering(multiple times) my receiver(which is starting a service).
the problem is that: i have seen that the 'receiver' variable becomes NULL after once executing registerReceiver and unregisterReceiver commands... specifically, after I register and unregister and then again register the receiver, the receiver has NULL only, and hence, while unregistering it again, it gives an error! so basically, my app is not able to register a Receiver again after unregistering it once. why is that a problem?
public class startScreen extends Activity {
/** Called when the activity is first created. */
private BroadcastReceiver receiver=new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
Intent serviceIntent = new Intent();
serviceIntent.setAction("com.example.MyService");
context.startService(serviceIntent);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.initial);
final IntentFilter filter = new IntentFilter();
filter.addAction("android.net.wifi.STATE_CHANGE");
Button button = (Button) findViewById(R.id.button1);
final ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton1);
try
{
... some code...
if(bool == true)
{
toggleButton.setChecked(true);
this.registerReceiver(receiver, filter);
}
else
toggleButton.setChecked(false);
}catch(Exception e) {
Log.e("Error", "Database", e);
} finally {
...
}
toggleButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if((toggleButton.isChecked()))
{
getBaseContext().registerReceiver(receiver, filter);
}
else
{
if (receiver != null){
getBaseContext().unregisterReceiver(receiver);
receiver = null;
}
}
}
});
}
#Override
protected void onResume(){
super.onResume();
if(bool == true)
{
if(receiver == null)
this.registerReceiver(receiver, filter);
}
}
#Override
protected void onPause(){
super.onPause();
if (receiver != null){
this.unregisterReceiver(receiver);
receiver = null;
}
}
}
You are explicitly setting receiver to null inside toggleButton.setOnClickListener and in onPause:
receiver = null;
Try removing those lines and see if it fixes the issue

Categories

Resources