簡體   English   中英

"如何在我的自定義非活動類中使用 findViewById for android 應用程序?"

[英]How can I use findViewById inside my Custom Non-Actitvity Class for android application?

在這里,我的活動類名稱是MapsActivity ,我的自定義非活動類名稱是GeoFenceBroadCastReceiver 我在 actitvity_maps.xml 文件中有一個SwitchCompact開關,我可以通過 findViewById 從 MapsActivity.java 訪問它但是當我想從 GeoFenceBroadCastReceiver 訪問它時,我的應用程序出現錯誤。 現在我的問題是我可以使用 findViewById 從 GeoFenceBroadCastReceiver 訪問我的 SwitchCompact 開關嗎?

SwitchCompact 開關代碼--

<androidx.appcompat.widget.SwitchCompat
    android:id="@+id/vibrationSwitchId"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"
    android:layout_gravity="right"
    android:layout_marginRight="20dp"
    android:fontFamily="@font/lato_bold"
    android:scaleX="1.6"
    android:scaleY="1.6"
    android:textAllCaps="true"
    android:textOff="@string/text_off"
    android:textOn="@string/text_on"
    android:thumb="@drawable/thumb"
    app:showText="true"
    app:switchTextAppearance="@style/switch_style"
    app:thumbTint="#FFC107"
    app:track="@drawable/track"
    app:trackTint="#E6D7D7" />
</RelativeLayout>

開關量輸出開關緊湊型

地圖活動代碼

package com.example.akash.mapsdemo;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.SwitchCompat;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;

import android.Manifest;

import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;

import android.location.Location;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;

import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.GeofencingClient;
import com.google.android.gms.location.GeofencingRequest;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;


public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener,  GoogleMap.OnMapLongClickListener{


private static final String TAG = "MapsActivity";

    private GeoFenceHelper geoFenceHelper;
    private GeofencingClient geofencingClient;

    private static final int BACKGROUND_LOCATION_ACCESS_REQUEST_CODE = 1002;

    private GoogleMap mMap;
    private GoogleApiClient client;
    private LocationRequest locationRequest;
    private Location lastLocation;
    private Marker currentLocationMarker;
    public static final int REQUEST_LOCATION_CODE = 99;
    int PROXIMITY_RADIUS = 10000;
    double latitude,longitude;

    private int FINE_LOCATION_ACCESS_REQUEST_CODE = 10001;

    private float GEOFENCE_RADIUS = 100;
    private String GEOFENCE_ID = "SOME_GEOFENCE_ID";


    void SwitchToast(SwitchCompat btnID, String textON, String textOFF, String modeName){
        btnID.setOnCheckedChangeListener((buttonView, isChecked) -> {
            AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
//            AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

            if (isChecked){
                if(modeName.equals("isVibration") ){
                    audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
                    Toast.makeText(MapsActivity.this, textON, Toast.LENGTH_SHORT).show();
                }
                if (modeName.equals("isAlarm")){
                    audioManager.setRingerMode(AudioManager.STREAM_ALARM);
                    Toast.makeText(MapsActivity.this, textON, Toast.LENGTH_SHORT).show();
                }
            }
            else{
                if(modeName.equals("isVibration") ){
                    audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
                    Toast.makeText(MapsActivity.this, textOFF, Toast.LENGTH_SHORT).show();
                }
                if (modeName.equals("isAlarm")){
                    audioManager.setRingerMode(AudioManager.STREAM_ALARM);
                    Toast.makeText(MapsActivity.this, textOFF, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

        geofencingClient = LocationServices.getGeofencingClient(this);
        geoFenceHelper = new GeoFenceHelper(this);


        SwitchCompat vibrationSwitchID = findViewById(R.id.vibrationSwitchId);
        SwitchCompat alarmSwitchID = findViewById(R.id.alarmSwitchId);

        SwitchToast(vibrationSwitchID, "Vibration ON", "Vibration OFF", "isVibration");
        SwitchToast(alarmSwitchID, "Alarm ON", "Alarm OFF", "isAlarm");


        NotificationManager systemService = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        if((Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) && !systemService.isNotificationPolicyAccessGranted()){
            startActivity(new Intent(Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS));
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        {
            checkLocationPermission();

        }
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);

        mapFragment.getMapAsync(this);


    }



    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == FINE_LOCATION_ACCESS_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //Now we have the permission
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                    return;
                }
                mMap.setMyLocationEnabled(true);
            } else {
                Toast.makeText(this, "We need location permission to run this app", Toast.LENGTH_LONG).show();
            }
        }
        if (requestCode == BACKGROUND_LOCATION_ACCESS_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //Now we have the permission
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                    return;
                }
                Toast.makeText(this, "You can add geofences..", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this, "Background location access is necessary for run this application", Toast.LENGTH_LONG).show();
            }
        }
    }



    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);
        }

        LatLng DIU = new LatLng(-34, 151);

        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(DIU, 16));

        enableUserLocation();

        mMap.setOnMapLongClickListener(this);
    }


    public void enableUserLocation() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            mMap.setMyLocationEnabled(true);
        } else {
            //ask for permission
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, FINE_LOCATION_ACCESS_REQUEST_CODE);
        }
    }


    @Override
    public void onMapLongClick(@NonNull LatLng latLng) {

        if (Build.VERSION.SDK_INT >= 29){
            //We need the background permission
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_BACKGROUND_LOCATION) == PackageManager.PERMISSION_GRANTED){
                tryAddingGeofence(latLng);
            }else{
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_BACKGROUND_LOCATION}, BACKGROUND_LOCATION_ACCESS_REQUEST_CODE);
            }
        }else{
            tryAddingGeofence(latLng);
        }
    }


    private void tryAddingGeofence(LatLng latLng){
        mMap.clear();
        addMarker(latLng);
        addCircle(latLng, GEOFENCE_RADIUS);
        addGeofence(latLng, GEOFENCE_RADIUS);
    }

    private void addGeofence(LatLng latLng, float radius) {
        Geofence geofence = geoFenceHelper.getGeoFence(GEOFENCE_ID, latLng, radius, Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_DWELL | Geofence.GEOFENCE_TRANSITION_EXIT);
        GeofencingRequest geofencingRequest = geoFenceHelper.getGeoFencingRequest(geofence);
        PendingIntent pendingIntent = geoFenceHelper.getPendingIntent();

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        geofencingClient.addGeofences(geofencingRequest, pendingIntent)
                .addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void unused) {
                        Log.d(TAG, "onSuccess: GeoFence Added....");
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        String errorMessage = geoFenceHelper.getErrorString(e);
                        Log.d(TAG, "onFailure: "+ errorMessage);
                    }
                });
    }

    private void addMarker(LatLng latLng){
        MarkerOptions markerOptions = new MarkerOptions().position(latLng);
        mMap.addMarker(markerOptions);
    }

    private void addCircle(LatLng latLng, float radius){
        CircleOptions circleOptions = new CircleOptions();
        circleOptions.center(latLng);
        circleOptions.radius(radius);
        circleOptions.strokeColor(Color.argb(255, 255, 0, 0));
        circleOptions.fillColor(Color.argb(64, 255, 0, 0));
        circleOptions.strokeWidth(4);
        mMap.addCircle(circleOptions);
    }


    protected synchronized void buildGoogleApiClient() {
        client = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
        client.connect();

    }

    @Override
    public void onLocationChanged(Location location) {

        latitude = location.getLatitude();
        longitude = location.getLongitude();
        lastLocation = location;

        if(currentLocationMarker != null)
        {
            currentLocationMarker.remove();

        }
        Log.d("lat = ",""+latitude);
        LatLng latLng = new LatLng(location.getLatitude() , location.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);

        markerOptions.title("Current Location");
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
        currentLocationMarker = mMap.addMarker(markerOptions);
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.animateCamera(CameraUpdateFactory.zoomBy(10));

        if(client != null)
        {
            LocationServices.FusedLocationApi.removeLocationUpdates(client,this);
        }
    }

    public void onClick(View v)
    {
        Object dataTransfer[] = new Object[2];
        GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();

        LinearLayout settingViewId = findViewById(R.id.settingViewID);
        FrameLayout locationViewId = findViewById(R.id.locationViewID);
        FrameLayout mosqueViewId = findViewById(R.id.mosqueViewID);
        LinearLayout prayerTimeViewId = findViewById(R.id.prayerTimeViewID);


        switch(v.getId())
        {
            case R.id.settingsID:

                locationViewId.setVisibility(v.GONE);
                mosqueViewId.setVisibility(v.GONE);
                prayerTimeViewId.setVisibility(v.GONE);
                settingViewId.setVisibility(v.VISIBLE);

                Toast.makeText(MapsActivity.this, "Showing Nearby Hospitals", Toast.LENGTH_SHORT).show();
                break;

            case R.id.locationID:

                locationViewId.setVisibility(v.VISIBLE);
                mosqueViewId.setVisibility(v.GONE);
                prayerTimeViewId.setVisibility(v.GONE);
                settingViewId.setVisibility(v.GONE);

                Toast.makeText(MapsActivity.this, "Showing Nearby Schools", Toast.LENGTH_SHORT).show();
                break;
            case R.id.mosqueID:

                locationViewId.setVisibility(v.GONE);
                mosqueViewId.setVisibility(v.VISIBLE);
                prayerTimeViewId.setVisibility(v.GONE);
                settingViewId.setVisibility(v.GONE);

                mMap.clear();
                String mosque = "mosque";
                String url = getUrl(latitude, longitude, mosque);
                dataTransfer[0] = mMap;
                dataTransfer[1] = url;

                getNearbyPlacesData.execute(dataTransfer);


                Toast.makeText(MapsActivity.this, "Showing Nearby Mosque", Toast.LENGTH_SHORT).show();
                break;

            case R.id.prayerTimeID:

                locationViewId.setVisibility(v.GONE);
                mosqueViewId.setVisibility(v.GONE);
                prayerTimeViewId.setVisibility(v.VISIBLE);
                settingViewId.setVisibility(v.GONE);

                Toast.makeText(MapsActivity.this, "Showing Nearby Restaurants", Toast.LENGTH_SHORT).show();
                break;
        }
    }


    private String getUrl(double latitude , double longitude , String nearbyPlace)
    {

        StringBuilder googlePlaceUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
        googlePlaceUrl.append("location="+latitude+","+longitude);
        googlePlaceUrl.append("&radius="+PROXIMITY_RADIUS);
        googlePlaceUrl.append("&type="+nearbyPlace);
        googlePlaceUrl.append("&sensor=true");
        googlePlaceUrl.append("&key="+getString(R.string.google_maps_key));

        Log.d("MapsActivity", "url = "+googlePlaceUrl.toString());

        return googlePlaceUrl.toString();
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {

        locationRequest = new LocationRequest();
        locationRequest.setInterval(100);
        locationRequest.setFastestInterval(1000);
        locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);


        if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION ) == PackageManager.PERMISSION_GRANTED)
        {
            LocationServices.FusedLocationApi.requestLocationUpdates(client, locationRequest, this);
        }
    }


    public boolean checkLocationPermission()
    {
        if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)  != PackageManager.PERMISSION_GRANTED )
        {

            ActivityCompat.requestPermissions(this,new String[] {Manifest.permission.ACCESS_FINE_LOCATION },REQUEST_LOCATION_CODE);
            return false;

        }
        else
            return true;
    }


    @Override
    public void onConnectionSuspended(int i) {
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    }
}

