2011-01-31 62 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

相關問題