2012-06-12 50 views
1


我有一個BroadcastReceiver的服務。
如何從BroadcastReceiveronReceive函數調用服務類中的函數?
如果我不能,我該怎麼辦?
下面是一些代碼:BroadcastReceiver onReceive函數中的調用類函數

public class MyService extends Service { 
    private BroadcastReceiver broadcastReceiver; 

    @Override 
    public IBinder onBind(Intent arg0) { 
     return null; 
    } 

    @Override 
    public void onCreate() { 
     broadcastReceiver = new BroadcastReceiver() { 
      @Override 
      public void onReceive(Context context, Intent intent) { 
       ... // How to call myFunction() here? 
      } 
     }; 
     ... // intentFilter, registerReceiver, etc... 
    } 

    private void myFunction() { 
     ... // do something 
    } 
} 

回答

1

你可以這樣調用:

broadcastReceiver = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      myFunction(); 
     } 
    }; 

或者,如果myFunction具有相同的名稱爲BroadcastReceiver方法,你可以顯式調用外部類的方法是這樣:

broadcastReceiver = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      MyService.this.myFunction(); 
     } 
    }; 
+0

我寫錯了函數名,所以IDE沒有找到函數,我認爲他們是一些特殊的事情。謝謝 – Snote

+0

不客氣! – tibtof