gpt4 book ai didi

java - 当当前位置位于地理围栏区域时应用程序崩溃

转载 作者:太空宇宙 更新时间:2023-11-04 10:09:55 25 4
gpt4 key购买 nike

我创建了一个应用程序来检测用户是否位于地理围栏区域。但问题是,当我进入地理围栏区域时,应用程序会关闭。

这是MainActivity.class中的代码

public class MainActivity extends AppCompatActivity {

public static final String GEOFENCE_ID = "MyGeofenceId";
public static double lat = 1; //just some random coordinates
public static double lng = 1; //just some random coordinates
GoogleApiClient googleApiClient = null;
private Button startLoc, startGeo, stopGeo;
private TextView txtPrint;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

startLoc = (Button) findViewById(R.id.startloc);
startGeo = (Button) findViewById(R.id.startgeo);
stopGeo = (Button) findViewById(R.id.stopgeo);
txtPrint = (TextView) findViewById(R.id.txtPrint);

googleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
@Override
public void onConnected(@Nullable Bundle bundle) {
txtPrint.append("Connected to GoogleApiClient");
}

@Override
public void onConnectionSuspended(int i) {
txtPrint.append("Suspended connection to GoogleApiClient");
}
})
.addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
txtPrint.append("Failed to connect to GoogleApiClient" + connectionResult.getErrorMessage());
}
})
.build();

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[] {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1234);
}
}

public void setTextPrint(String text){
txtPrint.setText(text);
}

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

int response = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this);
if(response != ConnectionResult.SUCCESS){
txtPrint.append("Google Play Services not available - show dialog to ask user to download it");
GoogleApiAvailability.getInstance().getErrorDialog(this, response, 1).show();
}else{
txtPrint.append("Google Play Services is available - no action required");
}
}

public void startLocationMonitoring(View view) {
setTextPrint("startLoc");
try{
LocationRequest locationRequest = LocationRequest.create()
.setInterval(10000)
.setFastestInterval(5000)
// .setNumUpdates(5)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, new LocationListener() {
@Override
public void onLocationChanged(Location location) {
txtPrint.append("Location update lat/long " + location.getLatitude() + " " + location.getLongitude());
}
});
}catch (SecurityException e){
txtPrint.append("Security Exception - " + e.getMessage());
}
}

public void startGeofenceMonitoring(View view) {
txtPrint.append("startGeo");

try{
Geofence geofence = new Geofence.Builder()
.setRequestId(GEOFENCE_ID)
.setCircularRegion(lat, lng, 200)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.setNotificationResponsiveness(1000)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT)
.build();

GeofencingRequest geofencingRequest = new GeofencingRequest.Builder()
.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER)
.addGeofence(geofence).build();

Intent intent = new Intent(this, GeofenceService.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

if(!googleApiClient.isConnected()){
txtPrint.append("GoogleApiClient is not connected");
}else{
LocationServices.GeofencingApi.addGeofences(googleApiClient, geofencingRequest, pendingIntent)
.setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(@NonNull Status status) {
if(status.isSuccess()){
txtPrint.append("Successfully added geofence");
}else{
txtPrint.append("Failed to add geofence - " + status.getStatus());
}
}
});
}
}catch (SecurityException e){
txtPrint.append("Security Exception - " + e.getMessage());
}
}

public void stopGeofenceMonitoring(View view) {
txtPrint.append("stopGeo");
ArrayList<String> geofenceIds = new ArrayList<String>();
geofenceIds.add(GEOFENCE_ID);
LocationServices.GeofencingApi.removeGeofences(googleApiClient, geofenceIds);
}

@Override
protected void onStart() {
super.onStart();
googleApiClient.reconnect();
}

@Override
protected void onStop() {
super.onStop();
googleApiClient.disconnect();
}
}

包含 Intent 处理程序的另一个类。 GeofenceService.class

public class GeofenceService extends IntentService {

public GeofenceService() {
super("GeofenceService");
}

@Override
protected void onHandleIntent(@Nullable Intent intent) {
MainActivity mainActivity = new MainActivity();
mainActivity.setTextPrint("HANDLED INTENT");
GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
if(geofencingEvent.hasError()){
// handle error
}else{

int transition = geofencingEvent.getGeofenceTransition();
List<Geofence> geofences = geofencingEvent.getTriggeringGeofences();
Geofence geofence = geofences.get(0);
String requestId = geofence.getRequestId();

if(transition == Geofence.GEOFENCE_TRANSITION_ENTER){
mainActivity.setTextPrint("Entered Geofence");
}else if(transition == Geofence.GEOFENCE_TRANSITION_EXIT){
mainActivity.setTextPrint("Exited Geofence");
}
}
}
}

我还将 GeofenceService 类放入 Android Manifest 中

<service android:name=".GeofenceService" android:exported="true" 
android:enabled="true"></service>

在 xml 文件中有 3 个按钮可以触发开始位置监控开始地理围栏监控并且停止地理围栏监控

位置正在更新,我可以添加和删除地理围栏。但当当前位置位于地理围栏区域时,应用程序将关闭。

最佳答案

MainActivity mainActivity = new MainActivity();

这是错误的。您无法创建这样的 Activity 。此外,您不应该直接从 IntentService 进行 UI 更改。什么app打不开?然后就没有任何 Activity 了。

您应该做的是,当当前位置位于地理围栏区域时,创建一个 Notification 。当用户单击通知时,通过在 Intent 中传递“HANDLED INTENT”字符串来打开您的 Activity ,然后将此字符串设置为txtPrint。

关于java - 当当前位置位于地理围栏区域时应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52475296/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com