【问题标题】:Android: Service value to a BroacastReceiverAndroid:BroadcastReceiver 的服务值
【发布时间】:2013-07-17 16:24:26
【问题描述】:

我是一名初学者,并且已经阅读过有关服务和广播接收器组件的文章。 还是我现在真的不知道,在这里做什么。 我有一个总是更改变量 k 的服务(类:ExampleService):

@覆盖 protected void onHandleIntent(Intent intent) {

while (k < 1000) {

    if(forward==true){
        k++;
    }else{
    k--;    
    }


    synchronized (this) {

        try {

            wait(100);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

k = 0;
this.stopSelf();

}

public long getInt(){
    return k;
}

还有我的广播接收器:

BroadcastReceiver broadi=new BroadcastReceiver(){

@Override
public void onReceive(Context arg0, Intent arg1) {
    // TODO Auto-generated method stub
    ExampleIntentService se=new ExampleIntentService();

            text.setText("Count:"+String.valueOf(se.getInt()));
}

};

所以我创建了一个服务对象并尝试使用我的“getInt()”方法获取该值。 它总是返回 0,我不知道为什么。 有什么建议吗?

【问题讨论】:

    标签: android service broadcastreceiver broadcast


    【解决方案1】:

    当你打电话时

    ExampleIntentService se=new ExampleIntentService();
    

    您正在创建该类的新实例,您不是指正在运行的服务实例。我认为你有 2 次机会:

    • k 及其getter 方法设为静态。使其成为静态 k 不会成为实例相关的,您可以通过调用来读取它的值

      ExampleIntentService.getInt();

    • 发送一个可以被你的广播接收器接收的广播,每次你改变k,但我认为你可以在 100 秒内每秒发送 10 个广播的那一刻做很多工作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-16
      • 1970-01-01
      • 2017-03-05
      • 1970-01-01
      • 2011-05-22
      • 2015-11-25
      • 1970-01-01
      • 2011-04-12
      相关资源
      最近更新 更多