目录
在 Android 开发中,我们可以通过 Intent
打开系统应用,比如浏览器、拨号界面、地图等。本示例将介绍如何点击按钮打开地图,并跳转到指定经纬度位置。适合初学者了解 Intent 跳转及 URI 构建的基本用法。
📄 文件名:activity_main.xml
代码语言:XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<Button
android:id="@+id/btn_3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="打开地图"/>
</LinearLayout>
📄 文件名:MainActivity.java
代码语言:Java
package com.example.mapdemo;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private Button btn_3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_3 = findViewById(R.id.btn_3);
// 打开地图
btn_3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// 纬度和经度
double latitude = 23.743282;
double longitude = 113.102215;
// 构建地图Uri
Uri geoUri = Uri.parse("geo:" + latitude + "," + longitude);
// 创建Intent
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(geoUri);
startActivity(intent);
}
});
}
}
📱 程序运行效果
运行程序后,点击“打开地图”按钮,系统会自动跳转到地图应用并定位到设置的经纬度(广州市附近)。如果设备未安装地图应用,可能会提示“无可用应用可处理此操作”。
📌 小贴士
-
推荐使用真机测试地图功能,部分模拟器不支持定位跳转。
-
geo:
URI 是 Android 内置支持的地理位置格式,可跳转地图应用。 -
可根据需要修改经纬度参数,跳转到任意地点。