How to access another activity? - android

Just to make it clear, this is not I want. I want to access another Activity's context.
Suppose I've two activities, MainActivity and WebActivity. In MainActivity I used oAuth2 login, and after login I start the WebActivity. In WebActivity I need to logout with the function mTencent.logout(MainActivity.this);, the question is how can I access MainActivity from WebActivity?
If I do this directly, I get the error,
MainActivity is not an enclosing class?
Considering I'm a starter of android, here may be not the exact way to implement it.
Will someone help? Thank you!
The API : void com.tencent.tauth.Tencent.logout(Context context)

Use Application context in your login and logout methods. As they will be managed at Application level.
So change mTencent.logout(MainActivity.this); to mTencent.logout(getApplicationContext());.
Also change your login method to work in application context.

Instead of using context of one activity in other which may result in crashes sometimes.
u can use libraries like EventBus to link the code.
Define a class which implements event u want to perform eg:LogOutEvent.java
public static class LogOutEvent { /* Additional fields if needed */ }
U can post events like logout from WebViewActivity.java using following command
EventBus.getDefault().post(new LogOutEvent());
and in MainActivity you first need to register event bus
#Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
public void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
and then in MainActivity you can subscribe for events like this
#Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(LogOutEvent event) {/* Do log out here */};

There is a good practice solution to your problem which involves certain steps to be performed:
1- Define an interface:
public interface LogOutInterface {
public void logout();
}
2- Have your MainActivity implement this interface:
public class MainActivity extends ???? implements LogOutInterface {
...
#Override
public void logout(){
//your logout procedure
}
}
3- Have a public method for your WebActivity and allow it to accept LogOutInterface:
public class WebActivity ... {
private LogOutInterface logoutInterface;
...
public void setLogOut(LogOutInterface logoutInterface) {
this.logoutInterface = logoutInterface;
}
}
4- call setLogOut from MainActivity:
public class MainActivity ... {
public void yourmethod() {
...
webActivity.setLogOut(this);
}
}
5- call logout function from your WebActivity:
public class WebActivity ... {
...
public void yourmethod() {
logoutInterface.logout();
}
}
hope this helps.

This is a workable one.
In the MainActivity, public static Activity thisActivity; & thisActivity = this; then in the WebActivity mTencent.logout(MainActivity.thisActivity);
or just can put the logout function as public static function of MainActivity,
public static void logout() {
if (mTencent.isSessionValid()) {
mTencent.logout(thisActivity);
}
}
then call MainActivity.logout() from WebActivity.

Related

Notify when onPause() called in any activity of an application

I think this question may simple but I didn't find any solution for this,
I there any way in Android that if any one of an activity calls onPause() I need to show Toast message or any notification kind of thing need to show. Generally I want to get notified when activity calls onPause() but I need it in one place since I may have some 15 activity I don't want to add it in all the activity.
ex:If I have activity when any one of the activity calls onPause I need to get notified but that notification code should be in one place and we should not add any line of code onPause() Is it possible to do this.
Thanks.
Create a baseActivity, which has for example :
open class BaseActivity : AppCompatActivity() {
override fun onPause() {
super.onPause()
Toast.makeText(this, "notified", Toast.LENGTH_SHORT).show()
}
}
Then you can extends this in your activities and handle the on pause call in BaseActivity
If your minSdkVersion >= 14, you can use Application.ActivityLifecycleCallbacks: ActivityLifecycleCallbacks
You have to define a custom Application class and you can register for this callbacks afterwards:
public class MyApplication extends Application {
private class LifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
#Override
public void onActivityCreated(final Activity activity, final Bundle savedInstanceState) {
//nothing to do
}
#Override
public void onActivityDestroyed(final Activity activity) {
//nothing to do
}
#Override
public void onActivityPaused(final Activity activity) {
// TODO Do your stuff, e.g. show toast.
}
#Override
public void onActivityResumed(final Activity activity) {
//nothing to do
}
#Override
public void onActivitySaveInstanceState(final Activity activity, final Bundle outState) {
//nothing to do
}
#Override
public void onActivityStarted(final Activity activity) {
}
#Override
public void onActivityStopped(final Activity activity) {
}
}
private final LifecycleCallbacks callbacks;
public void onCreate() {
super.onCreate();
callbacks = new LifecycleCallbacks();
application.registerActivityLifecycleCallbacks(callbacks);
}
}
Create a BaseActivity which contain all the methods you want to use in all other activities.
Then extend every activity with BaseActivity to call onPause() method.

Start two activities simultaneously one in foreground other in background

I have two activities SplashScreen and MainActivity.
MainActvity download some data and show it.
Now I want to start both activities on application start, MainActivity in background and SplashScreen in foreground and when the data of MainActivity download complete I want to make MainActivity foreground and finish SplashScreen.
I have seen many solution but no one is going good in my situation.
Please give me some suggestion or example .
I think it's better to make splash screen to download data and when it completed show new activity (MainActivity). In onStart metod use downloaded data stored on phone.
Your example: The only way You can have resolve this your way is by start MainActivity first and from onStart start SplashScreen:
class SplashScreen extends Activitiy {
public void onStart() {
EventBus.register(this);
}
#Subscribe
public void finishedDownload(FinishedDownloadEvent) {
this.finish()
}
}
class MainActivity extens Activity () {
public void onStart () {
open(new Intent(SplashScreen.class)); // We would like to have
download();
}
public void download (OnFinish onFinish) {
... download
EventBus.post(new FinishedDownloadEvent());
}
}
I forgot:
class EventBus {
private final static Bus instance = new Bus();
public static void register (Object obj) {
instance.register(obj)
}
public static void post (Event obj) {
instance.post(obj)
}
}
EventBuss

