📜  如何在 Android 片段中获取当前位置?

📅  最后修改于: 2022-05-13 01:55:42.415000             🧑  作者: Mango

如何在 Android 片段中获取当前位置?

Fragment 是一个活动的一部分,可以实现更模块化的活动设计。片段封装了功能,以便更容易在活动和布局中重用。 Android 设备存在各种屏幕尺寸和密度。片段简化了组件在不同布局及其逻辑中的重用。您可以为手机(电话)构建单窗格布局,为平板电脑构建多窗格布局。您还可以使用片段来支持智能手机上横向和纵向的不同布局。下图显示了如何将片段定义的两个 UI 模块组合成一个活动以用于平板电脑设计,但如何将其分开以用于手机设计。

Android 中的片段

在本文中,我们将实现一个应用程序,在该应用程序中我们可以获得当前位置的坐标。我们将看到我们可以在 Fragment 中获得该当前位置的人。

我们将在本文中构建什么?

这是我们将在本文中构建的示例视频。请注意,我们将使用Java语言来实现这个项目。

分步实施

步骤 1. 创建一个新项目

  • 打开一个新项目。
  • 我们将使用Java语言开发 Empty Activity。保持所有其他选项不变。
  • 在您方便的时候命名应用程序。
  • 将有两个名为 activity_main.xml 和 MainActivity 的默认文件。Java

如果您不知道如何在 Android Studio 中创建新项目,可以参考如何在 Android Studio 中创建/启动新项目?

步骤 2. 添加所需的依赖项

导航到 Gradle Scripts > gradle.scripts(module) 并添加以下依赖项

implementation 'com.google.android.gms:play-services-location:17.0.0'

步骤 3. 添加所需权限

导航到 AndroidManifest.xml 文件并向其中添加以下代码 -


步骤 4. 处理 XML 文件

导航到 app > res > layout > activity_main.xml 并将以下代码添加到该文件。下面是 activity_main.xml 文件的代码。

XML


  
    
  


XML


  
   


Java
package com.example.currentloactioninfragment;
  
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
  
import android.os.Bundle;
  
public class MainActivity extends AppCompatActivity {
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // Initialize fragment
        Fragment fragment= new MainFragment();
  
        // open fragment
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.frame_layout,fragment)
                .commit();
    }
}


Java
package com.example.currentloactioninfragment;
  
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Looper;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.core.content.PackageManagerCompat;
import androidx.fragment.app.Fragment;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
  
public class MainFragment extends Fragment {
  
    // Initialize variables
    Button btLocation;
    TextView tvLatitude, tvLongitude;
    FusedLocationProviderClient client;
  
    @Override
    public View onCreateView(LayoutInflater inflater,
                             ViewGroup container,
                             Bundle savedInstanceState)
    {
        // Initialize view
        View view = inflater.inflate(R.layout.fragment_main,
                                     container, false);
  
        // Assign variable
        btLocation = view.findViewById(R.id.bt_location);
        tvLatitude = view.findViewById(R.id.tv_latitude);
        tvLongitude = view.findViewById(R.id.tv_longitude);
  
        // Initialize location client
        client = LocationServices
                     .getFusedLocationProviderClient(
                         getActivity());
  
        btLocation.setOnClickListener(
            new View.OnClickListener() {
                @Override public void onClick(View view)
                {
                    // check condition
                    if (ContextCompat.checkSelfPermission(
                            getActivity(),
                            Manifest.permission
                                .ACCESS_FINE_LOCATION)
                            == PackageManager
                                   .PERMISSION_GRANTED
                        && ContextCompat.checkSelfPermission(
                               getActivity(),
                               Manifest.permission
                                   .ACCESS_COARSE_LOCATION)
                               == PackageManager
                                      .PERMISSION_GRANTED) {
                        // When permission is granted
                        // Call method
                        getCurrentLocation();
                    }
                    else {
                        // When permission is not granted
                        // Call method
                        requestPermissions(
                            new String[] {
                                Manifest.permission
                                    .ACCESS_FINE_LOCATION,
                                Manifest.permission
                                    .ACCESS_COARSE_LOCATION },
                            100);
                    }
                }
            });
  
        // Return view
        return view;
    }
  
