【问题标题】:Call MainActivity function outside the class在类外调用 MainActivity 函数
【发布时间】:2014-12-05 22:02:10
【问题描述】:

我尝试在 MainActivity 之外展示广告。如果我在这个类中调用 showAd,它会很好地显示我的广告,但是当我通过实现的接口在我的游戏类中调用这个函数时,我有一个错误: “需要主线程”

MMRequest request = new MMRequest(); ;  
    MMInterstitial interstitial;
  @Override
  public void onCreate(Bundle savedInstanceState) 
  {
        super.onCreate(savedInstanceState);   
        MMSDK.initialize(this);  
        interstitial = new MMInterstitial(this);               
        interstitial.setMMRequest(request);
        interstitial.setApid("xxxxxx");  

        AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration();    

        RelativeLayout layout = new RelativeLayout(this);

        View gameView = initializeForView(new JumpJackieJump(new RequestHandler(), this), cfg);
        layout.addView(gameView);           

        setContentView(layout);  }

@Override
public void showAd() 
{   
    interstitial.fetch();
    interstitial.setListener(new RequestListenerImpl() 
    {   
        @Override
        public void requestCompleted(MMAd mmAd) 
        {
            interstitial.display();             
        }           
});

【问题讨论】:

  • 请发布更完整的代码。从上面的sn-p看不清楚。

标签: java android call


【解决方案1】:

这是因为主线程 UI 线程。 (请记住,这仅适用于 android - 如需更多参考,请参阅 this)。

根据 Android 文档,您应该 avoid updating the UI outside the UI thread

Additionally, the Andoid UI toolkit is not thread-safe. So, you must not manipulate your UI from a worker thread—you must do all manipulation to your user interface from the UI thread.

话虽如此,您也许可以使用 this 之类的东西来做您想做的事情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-05
    • 1970-01-01
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    • 2012-08-02
    相关资源
    最近更新 更多