Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 为什么活动类中的BroadCastReceiver未接收到LocalBroadCastManager从IntentService发送的意图?_Java_Android_Android Layout_Listview_Android Fragments - Fatal编程技术网

Java 为什么活动类中的BroadCastReceiver未接收到LocalBroadCastManager从IntentService发送的意图?

Java 为什么活动类中的BroadCastReceiver未接收到LocalBroadCastManager从IntentService发送的意图?,java,android,android-layout,listview,android-fragments,Java,Android,Android Layout,Listview,Android Fragments,选择LanguageFragment.java Intent explicitGetNumberServiceIntentUSA = new Intent(getActivity(), GetNumberService.class); explicitGetNumberServiceIntentUSA.putExtra("country", "USA"); getActivity().startService(explicitGetNumberServiceIntentUSA); 这就是Get

选择LanguageFragment.java

Intent explicitGetNumberServiceIntentUSA = new Intent(getActivity(), GetNumberService.class);
explicitGetNumberServiceIntentUSA.putExtra("country", "USA");
getActivity().startService(explicitGetNumberServiceIntentUSA);
这就是GetNumberService的调用方式

这就是从GetNumberService.java传递arraylist的方式

Intent mobileNumbersIntent = new Intent();
mobileNumbersIntent.putStringArrayListExtra("mobileNumbers", mobileNumberList);
mobileNumbersIntent.setAction(ChooseNumber1.MobileNumberBroadcastReceiver.MOBILE_NO_RECEIVER);
mobileNumbersIntent.addCategory(Intent.CATEGORY_DEFAULT);
mobileNumbersIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //this is needed when callling startActivity() outisde an Activity            
sendBroadcast(mobileNumbersIntent);
在onHandleIntent()方法中

GetNumberService完美地完成了它的工作

选择编号1.java

public class ChooseNumber1 extends AppCompatActivity {
    private MobileNumberBroadcastReceiver receiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        IntentFilter intentFilter = new IntentFilter(MobileNumberBroadcastReceiver.MOBILE_NO_RECEIVER);
        intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
        receiver = new MobileNumberBroadcastReceiver();
        registerReceiver(receiver, intentFilter);
        setContentView(R.layout.activity_choose_number1);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    protected void onDestroy(){
        unregisterReceiver(receiver);
        super.onDestroy();
    }

    public class MobileNumberBroadcastReceiver extends BroadcastReceiver {

        public static final String MOBILE_NO_RECEIVER = "abcd";
        ArrayList<String> mobileNumbersList = new ArrayList<>();
        ListView mobileNumberListView;
        ArrayAdapter<String> mobileNumberAdapter;

        @Override
        public void onReceive(Context context, Intent intent) {
          //  if(intent.getAction().equals(GetNumberService.MOBILE_NUMBER_LIST_PASS_ACTION)){
                mobileNumbersList = intent.getStringArrayListExtra("mobileNumberList");
         //   }
            mobileNumberAdapter = new ArrayAdapter<String>(new ChooseNumbers(),
                    R.layout.list_item_numbers, R.id.list_item_number_textview, mobileNumbersList);

            mobileNumberListView = (ListView) findViewById(R.id.listViewNumberList);
            mobileNumberListView.setAdapter(mobileNumberAdapter);
        }
    }

}
公共类选择编号1扩展AppCompative活动{
专用移动通信接收机;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
IntentFilter IntentFilter=新的IntentFilter(MobileNumberBroadcastReceiver.MOBILE\u NO\u RECEIVER);
intentFilter.addCategory(Intent.CATEGORY\u默认值);
receiver=新的MobileNumberBroadcastReceiver();
注册接收者(接收者、意图过滤器);
setContentView(R.layout.activity\u choose\u number1);
Toolbar Toolbar=(Toolbar)findViewById(R.id.Toolbar);
设置支持操作栏(工具栏);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@凌驾
受保护的空onDestroy(){
未注册接收人(接收人);
super.ondestory();
}
公共类MobileNumberBroadcastReceiver扩展了BroadcastReceiver{
公共静态最终字符串MOBILE\u NO\u RECEIVER=“abcd”;
ArrayList MobileNumberList=新的ArrayList();
ListView-mobileNumberListView;
阵列适配器;
@凌驾
公共void onReceive(上下文、意图){
//if(intent.getAction().equals(GetNumberService.MOBILE\u NUMBER\u LIST\u PASS\u ACTION)){
mobileNumberList=intent.getStringArrayListExtra(“mobileNumberList”);
//   }
mobileNumberAdapter=new ArrayAdapter(new ChooseNumber(),
R.layout.list\u item\u number、R.id.list\u item\u number\u textview、mobileNumberList);
mobileNumberListView=(ListView)findViewById(R.id.listViewNumberList);
setAdapter(mobileNumberAdapter);
}
}
}
活动\u选择\u number1.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.a2ndnumber.a2ndnumber.ChooseNumbers">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_choose_number1" />

</android.support.design.widget.CoordinatorLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.a2ndnumber.a2ndnumber.ChooseNumber1"
    tools:showIn="@layout/activity_choose_number1">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/listViewNumberList"/>

</RelativeLayout>

content\u choose\u number1.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.a2ndnumber.a2ndnumber.ChooseNumbers">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_choose_number1" />

</android.support.design.widget.CoordinatorLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.a2ndnumber.a2ndnumber.ChooseNumber1"
    tools:showIn="@layout/activity_choose_number1">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/listViewNumberList"/>

</RelativeLayout>

附注2:

问题是,我无法在ChooseNumber1.java或ChooseNumbersFragment.java中接收MobileNumberIntent。我认为问题在于BroadcastManager.java。如果我调试,它将转到Handler.java和其他几个类,最后是mId=-1,堆栈跟踪中没有错误。我被打动了

PS:AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.a2ndnumber.a2ndnumber">

    <!-- TODO : Add permissions -->
    <uses-permission android:name="android.permission.INTERNET" />

    <!-- Contacts -->
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".ChooseLanguage"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
        </activity>
        <activity
            android:name=".Choose_Country"
            android:label="@string/app_name"
            android:parentActivityName=".ChooseLanguage"
            android:theme="@style/AppTheme.NoActionBar">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.a2ndnumber.a2ndnumber.ChooseLanguage" />
        </activity>
        <activity
            android:name=".MainActivity"
            android:noHistory="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name=".service.GetNumberService" />

        <activity
            android:name=".ChooseNumber1"
            android:label="@string/title_activity_choose_number1"
            android:parentActivityName=".Choose_Country"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.a2ndnumber.a2ndnumber.Choose_Country" />
        </activity>
    </application>

</manifest>

PS:在阅读了Stackoverflow中的大量示例和答案后,我对代码进行了大量修改。这是我的最新代码。看起来问题在于意图过滤器和/或使用操作获取意图。请帮帮我。谢谢。

您的
findViewById()
很好,返回一个非空值

问题在于stacktrace中的适配器:分配适配器时,传递给它的
mobileNumbersList
列表为空
ArrayAdapter
需要非空数组


(代码中还有许多其他问题-这只是NPE。)

我建议检查此简单代码是否有效:

内部活动:

@Override
      protected void onResume() {
        super.onResume();
        IntentFilter intFilt = new IntentFilter(MYBROADCASTINGSTRING);
        registerReceiver(updbr,intFilt);
      }
    @Override
      protected void onPause() {
        super.onPause();
        unregisterReceiver(updbr);
      }


        private BroadcastReceiver updbr = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent2) {
                    try {
Log.d("MYLOG", "gotcha!");
                    } catch (Exception e) {

                    }
                }
            };
在接球时在发球中施放broadbast:

Intent intentBR = new Intent(MYBROADCASTINGSTRING);
        intentBR.putExtra(somestring, "teststring");
        sendBroadcast(intentBR);
其中,
MYBROADCASTINGSTRING
是某个常量。例如,
公共最终静态字符串MYBROADCASTINGSTRING=“MYBROADCASTINGSTRING”

