如何在MainActivity类中调用非活动类?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在MainActivity类中调用非活动类?相关的知识,希望对你有一定的参考价值。

我有Fused Location Api类,它现在扩展了AppCompatActivity。我想让它成为非活动类,并在MainActivity或任何其他活动类中调用它。我怎样才能做到这一点?我是新手。所以,任何建设性的批评都会非常感激。

public class GpsLocation extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener, LocationListener 

private Location location;
private TextView locationTv;
private GoogleApiClient googleApiClient;
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
private LocationRequest locationRequest;
private static final long UPDATE_INTERVAL = 5000, FASTEST_INTERVAL = 5000; // = 5 seconds
// lists for permissions
private ArrayList<String> permissionsToRequest;
private ArrayList<String> permissionsRejected = new ArrayList<>();
private ArrayList<String> permissions = new ArrayList<>();
// integer for permissions results request
private static final int ALL_PERMISSIONS_RESULT = 1011;


@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.content_hotkey_navigation);
    locationTv = findViewById(R.id.location);
    // we add permissions we need to request location of the users
    permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
    permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);

    permissionsToRequest = permissionsToRequest(permissions);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) 
        if (permissionsToRequest.size() > 0) 
            requestPermissions(permissionsToRequest.toArray(
                    new String[0]), ALL_PERMISSIONS_RESULT);
        
    

    // we build google api client
    googleApiClient = new GoogleApiClient.Builder(this).
            addApi(LocationServices.API).
            addConnectionCallbacks(this).
            addOnConnectionFailedListener(this).build();


private ArrayList<String> permissionsToRequest(ArrayList<String> wantedPermissions) 
    ArrayList<String> result = new ArrayList<>();

    for (String perm : wantedPermissions) 
        if (!hasPermission(perm)) 
            result.add(perm);
        
    

    return result;


private boolean hasPermission(String permission) 
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) 
        return checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED;
    

    return true;


@Override
protected void onStart() 
    super.onStart();

    if (googleApiClient != null) 
        googleApiClient.connect();
    


@Override
protected void onResume() 
    super.onResume();

    if (!checkPlayServices()) 
        locationTv.setText("You need to install Google Play Services to use the App properly");
    


@Override
protected void onPause() 
    super.onPause();

    // stop location updates
    if (googleApiClient != null  &&  googleApiClient.isConnected()) 
        LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
        googleApiClient.disconnect();
    


private boolean checkPlayServices() 
    GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
    int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);

    if (resultCode != ConnectionResult.SUCCESS) 
        if (apiAvailability.isUserResolvableError(resultCode)) 
            apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST);
         else 
            finish();
        

        return false;
    

    return true;


@Override
public void onConnected(@Nullable Bundle bundle) 
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            &&  ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) 
        return;
    

    // Permissions ok, we get last location
    location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);

    if (location != null) 
        locationTv.setText("Latitude : " + location.getLatitude() + "\nLongitude : " + location.getLongitude());
    

    startLocationUpdates();


private void startLocationUpdates() 
    locationRequest = new LocationRequest();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setInterval(UPDATE_INTERVAL);
    locationRequest.setFastestInterval(FASTEST_INTERVAL);

    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            &&  ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) 
        Toast.makeText(this, "You need to enable permissions to display location !", Toast.LENGTH_SHORT).show();
    

    LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);


@Override
public void onConnectionSuspended(int i) 


@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) 


@Override
public void onLocationChanged(Location location) 
    if (location != null) 
        locationTv.setText("Latitude : " + location.getLatitude() + "\nLongitude : " + location.getLongitude());
    


@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) 
    switch(requestCode) 
        case ALL_PERMISSIONS_RESULT:
            for (String perm : permissionsToRequest) 
                if (!hasPermission(perm)) 
                    permissionsRejected.add(perm);
                
            

            if (permissionsRejected.size() > 0) 
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) 
                    if (shouldShowRequestPermissionRationale(permissionsRejected.get(0))) 
                        new AlertDialog.Builder(GpsLocation.this).
                                setMessage("These permissions are mandatory to get your location. You need to allow them.").
                                setPositiveButton("OK", new DialogInterface.OnClickListener() 
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) 
                                        requestPermissions(permissionsRejected.
                                                toArray(new String[0]), ALL_PERMISSIONS_RESULT);
                                    
                                ).setNegativeButton("Cancel", null).create().show();

                        return;
                    
                
             else 
                if (googleApiClient != null) 
                    googleApiClient.connect();
                
            

            break;
    

我需要得到它的gps坐标并将其发送到MainActivity类。所以请帮助我。任何帮助都会非常感激。

答案

如果你想要一个普通的课程,你为什么要扩展AppCompat呢?创建一个普通类并在您的活动中实例化它。你在这堂课中究竟想做什么,它不能成为你活动中的一种方法?

我可以通过调用在任何地方创建融合的Location Client

 fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

以上是关于如何在MainActivity类中调用非活动类?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 MainActivity 之外的另一个类中调用 findViewById(R.id.textView)?

如何通过线程更新非 MainActivity 活动?

如何在活动形式非活动类中调用方法

如何从扩展 JobService 的类中调用将视图作为参数的 MainActivity 方法?

android其他类怎么调用继承自activity的类(mainactivity)中的非静态方法?

Android 中如何在java类中调用activity 中的一个方法?