发送器循环快速时广播接收器多次呼叫?

时间:2016-02-04 11:28:33

标签: android broadcastreceiver

在我的应用程序中,我有一个广播接收器的活动,它接收来自服务的消息。该服务包含一个循环。在循环中,如果存在,它可以决定从存储器下载数据或读取数据。当从互联网下载数据时(每个循环周期大约需要1秒),广播接收机运行良好。但是当从存储器读取数据时(5个循环周期可能在几毫秒内发生),当最后一个循环周期结束时,广播接收器被调用5次!任何解决方案或解决方法?

以下是我的服务示意图:

 MyService extends Service{

 void foo(){
     for (int i = 0 ; i < 5 ; i++)
         if (file.exists()){
            myArrayList = readFile(fileName);
            System.out.println("cycle done " + (i+1));
            myIntent.putExtra("loop number" , (i+1));
            sendBroadcast(myIntent);                
         } else {
            myArrayList = downloadData(myUrl);
            System.out.println("cycle done " + (i+1));
            myIntent.putExtra("loop number" , (i+1));
            sendBroadcast(myIntent);
         }
 }
 }

广播接收器的原理图:

MyActivity extends Activity {
//some code here
private BroadcastReceiver myBr = new BroadcastReceiver() {
      @Override
      public void onReceive(Context context, Intent intent) {
           System.out.println("myBr called " + intent.getExtra("loop number"));                                        
      }
};    

以下是所有循环周期从互联网获取数据时的示例日志:

cycle done 1
myBr is called 1
cycle done 2
myBr is called 2
cycle done 3
myBr is called 3
cycle done 4
myBr is called 4
cycle done 5
myBr is called 5
...

最后是所有循环周期从存储中获取数据的示例日志:

cycle done 1
cycle done 2
cycle done 3
cycle done 4
cycle done 5
myBr is called 5
myBr is called 5
myBr is called 5
myBr is called 5
myBr is called 5

0 个答案:

没有答案