我正在尝试设置最基本的接近警报,但似乎没有任何反应。我对 Android 编程相当陌生,所以请让我知道我做错了什么或者我错过了什么。我从这里的一些源代码和这个源代码中得到启发。这是我的代码:
package com.example.proximityalert;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
public class MainActivity extends Activity {
private static final String PROX_ALERT_INTENT = "com.example.proximityalert";
private IntentReceiver locationReminderReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(PROX_ALERT_INTENT);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationManager.addProximityAlert(55.586301,13.045417, 200, -1, pendingIntent);
this.locationReminderReceiver = new IntentReceiver();
final IntentFilter filter = new IntentFilter(PROX_ALERT_INTENT);
this.registerReceiver(this.locationReminderReceiver, filter);
}
}
和接收方
package com.example.proximityalert;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.util.Log;
import android.widget.Toast;
public class IntentReceiver extends BroadcastReceiver{
// @SuppressWarnings("deprecation")
@Override
public void onReceive(Context context, Intent intent) {
String key = LocationManager.KEY_PROXIMITY_ENTERING;
Boolean entering = intent.getBooleanExtra(key, false);
if (entering) {
Toast.makeText(context, "LocationReminderReceiver entering", Toast.LENGTH_SHORT).show();
Log.i("LocationReminderReceiver", "entering");
} else {
Toast.makeText(context, "LocationReminderReceiver exiting", Toast.LENGTH_SHORT).show();
Log.i("LocationReminderReceiver", "exiting");
}
}
}