IntentService LocalBroadcastManager未到达Receiver

时间:2015-08-25 19:22:48

标签: android android-intent broadcastreceiver intentfilter localbroadcastmanager

我使用的是Android Studio 1.3,我有一个SELECT j.PID, j.D, j.CHECKIN, IIF(j.TL <= 0, '0', j.TL) AS REMAINING_HRS FROM (SELECT PID, D, CHECKIN, CAST(DATEDIFF(hour, GETDATE(), DATEADD(HH,a.D,aCHECKIN) AS int) TL FROM TABLE1 a ) as j 设置,可以收集一些数据并通过IntentService发送出去,如下所示:

IntentService

LocalBroadcastManager

以上代码运行,但从未捕获广播。

的AndroidManifest.xml

public class cService extends IntentService {

    public cService(){
        super("cService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {

            SoapPrimitive response = (SoapPrimitive)envelope.getResponse();

            Intent broadcastIntent = new Intent("action.getTestData");
            broadcastIntent.putExtra("data", response.toString());
            LocalBroadcastManager.getInstance(this).sendBroadcast(broadcastIntent);
    }
}

扩展BroadcastReceiver的接收器(永远不会被调用)

<service android:name=".services.cService"
         android:exported="false">
</service>

<receiver android:name=".services.Receiver">
</receiver>

MainActivity onCreate()

public class Receiver extends BroadcastReceiver
{
    protected MainActivity mainActivityContext;

    public Receiver() {}

    @Override
    public void onReceive(Context context, Intent intent) {

        final String data = intent.getStringExtra("data");

        mainActivityContext.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                TextView txtData = (TextView)mainActivityContext.findViewById(R.id.textView2);
                txtData.setText(data);
            }
        });

    }
}

我在这里做错了导致广播没有收到?我认为这与我的public class MainActivity extends Activity implements View.OnClickListener{ TextView txtData; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Dummy text field that should populate with something upon //onReceive() executing... txtData = (TextView)findViewById(R.id.textView2); txtData.setText("Ready."); IntentFilter filter = new IntentFilter("action.getTestData"); filter.addDataScheme("string"); BroadcastReceiver c = new Receiver(); LocalBroadcastManager.getInstance(this).registerReceiver(c,filter); }

有关

4 个答案:

答案 0 :(得分:0)

您可以尝试在XML的android:exported=true块中设置<service>。根据文件:

http://developer.android.com/guide/topics/manifest/service-element.html#exported

  

默认值取决于服务是否包含意图过滤器。没有任何过滤器意味着只能通过指定其确切的类名来调用它。这意味着该服务仅供应用程序内部使用(因为其他人不知道类名)。所以在这种情况下,默认值为&#34; false&#34;。另一方面,至少有一个过滤器的存在意味着该服务是供外部使用的,因此默认值为&#34; true&#34;。

希望这有帮助。

答案 1 :(得分:0)

试试这个:

IntentFilter filter = new IntentFilter(cService.class);
filter.addCategory(Intent.CATEGORY_DEFAULT);
Receiver receiver = new Receiver();
registerReceiver(receiver, filter);

答案 2 :(得分:0)

我设法通过将BroadcastReceiver纳入onResume() MainActivity来解决我遇到的问题。我的目标是在Service完成检索所有网络数据后简单地捕获该数据。

我希望这有助于某人...

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.Button;

    public class MainActivity extends Activity implements View.OnClickListener {

        private boolean isReceiverRegistered;
        private Button btnRetrieveRouteData;
        private BroadcastReceiver receiver;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            setContentView(R.layout.activity_main);

            //UI Component Instances
            btnRetrieveRouteData =  (Button)findViewById(R.id.btnGetRouteInformation);
            btnRetrieveRouteData.setOnClickListener(this);
        }

        @Override
        protected void onResume(){
            super.onResume();
            if (!isReceiverRegistered) {
                IntentFilter intentFilter = new IntentFilter("ma.MainActivity.WebServiceReceiver.ReturnedReceivedDataFilePath");
                receiver = new BroadcastReceiver() {
                    @Override
                    public void onReceive(final Context context, Intent intent) {

                        //Get message from WebServiceReceiver Intent
                        String ReceivedDataFromIntent = intent.getStringExtra("WebServiceReceiver_ReturnedReceivedDataFilePath");

                        //Do whatever with the data received from the Service...
                    }
                };

                //Register the receiver
                isReceiverRegistered = true;
                this.registerReceiver(receiver, intentFilter);
            }
        }

        @Override
        protected void onPause(){
            super.onPause();
            if (isReceiverRegistered) {
                try {
                    unregisterReceiver(receiver);
                } catch (IllegalArgumentException e) {
                   //Handle Exception as needed...
                }
                isReceiverRegistered = false;
            }
        }

        @Override
        public void onDestroy(){
            super.onDestroy();
        }

        public void onClick(View view){
           switch(view.getId()){
               case R.id.btnGetRouteInformation:
                     CallWebService("testParam1", "testParam2");
                   break;

                default:
                    //Do nothing
                   break;
           }
        }

        private void CallWebService(String param1, String param2){

            //Begin web call to retrieve necessary data.
            ServerCaller.GetRequestForRouteWithDriverId(this, param1, param2);

            //WebServiceReceiver will get this returned data and broadcast it; received in "onResume()" here.
        }

    }

然后我有另一个名为WebServiceReceiver的classe,这个类将处理来自webservice的结果,它将准备数据,然后创建我们的onResume()覆盖方法将过滤和读入的意图。

public class WebServiceReceiver extends BroadcastReceiver
{
    public WebServiceReceiver() {}


    @Override
    public void onReceive(Context context, Intent intent) {

        String action = intent.getAction();

        if (action.equals("Helper_GetRequestForData")){
            //Retrieve the data from incoming Intent that web service submitted
            final String ReceivedDataFilePathThatContainsData = intent.getStringExtra("Helper_GetRequestForData");

            Intent responder = new Intent("ma.MainActivity.WebServiceReceiver.ReturnedReceivedDataFilePath");
            responder.putExtra("WebServiceReceiver_ReturnedReceivedDataFilePath", ReceivedDataFilePathThatContainsData);
            context.sendBroadcast(responder);
        }
    }

}

答案 3 :(得分:0)

一旦我更换了

,事情开始为我效劳
registerReceiver(receiver, filter);

LocalBroadcastManager.getInstance(this).registerReceiver(receiver, filter);

的上方。当然,这仅适用于您使用应用程序内部的本地服务。