GeoFenceBroadCast 接收器代碼

package com.example.akash.mapsdemo;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

import androidx.appcompat.widget.SwitchCompat;

import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.GeofencingEvent;

import java.util.List;

public class GeoFenceBroadCastReceiver extends BroadcastReceiver {

    private static final String TAG = "GeoFenceBroadCastReceiv";

//    public Activity mapsActivity;
//    public GeoFenceBroadCastReceiver(MapsActivity _mapsActivity) {
//        this.mapsActivity = _mapsActivity;
//        SwitchCompat btnID = this.mapsActivity.findViewById ( R.id.vibrationSwitchId );
//    }


    @Override
    public void onReceive(Context context, Intent intent) {
//        Toast.makeText(context, "Geofence Trigger", Toast.LENGTH_LONG).show();


        NotificationHelper notificationHelper = new NotificationHelper(context);

        GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
        
        if(geofencingEvent.hasError()){
            Log.d(TAG, "onReceiver: Error receiving geofence event");
            return;
        }

        List<Geofence> geofenceList = geofencingEvent.getTriggeringGeofences();
//
        for (Geofence geofence: geofenceList){
            Log.d(TAG, "onReceive: "+ geofence.getRequestId());
        }
//        Location location = geofencingEvent.getTriggeringLocation();

        int transitionType = geofencingEvent.getGeofenceTransition();

        switch (transitionType){
            case Geofence.GEOFENCE_TRANSITION_ENTER:
                Toast.makeText(context, "GEOFENCE_TRANSITION_ENTER", Toast.LENGTH_SHORT).show();
                notificationHelper.sendHighPriorityNotification("GEOFENCE_TRANSITION_ENTER", "", MapsActivity.class);

                break;
            case Geofence.GEOFENCE_TRANSITION_DWELL:
                Toast.makeText(context, "GEOFENCE_TRANSITION_DWELL", Toast.LENGTH_SHORT).show();
                notificationHelper.sendHighPriorityNotification("GEOFENCE_TRANSITION_DWELL", "", MapsActivity.class);
                break;
            case Geofence.GEOFENCE_TRANSITION_EXIT:
                Toast.makeText(context, "GEOFENCE_TRANSITION_EXIT", Toast.LENGTH_SHORT).show();
                notificationHelper.sendHighPriorityNotification("GEOFENCE_TRANSITION_EXIT", "", MapsActivity.class);
                break;
        }

    }
}

你不想那樣做。 BroadcastReceiver 是一個單獨的上下文。 沒有任何活動在它關閉時存在的承諾。 相反,您應該將開關的狀態存儲在廣播接收器也可以看到的某個位置。 執行此操作的標准方法是在 SharedPreferences 中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM