
上QQ阅读APP看书,第一时间看更新
How to do it...
Again, to keep the example simple so that we can focus on the task at hand, we will create a function to show an intent in action and call this function from a button on our activity.
Once your new project is created in Android Studio, follow these steps:
- Open the MainActivity.java class and add the following function:
public void launchIntent(View view) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse("https://www.packtpub.com/")); startActivity(intent); }
- While you are typing this code, Android Studio will give this warning on View and intent: Cannot resolve symbol 'Intent'.
- This means that you need to add the library reference to the project. You can do this manually by entering the following code in the import section:
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
Alternatively, let Android Studio add the library reference for you: just click on the code highlighted with a red font and press Alt + Enter.
- Open the activity_main.xml file and replace the <TextView /> block with the following XML:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Launch Browser"
android:id="@+id/button"
android:onClick="launchIntent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"/>

- Now, it's time to run the application and see the intent in action. You will need to either create an Android emulator (in Android Studio, go to Tools | Android | AVDManager) or connect a physical device to your computer.
- When you press the Launch Browser button, you will see the default web browser open with the URL specified.