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)
Related
I am trying to call a function in a OnPreferenceClickListener which is defined in a another class. Since I have not managed to initialisation an interface in OnPreferenceClickListener. I have given an example code below:
public void onCreatePreferences(Bundle bundle, String s) {
ListPreference preference = findPreference(getString(R.string.settings_ble_choose_device_key));
preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(#NonNull Preference preference) {
callFunctionInMainActivity();
return false;
}
});
}
How i can call a function witch is implement in a another class?
Thank you very much
Rene
You can implement an intent for this. Where you send a broadcast from your OnPreferenceClickListener class and implement a broadcast received in the other class to listen for this intent and invoke the method that you want. Here is an example:
public void onCreatePreferences(Bundle bundle, String s) {
ListPreference preference = findPreference(getString(R.string.settings_ble_choose_device_key));
preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(#NonNull Preference preference) {
sendBroadcast(new Intent(Constants.ACTION_STOP_MAIN_SERVICE));
return true;
}
});
}
In your other class:
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action= intent.getAction();
if(action.equalsIgnoreCase(ConstantesIdentifiant.ACTION_STOP_MAIN_SERVICE)){
finishAffinity();
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerReceiver(broadcastReceiver, new IntentFilter(ConstantesIdentifiant.ACTION_STOP_MAIN_SERVICE));
}
#Override
protected void onDestroy() {
unbindService(mConnection);
unregisterReceiver(broadcastReceiver);
super.onDestroy();
}
I have a service which has an interface, I'm implementing the interface callback in multiple activities, but because of I'm calling the app instance on every activity's onCreate, the interfaces are responding on the current activity only. How do I make sure they work all together in every activity.
MyApp.java
public class MyApp extends Application {
private static MyApp myApp;
#Override
public void onCreate() {
super.onCreate();
myApp = new MyApp();
}
#Contract(pure = true)
public static synchronized MyApp getInstance() {
MyApp myApp;
synchronized (MyApp.class) {
myApp = MyApp.myApp;
}
return myApp;
}
public void setCallBackListener(MyService.ReceiversCallbacks receiversCallbacks) {
MyService.receiversCallbacks = receiversCallbacks;
}
}
MyService.java
public class MyService extends Service {
public static MyService.ReceiversCallbacks receiversCallbacks;
public MyService() {
super();
}
public interface ReceiversCallbacks {
void onReceiveCallbacks(String data);
}
#Override
public void onCreate() {
super.onCreate();
Notification notification = new NotificationCompat.Builder(this, NOTIFICATION_ID)
.setContentTitle("Background service")
.setSmallIcon(R.drawable.ic_launcher)
.build();
startForeground(1, notification);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (MY_LOGIC) receiversCallbacks.onReceiveCallbacks("DATA_FROM_MY_LOGIC");
//stopSelf();
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
ActivityA.java
public class ActivityA extends AppCompatActivity implements MyService.ReceiversCallbacks {
#Override
protected void onCreate(Bundle savedInstanceState) {
MyApp.getInstance().setCallBackListener(this);
}
#Override
public void onReceiveCallbacks(String data) {
// calling important functions
}
}
ActivityB.java
public class ActivityB extends AppCompatActivity implements MyService.ReceiversCallbacks {
#Override
protected void onCreate(Bundle savedInstanceState) {
MyApp.getInstance().setCallBackListener(this);
}
#Override
public void onReceiveCallbacks(String data) {
// calling important functions
}
}
Each activity's onCreate when I do this MyApp.getInstance().setCallBackListener(this); The focus of the call back shifts to the new activity. But I want the focus in both or more activities at the same time, how do I do that? Is there any better way for the solution I want?
Please note these:
I don't want to call those functions onResume
I don't want to use Broadcasts
I just created different interfaces for each activity and registered them to their corresponding activity, and they worked!
MyApp.getInstance().setCallBackListener(this);
I have service, which gets data from API and sends this data to BroadcastReceiver class. Also, I create interface OnReceiveListener, which used in Activity. Look at the code here:
Activity:
public class StartActivity extends AppCompatActivity
implements MyBroadcastReceiver.OnReceiveListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
MyBroadcastReceiver receiver = new MyBroadcastReceiver();
receiver.setOnReceiveListener(this);
LocalBroadcastManager.getInstance(this).registerReceiver(receiver,
new IntentFilter(MyBroadcastReceiver.START));
...
}
#Override
public void onReceive(Intent intent) {
// Do smth here
}
}
MyBroadcastReceiver:
public class MyBroadcastReceiver extends BroadcastReceiver {
public static final String START = "com.example.myapp.START";
public static final String GET_LINKS = "com.example.myapp.GET_LINKS";
private OnReceiveListener onReceiveListener = null;
public interface OnReceiveListener {
void onReceive(Intent intent);
}
public void setOnReceiveListener(Context context) {
this.onReceiveListener = (OnReceiveListener) context;
}
#Override
public void onReceive(Context context, Intent intent) {
if(onReceiveListener != null) {
onReceiveListener.onReceive(intent);
}
}
}
Service isn't important on this question.
---- Question ----
So, what's problem: I want to use this receiver in fragment, but when it sets context - I get exception "enable to cast". What I should to do on this case?
Here is my code in fragment:
public class MainFragment extends Fragment
implements MyBroadcastReceiver.OnReceiveListener {
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
MyBroadcastReceiver myBroadcastReceiver = new MyBroadcastReceiver();
myBroadcastReceiver.setOnReceiveListener(getContext());
LocalBroadcastManager.getInstance(getContext()).registerReceiver(myBroadcastReceiver,
new IntentFilter(MyBroadcastReceiver.GET_LINKS));
}
#Override
public void onReceive(Intent intent) {
// Do smth here
}
}
Your MainFragment class implements your OnReceiveListener interface, not its Context as returned by getContext(). Instead of passing a Context object into setOnReceiveListener(), try directly passing an OnReceiveListener instance. Then your fragment and activity can both call setOnReceiveListener(this).
you don't need to dynamically register the receiver. i believe you must have registered it in manifest using <receiver> tag.
this is not required:
LocalBroadcastManager.getInstance(getContext()).registerReceiver(myBroadcastReceiver,
new IntentFilter(MyBroadcastReceiver.GET_LINKS));
and about callback registering listener, instead of using getContext() use MainFragment.this like this:
myBroadcastReceiver.setOnReceiveListener(MainFragment.this);
After searching for hours for the appropriate way to implement such a solution to this problem, I've found a way finally. It is based on RussHWolf's answer. The complete solution with code is below:
In this way, a setListener() method is exposed so that Fragment or Activity can set the listener by sending an instance of IStatusChangeListener.
public class StatusChangeReceiver extends BroadcastReceiver {
private IStatusChangeListener listener;
public void setListener(IStatusChangeListener listener) {
this.listener = listener;
}
#Override
public void onReceive(Context context, Intent intent) {
if (NetworkUtil.isNetworkConnected()) {
listener.onConnected();
} else {
listener.onDisconnected();
}
}
}
This is the interface:
public interface IStatusChangeListener {
void onConnected(String status);
void onDisonnected(String status);
}
Now, it is required to have an instance of IStatusChangeListener interface instead of implementing the IStatusChangeListener interface. And then, pass this instance of IStatusChangeListener to setListener() method.
public class MainFragment extends Fragment { //Not implementing the interface
private IStatusChangeListener listener = new IStatusChangeListener() {
#Override
void onConnected(String status) {
//some log here
}
#Override
void onDisonnected(String status) {
//some log here
}
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
StatusChangeReceiver r = new StatusChangeReceiver();
r.setListener(listener); // pass the IStatusChangeListener instance
LocalBroadcastManager.getInstance(getContext()).registerReceiver(r, new IntentFilter("connectionStatus"));
}
}
Note: Always use LocalBroadcastManager if you register BroadcastReceiver from Fragment.
I've implemented a RecyclerView which has a user interface of a timer counting down. I created a BroadcastService class which creates a CountDownTimer and broadcasts the timer's contents in the onTick() method to my MainActivity, where I use a BroadCast receiever to update the UI.
My BroadcastReceiver is only receiving the initial value from the BroadcastService. I figured that's because I hadn't notified the recycler view's adapter that the data had changed. However, because of variable scope, I'm unable to access my adapter from my broadcast receiver.
Perhaps I have a fundamental lack of understanding of variable scope, but how can I access the adapter from
adapter = new DataAdapter(getApplicationContext(), data);
in my broadcast receiver class? Because right now it's not being recognized.
This is my class definition + onCreate()
public class Profile_Page extends ActionBarActivity implements DataAdapter.ClickListener {
private RecyclerView recyclerView;
public DataAdapter adapter;
private Context context;
String currentUser;
Data current = new Data();
final List<Data> data = new ArrayList<>();
public static String BROADCAST_ACTION =
"packagename.countdown_br";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IntentFilter filter = new IntentFilter();
filter.addAction(BROADCAST_ACTION);
filter.addCategory(Intent.CATEGORY_DEFAULT);
registerReceiver(br, filter);
startService(new Intent(this, Broadcast_Service.class));
setContentView(R.layout.activity_profile__page);
ParseQuery<ParseObject> query = ParseQuery.getQuery("ParseClass");
query.whereEqualTo("author", ParseUser.getCurrentUser());
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, ParseException e) {
if (e == null) {
for (ParseObject getData : list)
{
current.1= getData.getString("1");
current.2= getData.getString("2");
current.3= getData.getString("3");
current.4= getData.getString("4");
current.5= getData.getString("5");
data.add(current);
}
}
else {
}
adapter = new DataAdapter(getApplicationContext(), data);
recyclerView.setAdapter(adapter); //set recyclerView to this adapter
}
});
}
And here's my Broadcast Receiver code [which is also in MainActivity.java]
public BroadcastReceiver br = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateGUI(intent);
//HOW TO NOTIFY DATA SET CHANGE
}
};
public void updateGUI(Intent intent) {
if (intent.getExtras() != null) {
long millisUntilFinished = intent.getLongExtra("countdown", 0);
current.goalTimer = String.valueOf(intent.getExtras().getLong("countdown") / 1000);
}
}
And, if it is of any use, here's my Broadcast Service class:
public class Broadcast_Service extends Service {
private final static String TAG = "BroadcastService";
LocalBroadcastManager broadcastManager;
public static final String COUNTDOWN_BR = "packagename.countdown_br";
Intent bi = new Intent(COUNTDOWN_BR);
CountDownTimer cdt = null;
#Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Starting timer...");
cdt = new CountDownTimer(30000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
bi.putExtra("countdown", millisUntilFinished);
sendBroadcast(bi);
}
#Override
public void onFinish() {
Log.i(TAG, "Timer finished");
}
};
cdt.start();
}
#Override
public void onDestroy() {
cdt.cancel();
Log.i(TAG, "Timer cancelled");
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
First of all, extend the BroadcastReciever class as follows:
public class MyReciever extends BroadcastReciever{
private Profile_Page activity;
public MyReciever(Profile_Page activity){
this.activity = activity;
}
#Override
public void onReceive(Context context, Intent intent) {
activity.updateGUI(intent);
}
}
Create a static instance of your activity and pass it to your receiver.
public class Profile_Page extends ActionBarActivity implements DataAdapter.ClickListener {
private static Profile_Page instance;
private MyReciever myReceiver;
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
instance = this;
myReceiver = new MyReciever(instance);
...
}
public void updateGUI(Intent intent) {
...
}
}
Now you can access your adapter quite easily. Hope this helps.
In my Activity1, I have an AsyncTask that uploads to the server. Once this task is started, I want to start Activity, without waiting for the completion of AsyncTask. When the AsyncTask from Activity1 is completed, I want to update something in Activity2. After doing some searching, I've found multiple references/examples of using interfaces. But I ran into the following problem:
OnUploadCompleted Interface
public interface OnUploadCompleted {
void on UploadCompleted();
}
Activity2
public class Activity2 extends Activity implements OnUploadCompleted {
// all the usual activity code
#Override
public void onUploadCompleted() {
Toast.makeText(this, "Upload Done", ....
}
}
Activity1
public class Activity1 extends Activity {
// all the usual activity code
private class Upload extends AsyncTask<...> {
OnUploadCompleted listener;
public Upload(OnUploadCompleted listener) {
this.listener = listener;
}
// skipping doInBackground task
#Override
protected void onPostExecute(...) {
super.onPostExecute();
listener.onUploadCompleted();
}
}
void foo (...) {
OnUploadCompleted listener = new Activity2();
Upload upload = new Upload(listener);
upload.execute();
finish();
}
}
The problem I have is in the foo() function. the listener is a new instance of Activity2 class, but Activity2 hasn't been created yet. It will be created by the parent activity of Activity1, after the finish(). So, when the listener is actually called, the activity that it's "connected" to is null. In the onUploadCompleted(), when Toast is called, the "this" is null.
try sending Broadcasts to ACtivity2 from Activity1 when Activity1's AsyncTask completed...
public class MainActivity extends Activity {
public static final String ACTION_TASK_COMPLETED = "com.sample.project.action.ACTION_TASK_COMPLETED";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class DoTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// please wait. I am doing work
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// yay... work completed...
Intent intent = new Intent(ACTION_TASK_COMPLETED);
LocalBroadcastManager.getInstance(MainActivity.this).sendBroadcast(intent);
}
}
}
public class SecondActivity extends Activity {
private TaskReceiver taskReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IntentFilter intentFilter = new IntentFilter(MainActivity.ACTION_TASK_COMPLETED);
taskReceiver = new TaskReceiver();
LocalBroadcastManager.getInstance(this).registerReceiver(taskReceiver, intentFilter);
}
#Override
protected void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(this).unregisterReceiver(taskReceiver);
}
private void onUploadImage() {
// uploading completed...
}
private class TaskReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
onUploadImage();
}
}
}