2

我的問題很簡單:我有一個BroadcastReceiver實現LocationListenerLocationListener需要通常未實現的方法,那些在BroadcastReceiveronReceive之外,所以我沒有使用的上下文。事情是在onLocationChanged方法(其中一個LocationListener未實現的)之一,我必須調用一個方法必須使用上下文,我不知道如何得到它。BroadcastReceiver實現LocationListener:如何獲取onLocationChanged中的上下文

public class MyBroadcastReceiver extends BroadcastReceiver implements LocationListener { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
    } 

    public void onLocationChanged(Location location) { 
     method(context); 
    } 

    public void onStatusChanged(String s, int i, Bundle b) {   
    } 

    public void onProviderDisabled(String s) { 
    } 

    public void onProviderEnabled(String s) {   
    } 
} 

我該如何做到這一點?

回答

1

您可以像下面那樣聲明一個類級別的Context,然後使用它。

公共類MyBroadcastReceiver擴展廣播接收器實現LocationListener的 {

private Context context; 
@Override 
public void onReceive(Context context, Intent intent) { 
this.conext = context; 
} 

public void onLocationChanged(Location location) { 
    method(context);  // Now you can use context 
} 
public void onStatusChanged(String s, int i, Bundle b) {   
} 
public void onProviderDisabled(String s) { 
} 
public void onProviderEnabled(String s) {   
} 
+0

的確如此。但是它真的使用了正確的上下文嗎?它只是給了我沒有錯誤,因爲我已經用「私有上下文上下文」聲明瞭該變量,甚至可能是空的。我的意思是,自從接受它只在廣播被觸發時才被調用,而不是在我從該類外部實例化類的時候,你確定方法(上下文)將獲得在onReceive方法中傳遞的上下文,而不是僅僅獲得一個空方法通過聲明「私人上下文」? – user2911015

2

我有一個實現LocationListener的一個BroadcastReceiver。

如果BroadcastReceiver通過清單登記,讓它成爲一個LocationListener是毫無意義的,因爲你的過程後onReceive()回報終止毫秒。

我要調用必須使用情境的方法,我不知道如何得到它

如果使用registerReceiver()設置此BroadcastReceiver,以及由於某種原因,這是有道理的對於你也有它是一個LocationListener,你的Context是所謂的registerReceiver()ActivityService)。

+0

我在這個廣播接收器中有很多方法,是的,我通過清單註冊了它。當onReceive被觸發時,只要進行onReceive內部的操作,就必須立即終止進程。這很好。在該方法的一個我有requestLocationUpdates,這就是爲什麼我需要的LocationListener的和上下文(我需要因爲\t \t的LocationManager的LocationManager =(的LocationManager)context.getSystemService(Context.LOCATION_SERVICE)範圍內; ) – user2911015

+0

@ user2911015:「當onReceive被觸發時,只要它執行了onReceive內部的任務,就必須立即終止進程。所以這很好「 - 然後在調用requestLocationUpdates()時沒有任何意義。 – CommonsWare

相關問題