簡體   English   中英

接口對象在廣播 onReceive 方法中具有空值

[英]Interface Object has null value in Broadcast onReceive method

我做了一個接口來從廣播接收器獲取觸發器,但它總是說接口對象具有空值!

這是定義接口的廣播接收器類的代碼:

public class GeofenceBroadcastReceiver extends BroadcastReceiver {

public interface ResultListener {
    public void SomeWorkToDo();
}

private ResultListener resultListener;

public void setter(ResultListener listener){
    Log.i("setter","working");
     this.resultListener=listener;
}

@Override
public void onReceive(Context context, Intent intent) {
    GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
    if (geofencingEvent.hasError()) {
        Toast.makeText(context, "error", Toast.LENGTH_SHORT).show();
        return;
    }

    int geofenceTransition = geofencingEvent.getGeofenceTransition();
    if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_DWELL) {
        Log.i("Geo Fencing broadcast","Running");
        Toast.makeText(context, "You Are Arrived!!!", Toast.LENGTH_SHORT).show();
        resultListener.SomeWorkToDo();
    }else {
        Toast.makeText(context, "something went wrong", Toast.LENGTH_SHORT).show();
    }
}

這是清單文件的代碼:

<receiver android:name=".GeoFencing.GeofenceBroadcastReceiver" />

此代碼在 MainActivity 中使用:

GeofenceBroadcastReceiver geofenceBroadcastReceiver=new GeofenceBroadcastReceiver();
    geofenceBroadcastReceiver.setter(new GeofenceBroadcastReceiver.ResultListener() {
        @Override
        public void SomeWorkToDo() {
            Log.i("our interface","working");
            startActivity(new Intent(ViewPlace.this,ViewDirections.class));
            finishAffinity();
        }
    });

您正在清單中注冊接收器。 您的new GeofenceBroadcastReceiver()不會被使用。 當收到該接收器的廣播時,Android 將創建自己的GeofenceBroadcastReceiver實例。 因此,回調將為null ,因為您的 setter 沒有被調用。

對於您要解決的任何問題,使用系統廣播很可能是錯誤的解決方案。 如果您確信系統廣播是正確的答案,並且您希望在清單中注冊接收器,則GeofenceBroadcastReceiver需要能夠自己完成所有工作,而無需來自其他對象的任何類型的回調。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM