2011-01-31 74 views
0

我有一个Android应用程序,我正在玩LocationManager,现在只是试图获得一些基本的功能。问题是,当我通过DDMS(Eclipse)或通过远程登录到模拟器并使用“geo”发送Location事件时,我没有收到任何响应。我有我的代码在下面,任何人都可以请帮我弄清楚我做错了什么?谢谢。为什么我的Android应用不会响应位置事件?

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(); 
    } 
} 

和我的类是应该的位置响应事件:

public class HelloLocationReceiver extends BroadcastReceiver { 

    @Override public void onReceive(Context context, Intent intent) { 
     Toast.makeText(context, "Alarm set off", Toast.LENGTH_LONG).show(); 
    } 
} 

回答

3

您需要注册一个接收器和定义一个意图过滤器,试试这个:

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(); 
    } 

} 

它的工作原理为了我。

+0

非常感谢......只是为了澄清一下,PROXIMITY_ALERT_INTENT字段就是存在意图的标识符,对吧? – jay 2011-02-01 13:56:00

相关问题