将变量从服务传递到广播接收器

时间:2013-05-30 08:54:16

标签: android android-intent android-service

大家好我想把两个变量从android服务发送到广播接收器,我需要帮助..

我在这里的服务类的oncreate方法中设置了两个var ..

    @Override
public void onCreate() {

    super.onCreate();


    Intent eSendIntent = new Intent(getApplicationContext(), OutgoingCallReceiver.class);

    eSendIntent.putStringArrayListExtra("BlockArray", contactsListB);
    eSendIntent.putExtra("BlockBool", checkB);
    getApplicationContext().sendOrderedBroadcast(eSendIntent, null);//Call receiver



 }

在我的接收器课程中......

onReceive(Context context, Intent intent){
Bundle bundle = intent.getExtras();

            if(bundle == null)
                    return;


            boolean cb = bundle.getBooleanExtra("BlockBool", true);
            ArrayList<String> ab = bundle.getStringArrayListExtra("BlockArray");


//disconnecting
            try{

                if(cb==false){
                for(int ij = 0; ij < ab.size(); ij++){
                    if(ab.get(ij).contains(phonenumber)){

                        tempBoolean = true;
                        //Log.e("OutgoingCallReceiver", SmsBlockerService.contactsListB.get(ij));
                    }
                }//for loop
                    if(tempBoolean==true){

                setResultData(null);
                        Toast.makeText(context, phonenumber + " is Blocked", Toast.LENGTH_SHORT).show();
                    }

            }else{
                setResultData(null);

                Toast.makeText(context, "All Out-Going Calls are Blocked", Toast.LENGTH_SHORT).show();
            }//end of main if

                    } catch(Exception e){
                        Toast.makeText(context, "Detect Calls sample application Failed: ", Toast.LENGTH_LONG).show();
             }
}

logcat的:

E / BroadcastReceiver(1459):BroadcastReceiver尝试在无序广播期间返回结果

3 个答案:

答案 0 :(得分:1)

在广播意图

中设置此项
         i.setAction("MYACTION");

而不是在你的清单中设置它

   <receiver android:name=".BroadcastClass" >
        <intent-filter>
            <action android:name="MYACTION" />
        </intent-filter>
    </receiver>

可能这应该有用

答案 1 :(得分:0)

假设您注册了接收器。现在尝试进行一些小改动:

        boolean cb = bundle.getBooleanExtra("BlockBool", true);
        ArrayList<String> ab = bundle.getStringArrayListExtra("BlockArray");

更新

在on create ...中调用广播... ...

  sendOrderedBroadcast(eSendIntent);

您正面临该错误,因为setResultData()函数仅适用于OrderedBroadcast。

来自Android文档:

   public final void setResultCode (int code)

   Added in API level 1
   Change the current result code of this broadcast; only works with broadcasts sent
   through Context.sendOrderedBroadcast. Often uses the Activity RESULT_CANCELED and  
   RESULT_OK constants, though the actual meaning of this value is ultimately up to the
   broadcaster.

   This method does not work with non-ordered broadcasts such as those sent with 
   Context.sendBroadcast.

答案 2 :(得分:0)

广播接收机工作的活动/屏幕

应该是&amp;运行。以便接收者可以接收传递的意图&amp;它的价值。