Android how to start activity without intent or backround

帅比萌擦擦* 提交于 2021-01-18 07:05:13

问题


Suppose I have two activities A and B activity A which contains a button I want to start Activity B when I press Button without intent.


回答1:


According the Oficial Documentation:

An intent is an abstract description of an operation to be performed. It can be used with startActivity to launch an Activity, broadcastIntent to send it to any interested BroadcastReceiver components, and startService(Intent) or bindService(Intent, ServiceConnection, int) to communicate with a background Service.

An Intent provides a facility for performing late runtime binding between the code in different applications. Its most significant use is in the launching of activities, where it can be thought of as the glue between activities. It is basically a passive data structure holding an abstract description of an action to be performed.

So you have to use it to open activities with no exceptions or workarounds, if you do that, you are ignoring the entire system architecture.




回答2:


If the reason of not using Intent that you don't want the the user to re-enter the previous activity

You can use finish() to finish that activity intent after you done work with

if(currentUser == null){
    startActivity(new Intent(MainActivity.this,StartActivity.class));
    finish();
}

So user will be unable to back again

If you want to do some code while the activity is finishing

You can use onDestroy() override method, Sometimes it can also be called if the activity is being killed by the android itself so you can add

isFinishing() function

Inside onDestroy() method which checks whether the application is closing by the call finish() returning true or otherwise by anything else returning false then you can easily specify your code for each situation.

@Override
protected void onDestroy() {
    super.onDestroy();
    if(isFinishing()){
        // Activity is being destroyed by the function `finish()`
        // What to do...
    }else{
        // Activity is being destroyed anonymously without `finish()`
        // What to do...
    }
}



回答3:


There is no way to start an activity from anotherone without an intent.




回答4:


Put your activity inside a Fragment and start the fragment fromo the button.




回答5:


These are the possible ways to start any Activity

1st

startActivity(new Intent(Activity_A.this, Activity_B.class));

2nd

Intent intent = new Intent(Activity_A.this, Activity_B.class);
startActivity(intent);

3rd

Intent intent = new Intent(Activity_A.this, Activity_B.class);
startActivityForResult(intent,code);


来源:https://stackoverflow.com/questions/43636613/android-how-to-start-activity-without-intent-or-backround

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!