Important Android Methods & Classes with Code Examples (Unit 5 & 6)
1. Explicit Intent
Intent intent = new Intent([Link], [Link]);
startActivity(intent);
Output: Opens SecondActivity screen.
2. Implicit Intent
Intent intent = new Intent(Intent.ACTION_VIEW);
[Link]([Link]("[Link]
startActivity(intent);
Output: Opens Google in the browser.
3. Activity Lifecycle Logging
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
Log.d("ActivityState", "onCreate Called");
}
Output: Logcat shows 'onCreate Called'.
4. BroadcastReceiver
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
[Link](context, "Broadcast Received", Toast.LENGTH_SHORT).show();
}
}
Intent intent = new Intent("MY_CUSTOM_BROADCAST");
sendBroadcast(intent);
Output: Toast saying 'Broadcast Received'.
5. Start Service
Intent i = new Intent(this, [Link]);
startService(i);
public class MyService extends Service {
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("ServiceDemo", "Service Started");
return START_STICKY;
}
}
Output: Logcat shows 'Service Started'.
6. Play Audio
MediaPlayer mp = [Link](this, [Link]);
[Link]();
Output: Plays audio file.
7. Text to Speech
TextToSpeech tts = new TextToSpeech(this, status -> {
if (status == [Link]) {
[Link]("Hello World", TextToSpeech.QUEUE_FLUSH, null, null);
}
});
Output: Speaks 'Hello World'.
8. Camera Capture
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 1);
Output: Opens camera and captures image.
9. SQLite Insert & Query
SQLiteDatabase db = openOrCreateDatabase("StudentDB", MODE_PRIVATE, null);
[Link]("CREATE TABLE IF NOT EXISTS student(name VARCHAR);");
[Link]("INSERT INTO student VALUES('Alex');");
Cursor c = [Link]("SELECT * FROM student", null);
if ([Link]()) {
[Link](this, [Link](0), Toast.LENGTH_SHORT).show(); // Shows "Alex"
}
Output: Toast with 'Alex'.
10. Fragment Transaction
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
[Link]([Link], new MyFragment());
[Link]();
Output: Replaces layout with MyFragment.