I have an Android application and I'm playing around with the LocationManager, right now just trying to get some basic functionality going. The problem is that when I send it a Location event, either through DDMS (Eclipse) or by telnet-ing to the emulator and using "geo", I'm not getting any response. I have my code below, can anyone please help me figure out what I'm doing wrong? Thanks.
public class HelloLocation extends Activity {
Toast mToast;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intent = new Intent(HelloLocation.this, HelloLocationReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(HelloLocation.this, 0, intent, 0);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.addProximityAlert(40.000, -74.000, 2500, -1, sender);
开发者_运维技巧 if(mToast != null) {
mToast.cancel();
}
mToast = Toast.makeText(HelloLocation.this, "Alarm set", Toast.LENGTH_LONG);
mToast.show();
}
}
and my class that's supposed to respond to the Location event:
public class HelloLocationReceiver extends BroadcastReceiver {
@Override public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm set off", Toast.LENGTH_LONG).show();
}
}
You need to register a receiver and define an intent filter, try this:
public class HelloLocation extends Activity {
Toast mToast;
// ADD LINE BELOW
private static final String PROXIMITY_ALERT_INTENT = "AnythingYouLike";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// DELETE LINE BELOW
//Intent intent = new Intent(HelloLocation.this, HelloLocationReceiver.class);
// REPLACE WITH LINE BELOW
Intent intent = new Intent(PROXIMITY_ALERT_INTENT);
PendingIntent sender = PendingIntent.getBroadcast(HelloLocation.this, 0, intent, 0);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.addProximityAlert(40.000, -74.000, 2500, -1, sender);
// ADD TWO LINES BELOW
IntentFilter filter = new IntentFilter(PROXIMITY_ALERT_INTENT);
registerReceiver(new HelloLocationReceiver(), filter);
// ------------------------
if(mToast != null) {
mToast.cancel();
}
mToast = Toast.makeText(HelloLocation.this, "Alarm set", Toast.LENGTH_LONG);
mToast.show();
}
}
It works for me.
精彩评论