Call function from jar in MainActivity

First time I'm trying to make my own .jar file. It works, but now I want to give feedback to the MainActivity. So I want to call a function 'receiveSerial()' in the MainActivity.
So the MainActivity must always implement the function 'receiveSerial()' when including my .jar.
.jar file (part of the) code:
package com.hoeks.ma.bluetooth;
import java.util.Set;
import ...
public class Blauwe{
..
private Activity ma;
public Blauwe(Activity m){
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
ma = (Activity)m;
}
..
public void sendSerial(String s) {
ma.receiveSerial(s); // This line give Eclipse error "Add cast to ma"
// When I add the cast it is not working
}
MainActivity
import com.hoeks.ma.bluetooth.Blauwe;
....
public void receiveSerial(String s) {
javascr.setSerial(s);
}
Note: I do not post the whole code because the code is a big mess right now, its not good for the readability.
1) create interface
public interface ReceiveSerialCallback{
public void receiveSerial(String s);
}
2) add interface implementation in MainActivity
public class MainActivity implements ReceiveSerialCallback{
...
public void receiveSerial(String s) {
// serial received
}
}
3) update Blauwe class
private ReceiveSerialCallback callback;
...
public void setReceiveSerialCallback(ReceiveSerialCallback callback) {
this.callback = callback;
}
...
public void sendSerial(String s) {
callback.receiveSerial(s);
}
4) set inteface callback object to Blauwe class in MainActivity
Blauwe b = new Blauwe();
b.setReceiveSerialCallback(this);
You have to cast because receiveSerial(String) is not a method of Activity, but MainActivity. I would create an interface (with method sendSerial) that MainActivity should implement, and save a reference of this interface in Blauwe class, instead of an Activity instance.

How Send message from fragment to activity and received and use in activity?

Please please don't minus my question i confused when googling.
I used Android Tab Layout with Swipeable Views in my code for when user pressed setting button on an activity.
now I need send message from TopRatedFragment.java that extends from fragment to the activity that call the mainActivity of "Android Tab Layout with Swipeable Views".
You can do this by implementing a call back
create an interface first
public interface CommunicationInterface {
public void onSuccess();
public void onFailed();
}
then in your activity implement the interface
public class YourActivity extends ActionBarActivity implements CommunicationInterface {
//default functions
#Override
public void onSuccess() {
//stuff you want to do in the acivity
}
#Override
public void onFailed() {
//stuff you want to do in the acivity
}
}
Now in the fragment
public class yourfragment extends Fragment {
CommunicationInterface callback;
//stuffs that usually come in yor fragment and like OncreateView etc
#Override
public void onActivityCreated(#Nullable Bundle outState) {
super.onActivityCreated(outState);
//after all the stuff you want to do in your fragment then implement //call back function to communicate with the activity
callback= (CommunicationInterface) getActivity();
callback.onSuccess();//according to your purpose use where ever you like
callback.onFailed();//according to your purpose use where ever you like
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
callback= (CommunicationInterface) activity;
}
}
Take a close look on this reference:
Creating event callbacks to the activity
The android docs recommend using this pattern of having the parent activity implement an interface of the fragment (Basically calling methods on it)
class MyFragment extends Fragment {
interface Listener {
public void onSomeEvent();
}
private void somethingHappeninInTheFragment() {
// let the activity know
((Listener) getActivity()).onSomeEVent();
}
}
class MyActivity extends Activity implements MyFragment.Listener {
// etc
#Override
public void onSomeEvent() {
// handle the message from the fragment
}
}
Explained with a more concrete example here: http://developer.android.com/guide/components/fragments.html#EventCallbacks
Here's the solution:
Step 1 : From your fragment.
Intent i = new Intent(getActivity(), YourActivity.class);
i.putExtra("key", "Your value1");
i.putExtra("key2", "Your value2");
i.putExtra("key3", "Your value3");
getActivity().startActivity(i);
Step 2 : In your Activity where you want the result
Intent getResults = getIntent();
String firstValue = getResults.getStringExtra("key1");
String secondValue = getResults.getStringExtra("key2");
String thirdValue = getResults.getStringExtra("key3");
Use those values your needs are.
Hope this helps.. :)

Call Public void

I have a public void in one class and I want to call it in another class when it creates but nothing seems to be working. here is the code of my first activity
public class activityone extends Activity {
public void actionC() {
//actions
}
Does anyone know how to call it in my second class?
In general, you need to have an instance of your activityone class in order to call an instance method.
To create an instance, you generally use a constructor like:
activityone a = new activityone();
a.actionC();
I'm not sure this is what you want though, because Activitys are generally created by the Android system itself and you should handle the onCreate method instead.
Here is what you can do:
public class activityone extends Activity {
/*public void actionC() {*/ //Instead on normal method, write your actions in onCreate()
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//actions
}
and in your second activity, do this:
Intent intent = new Intent(getApplicationContext(),activityone.class);
startActivity(intent);
Hope it helps !!!

Categories

Resources