    @Override
    public void onRequestPermissionsResult(
        int requestCode, @NonNull String[] permissions,
        @NonNull int[] grantResults)
    {
        super.onRequestPermissionsResult(
            requestCode, permissions, grantResults);
        // Check condition
        if (requestCode == 100 && (grantResults.length > 0)
            && (grantResults[0] + grantResults[1]
                == PackageManager.PERMISSION_GRANTED)) {
            // When permission are granted
            // Call  method
            getCurrentLocation();
        }
        else {
            // When permission are denied
            // Display toast
            Toast
                .makeText(getActivity(),
                          "Permission denied",
                          Toast.LENGTH_SHORT)
                .show();
        }
    }
  
    @SuppressLint("MissingPermission")
    private void getCurrentLocation()
    {
        // Initialize Location manager
        LocationManager locationManager
            = (LocationManager)getActivity()
                  .getSystemService(
                      Context.LOCATION_SERVICE);
        // Check condition
        if (locationManager.isProviderEnabled(
                LocationManager.GPS_PROVIDER)
            || locationManager.isProviderEnabled(
                LocationManager.NETWORK_PROVIDER)) {
            // When location service is enabled
            // Get last location
            client.getLastLocation().addOnCompleteListener(
                new OnCompleteListener() {
                    @Override
                    public void onComplete(
                        @NonNull Task task)
                    {
  
                        // Initialize location
                        Location location
                            = task.getResult();
                        // Check condition
                        if (location != null) {
                            // When location result is not
                            // null set latitude
                            tvLatitude.setText(
                                String.valueOf(
                                    location
                                        .getLatitude()));
                            // set longitude
                            tvLongitude.setText(
                                String.valueOf(
                                    location
                                        .getLongitude()));
                        }
                        else {
                            // When location result is null
                            // initialize location request
                            LocationRequest locationRequest
                                = new LocationRequest()
                                      .setPriority(
                                          LocationRequest
                                              .PRIORITY_HIGH_ACCURACY)
                                      .setInterval(10000)
                                      .setFastestInterval(
                                          1000)
                                      .setNumUpdates(1);
  
                            // Initialize location call back
                            LocationCallback
                                locationCallback
                                = new LocationCallback() {
                                      @Override
                                      public void
                                      onLocationResult(
                                          LocationResult
                                              locationResult)
                                      {
                                          // Initialize
                                          // location
                                          Location location1
                                              = locationResult
                                                    .getLastLocation();
                                          // Set latitude
                                          tvLatitude.setText(
                                              String.valueOf(
                                                  location1
                                                      .getLatitude()));
                                          // Set longitude
                                          tvLongitude.setText(
                                              String.valueOf(
                                                  location1
                                                      .getLongitude()));
                                      }
                                  };
  
                            // Request location updates
                            client.requestLocationUpdates(
                                locationRequest,
                                locationCallback,
                                Looper.myLooper());
                        }
                    }
                });
        }
        else {
            // When location service is not enabled
            // open location setting
            startActivity(
                new Intent(
                    Settings
                        .ACTION_LOCATION_SOURCE_SETTINGS)
                    .setFlags(
                        Intent.FLAG_ACTIVITY_NEW_TASK));
        }
    }
}


导航到应用 > 右键单击 > 新建 > 片段 > 空白片段并将其命名为 MainFragment。在 fargment_main.xml 文件中使用以下代码 -

XML



  
   

步骤 5. 处理Java文件

导航到 MainActivity。 Java文件并在其中使用以下代码。代码中添加了注释以便更好地理解。

Java

package com.example.currentloactioninfragment;
  
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
  
import android.os.Bundle;
  
public class MainActivity extends AppCompatActivity {
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // Initialize fragment
        Fragment fragment= new MainFragment();
  
        // open fragment
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.frame_layout,fragment)
                .commit();
    }
}

导航到 MainFragment。 Java文件并在其中使用以下代码。代码中添加了注释以便更好地理解。

Java

package com.example.currentloactioninfragment;
  
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Looper;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.core.content.PackageManagerCompat;
import androidx.fragment.app.Fragment;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
  
public class MainFragment extends Fragment {
  
    // Initialize variables
    Button btLocation;
    TextView tvLatitude, tvLongitude;
    FusedLocationProviderClient client;
  
