服务中的动态广播接收机没有接收意图



我在服务中注册了一个动态广播接收器,我的服务正在while(somecondition)循环中执行一些繁重的SD卡读/写操作。

当广播从我的另一个应用程序(正在其他过程中)发送时,我的广播接收器没有接收到。

当循环时不执行时,会接收到相同的广播。

我还试着用Thread.Sleep(100)来结束循环,只是为了给广播接收器一些时间来执行,但它不起作用。

任何有关这方面的帮助都会对我帮助很大。

-谢谢&当做Manju

Code below for registering BxRx:
this.registerReceiver(myReceiver, new IntentFilter(ACTIVITY_NAME));
code below for sending broadcast:
Intent intnt = new Intent(ACTIVITY_NAME);
            intnt.putExtra("STOP_ALL_TESTING", true);
            Log.d(TAG,"Sending BX STOP_ALL_TESTING");
            myActivity.this.sendBroadcast(intnt);
code below for while loop:
while(somecondition){
:
:
:
Thred.sleep(100);
}

    public void onReceive(Context context, Intent intent) {
            Log.d(TAG,"Received intent: "+intent.getAction());
            boolean flag = intent.getBooleanExtra("STOP_ALL_TESTING", false);
            Log.d(TAG,"Flag set to: "+flag);
            if((boolean)intent.getBooleanExtra("STOP_ALL_TESTING",false)){
                Log.d(TAG,"Broadcast received to STOP_ALL_TESTING");
                Log.d(TAG,"Bx Rx, setting flag to stop testing as requested by user");
                synchronized(this){
                    bStopTesting=true;
                }
            }
        }

请粘贴完整的代码。

看起来您的问题是在服务的onStartCommand方法中有一个无休止的循环。onStartCommand和onReceive都在同一个线程上执行,并且只能一个接一个地执行。应用程序主线程是一个Looper线程,它以顺序的方式处理事件。基本上,如果你在服务中有一个无休止的操作,你会阻塞整个主线程,包括所有的GUI、服务和广播接收器。调用Thread.sleep()没有帮助,因为该方法不会返回。为了避免这种情况,您可以使用IntentServicehttp://developer.android.com/reference/android/app/IntentService.htmlclass,它将处理另一个线程上的意图。

public class HeavyService extends IntentService {
    public HeavyService() {
        super("HeavyService");
    }
    @Override
    public void onCreate() {
        super.onCreate();
        //do your initialization
    }
    @Override
    protected void onHandleIntent(Intent intent) {
        //this will be executed on a separate thread. Put your heavy load here. This is
        //similar to onStartCommand of a normal service
    }
}

最新更新