它不需要改进
AndroidManifest.xml
。它有用吗

当你发送广播时,你会传递一个额外的信息,就像这样

mobileNumbersIntent.putStringArrayListExtra("mobileNumbers", mobileNumberList);
当你在广播接收器中读到这些额外的信息时,你就是这样做的

mobileNumbersList = intent.getStringArrayListExtra("mobileNumberList");
您应该使用同一个键作为附加项。为此,我建议在
IntentService
中使用一个常量

public static final string EXTRA_MOBILE_NUMBERS = "mobile_numbers";
然后你可以做一些事情,比如:

mobileNumbersIntent.putStringArrayListExtra(MyIntentService.EXTRA_MOBILE_NUMBERS, mobileNumberList);


要处理来自IntentService的结果,请使用ResultReciver而不是广播接收器

像这样,

步骤1:在活动中使用ResultReceiver创建结果处理程序

public ResultReceiver downloadReceiver = new ResultReceiver(new Handler()) {
    @Override
    protected void onReceiveResult(int resultCode, Bundle resultData) {
        super.onReceiveResult(resultCode, resultData);
        //Broadcast /send the result code in intent service based on your logic(success/error) handle with switch
        switch (resultCode) {
            case 1: {
                //Get the resultData and do your logic here
                //Update your list view item here
                break;
            }
            case 2: {
                //Get the resultData and do your logic here
                //Update your list view item here
                break;
            }
        }
    }
}; 
步骤2:将结果处理程序放入intent中并启动intent服务

Intent intent = new Intent(getContext(), DownloadService.class);
intent.putExtra("receiver",downloadReceiver);
步骤3:在服务类中处理意图(获取结果处理程序的值)

步骤4:向结果处理程序发送/广播数据

final ResultReceiver receiver;

@Override
protected void onHandleIntent(Intent intent) {
    receiver = intent.getParcelableExtra("receiver");
}
//based on your logic, change the result code and data

//Add your result data (success scenario)
Bundle bundle = new Bundle();
bundle.putString("result","Some text");
receiver.send(1,bundle);

//Add your result data (failure scenario)
receiver.send(0,bundle);

所需的流不需要广播和接收器设置。由于
选择编号1
活动将在
服务
完成其工作后启动,因此只需将
阵列列表
附加到用于启动
选择编号1
意图
。然后可以在
onCreate()
中检索列表,您的
ListView
及其
适配器可以立即初始化,而不是试图等待广播

例如,在您的
服务中
,在组合列表后:

Intent mobileNumbersIntent = new Intent(this, ChooseNumber1.class);
mobileNumbersIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mobileNumbersIntent.putStringArrayListExtra("mobileNumbers", mobileNumberList);
startActivity(mobileNumbersIntent);
然后,在
活动中

public class ChooseNumber1 extends AppCompatActivity {

    private ArrayAdapter<String> mobileNumberAdapter;
    private ArrayList<String> mobileNumbersList = new ArrayList<>();
    private ListView mobileNumberListView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_number1);

        ...

        mobileNumberListView = (ListView) findViewById(R.id.listViewNumberList);

        mobileNumbersList = getIntent().getStringArrayListExtra("mobileNumbers");
        if(mobileNumbersList != null) {
            mobileNumberAdapter = new ArrayAdapter<String>(this,
                                                           R.layout.list_item_numbers,
                                                           R.id.list_item_number_textview,
                                                           mobileNumbersList);
            mobileNumberListView.setAdapter(mobileNumberAdapter);
        }
    }
}
公共类选择编号1扩展AppCompative活动{
专用阵列适配器;
私有ArrayList MobileNumberList=新ArrayList();
私有ListView-mobileNumberListView;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u choose\u number1);
...
mobileNumberListView=(ListView)findViewById(R.id.listViewNumberList);
mobileNumbersList=getIntent().GetStringArrayListXTRA(“mobileNumbers”);
如果(MobileEnumbersList!=null){
移动通信适配器