Keywords: Android Development | Screen Rotation | Configuration Change Handling
Abstract: This paper comprehensively analyzes three core approaches to prevent Activity reloading during screen orientation changes in Android applications: distinguishing between initial creation and state restoration via savedInstanceState, locking screen orientation in the Manifest, and handling configuration changes using the configChanges attribute. The article details the implementation principles, applicable scenarios, and considerations for each method, emphasizing the importance of handling both orientation and screenSize in API level 13 and above, with complete code examples and best practice recommendations.
Introduction
Screen orientation change is a common runtime configuration change scenario in Android application development. By default, when a user rotates the device, the system destroys and recreates the current Activity, which may lead to state loss and disrupted user experience. This paper systematically explores effective strategies to prevent such reloading behavior.
Core Problem Analysis
When the screen orientation changes on an Android device, the system triggers a configuration change. The default handling mechanism destroys and recreates the current Activity, primarily to load layout resources appropriate for the new orientation. However, in certain scenarios, developers wish to maintain the current state unchanged, such as an application displaying random images that should not regenerate images upon screen rotation.
Solution 1: State Preservation and Restoration
The first method involves distinguishing between initial creation and state restoration within the Activity lifecycle. By overriding the onSaveInstanceState(Bundle outState) method to save critical data, then checking whether the savedInstanceState parameter in onCreate(Bundle savedInstanceState) is null, one can determine if it's the first creation or a state restoration.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
// Initial creation, load random image
loadRandomImage();
} else {
// State restoration, maintain existing image
restoreImageFromBundle(savedInstanceState);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save current image information
outState.putString("IMAGE_KEY", currentImageUrl);
}This approach is suitable for scenarios requiring fine-grained control over state restoration but increases code complexity.
Solution 2: Locking Screen Orientation
The second method locks the application to a specific orientation by adding the android:screenOrientation attribute to the <activity> tag in AndroidManifest.xml.
<activity
android:name=".MainActivity"
android:screenOrientation="portrait">
</activity>This method is straightforward and completely avoids configuration changes due to screen rotation. However, it restricts user freedom to choose orientation, potentially affecting user experience on certain devices.
Solution 3: Handling Configuration Changes
The third method uses the android:configChanges attribute to declare that the application will handle specific configuration changes itself. When a configuration change occurs, the Activity is not recreated but receives an onConfigurationChanged(Configuration newConfig) callback.
<activity
android:name=".MainActivity"
android:configChanges="orientation|screenSize">
</activity>In the Activity, one can optionally handle the callback or ignore it entirely:
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Layout adjustments can be made here, but no need to reload images
adjustLayoutForOrientation(newConfig.orientation);
}Important Note: Starting from API level 13, screen orientation changes also involve screen size changes, so both orientation and screenSize must be declared. Declaring only orientation is ineffective on API 13+ devices.
Comparison and Selection Recommendations
Each of the three solutions has its advantages and disadvantages: the state preservation method is the most flexible but most complex; the orientation locking method is the simplest but most restrictive; the configuration change handling method strikes a good balance between flexibility and complexity.
According to Android official documentation, handling configuration changes may be considered bad practice as it requires developers to manually manage all related resources. However, in simple scenarios such as maintaining random images unchanged, this is a reasonable choice.
Implementation Example
The following complete example demonstrates using the configuration change method to maintain random images:
// MainActivity.java
public class MainActivity extends AppCompatActivity {
private ImageView imageView;
private String currentImageUrl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
if (currentImageUrl == null) {
loadRandomImage();
} else {
// Image already exists, display directly
loadImage(currentImageUrl);
}
}
private void loadRandomImage() {
// Simulate random image loading
currentImageUrl = "https://example.com/image_" + System.currentTimeMillis() + ".jpg";
loadImage(currentImageUrl);
}
private void loadImage(String url) {
// Actual image loading logic
Glide.with(this).load(url).into(imageView);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Only adjust layout, do not reload images
adjustLayout();
}
private void adjustLayout() {
// Adjust layout parameters based on new orientation
ViewGroup.LayoutParams params = imageView.getLayoutParams();
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
params.height = ViewGroup.LayoutParams.MATCH_PARENT;
} else {
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
}
imageView.setLayoutParams(params);
}
}<!-- AndroidManifest.xml -->
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name">
<activity
android:name=".MainActivity"
android:configChanges="orientation|screenSize"
android:theme="@style/AppTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>Conclusion
Preventing Android applications from reloading during screen rotation requires selecting an appropriate strategy based on specific needs. For simple scenarios, the configuration change handling method offers the best balance; for complex applications requiring full control over state restoration, the state preservation method is more suitable; while orientation locking is applicable to dedicated applications with fixed orientations. Developers should make decisions considering API compatibility, user experience, and code maintenance costs.