एक्टिविटी लाइफसाइकिल: onDestroy() समझना
यह उदाहरण दर्शाता है कि onDestroy() कब कॉल होता है और इसे कैसे लॉग करें। ध्यान दें: onDestroy() को मैन्युअली कॉल **नहीं** करना चाहिए; सिस्टम इसे उपयुक्त समय पर कॉल करता है।
चरण 1: नया प्रोजेक्ट बनाएं
Android Studio में File → New Project चुनें।
चरण 2: लेआउट XML (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:text="Destroy"
android:textColor="@color/colorPrimary"
android:textSize="32sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
चरण 3: MainActivity.java
package com.sample.q2;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
public static final String MY_TAG = "Destroy";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i(MY_TAG, "onCreate");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.i(MY_TAG, "onDestroy");
}
}
चरण 4: AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
onDestroy() कब कॉल होता है?
- एक्टिविटी
finish()होने पर - सिस्टम द्वारा मेमोरी रिक्लेम करने पर (लो मेमोरी)
- कॉन्फिगरेशन चेंज (रोटेशन) पर, यदि
android:configChangesनहीं संभाला गया - यूजर द्वारा "सभी ऐप्स बंद करें" से स्वाइप करने पर
⚠️ चेतावनी
कभी भी `onDestroy()` को मैन्युअली कॉल न करें। एक्टिविटी खत्म करने के लिए finish() या finishAffinity() का उपयोग करें। सिस्टम स्वचालित रूप से `onDestroy()` कॉल करेगा।
आउटपुट
Logcat में "Destroy: onCreate" और ऐप बंद होने पर "Destroy: onDestroy" दिखाई देगा।