    @Override
    public View onCreateView(LayoutInflater inflater,
                             ViewGroup container,
                             Bundle savedInstanceState)
    {
        // Initialize view
        View view = inflater.inflate(R.layout.fragment_main,
                                     container, false);
  
        // Assign variable
        btLocation = view.findViewById(R.id.bt_location);
        tvLatitude = view.findViewById(R.id.tv_latitude);
        tvLongitude = view.findViewById(R.id.tv_longitude);
  
        // Initialize location client
        client = LocationServices
                     .getFusedLocationProviderClient(
                         getActivity());
  
        btLocation.setOnClickListener(
            new View.OnClickListener() {
                @Override public void onClick(View view)
                {
                    // check condition
                    if (ContextCompat.checkSelfPermission(
                            getActivity(),
                            Manifest.permission
                                .ACCESS_FINE_LOCATION)
                            == PackageManager
                                   .PERMISSION_GRANTED
                        && ContextCompat.checkSelfPermission(
                               getActivity(),
                               Manifest.permission
                                   .ACCESS_COARSE_LOCATION)
                               == PackageManager
                                      .PERMISSION_GRANTED) {
                        // When permission is granted
                        // Call method
                        getCurrentLocation();
                    }
                    else {
                        // When permission is not granted
                        // Call method
                        requestPermissions(
                            new String[] {
                                Manifest.permission
                                    .ACCESS_FINE_LOCATION,
                                Manifest.permission
                                    .ACCESS_COARSE_LOCATION },
                            100);
                    }
                }
            });
  
        // Return view
        return view;
    }
  
    @Override
    public void onRequestPermissionsResult(
        int requestCode, @NonNull String[] permissions,
        @NonNull int[] grantResults)
    {
        super.onRequestPermissionsResult(
            requestCode, permissions, grantResults);
        // Check condition
        if (requestCode == 100 && (grantResults.length > 0)
            && (grantResults[0] + grantResults[1]
                == PackageManager.PERMISSION_GRANTED)) {
            // When permission are granted
            // Call  method
            getCurrentLocation();
        }
        else {
            // When permission are denied
            // Display toast
            Toast
                .makeText(getActivity(),
                          "Permission denied",
                          Toast.LENGTH_SHORT)
                .show();
        }
    }
  
    @SuppressLint("MissingPermission")
    private void getCurrentLocation()
    {
        // Initialize Location manager
        LocationManager locationManager
            = (LocationManager)getActivity()
                  .getSystemService(
                      Context.LOCATION_SERVICE);
        // Check condition
        if (locationManager.isProviderEnabled(
                LocationManager.GPS_PROVIDER)
            || locationManager.isProviderEnabled(
                LocationManager.NETWORK_PROVIDER)) {
            // When location service is enabled
            // Get last location
            client.getLastLocation().addOnCompleteListener(
                new OnCompleteListener() {
                    @Override
                    public void onComplete(
                        @NonNull Task task)
                    {
  
                        // Initialize location
                        Location location
                            = task.getResult();
                        // Check condition
                        if (location != null) {
                            // When location result is not
                            // null set latitude
                            tvLatitude.setText(
                                String.valueOf(
                                    location
                                        .getLatitude()));
                            // set longitude
                            tvLongitude.setText(
                                String.valueOf(
                                    location
                                        .getLongitude()));
                        }
                        else {
                            // When location result is null
                            // initialize location request
                            LocationRequest locationRequest
                                = new LocationRequest()
                                      .setPriority(
                                          LocationRequest
                                              .PRIORITY_HIGH_ACCURACY)
                                      .setInterval(10000)
                                      .setFastestInterval(
                                          1000)
                                      .setNumUpdates(1);
  
                            // Initialize location call back
                            LocationCallback
                                locationCallback
                                = new LocationCallback() {
                                      @Override
                                      public void
                                      onLocationResult(
                                          LocationResult
                                              locationResult)
                                      {
                                          // Initialize
                                          // location
                                          Location location1
                                              = locationResult
                                                    .getLastLocation();
                                          // Set latitude
                                          tvLatitude.setText(
                                              String.valueOf(
                                                  location1
                                                      .getLatitude()));
                                          // Set longitude
                                          tvLongitude.setText(
                                              String.valueOf(
                                                  location1
                                                      .getLongitude()));
                                      }
                                  };
  
                            // Request location updates
                            client.requestLocationUpdates(
                                locationRequest,
                                locationCallback,
                                Looper.myLooper());
                        }
                    }
                });
        }
        else {
            // When location service is not enabled
            // open location setting
            startActivity(
                new Intent(
                    Settings
                        .ACTION_LOCATION_SOURCE_SETTINGS)
                    .setFlags(
                        Intent.FLAG_ACTIVITY_NEW_TASK));
        }
    }
}

这是我们应用程序的最终输出。

输出: