Android_Unit5_Unit6_Code_Examples
Android_Unit5_Unit6_Code_Examples
1. Explicit Intent
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
Output: Opens SecondActivity screen.
2. Implicit Intent
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://www.google.com"));
startActivity(intent);
Output: Opens Google in the browser.
4. BroadcastReceiver
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(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, MyService.class);
startService(i);
6. Play Audio
MediaPlayer mp = MediaPlayer.create(this, R.raw.soundfile);
mp.start();
Output: Plays audio file.
7. Text to Speech
TextToSpeech tts = new TextToSpeech(this, status -> {
if (status == TextToSpeech.SUCCESS) {
tts.speak("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.