为什么网络更改侦听器在我的应用程序中不起作用

时间:2016-05-22 21:32:45

标签: android android-fragments android-studio broadcastreceiver android-broadcastreceiver

我想在我的应用中存档网络更改侦听器。例如:当我启动我的应用程序而没有ON Mobile Data和Wifi时,它显示"网络不可用!"。之后,当我在Wifi或移动数据上,它会自动获取数据并在UI上显示。

我已经扩展了Fragment实现接口以及基本片段的Main活动。 我尝试过broadcastreceiver,但它不起作用。当我在没有网络的情况下运行app时,它显示两次没有互联网连接并且在Wifi ON没有自动更新但是当我在菜单中单击其他选项然后UI显示。请帮帮我......

1-主要活动

public class MainActivity extends AppCompatActivity implements BaseFragment.OnFragmentInteractionListener{

    private Realm realm;
    private Results results;
    RecycleAdapter recyclerAdapter;
    BroadcastReceiver receiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        RealmConfiguration realmConfiguration = new RealmConfiguration.Builder
                (MainActivity.this)
                .build();
        Realm.setDefaultConfiguration(realmConfiguration);
    }


    @Override
    public void onTabletListener(Results result) {
        DetailFragment detailFragment = (DetailFragment) getFragmentManager()
                .findFragmentById(R.id.fragment_detail);

        if (detailFragment != null) {
            detailFragment.updateTabletUI(result);
        }
    }

    @Override
    public void onFragmentInteraction(Results currentMovie) {
        DetailFragment detailFragment = (DetailFragment) getFragmentManager()
                .findFragmentById(R.id.fragment_detail);

        if (detailFragment == null) {
            Intent intent = new Intent(this, DetailActivity.class)
                    .putExtra("movie_Id", currentMovie.getId())
                    .putExtra("movie_Name", currentMovie.getTitle())
                    .putExtra("poster_Path", currentMovie.getPoster_path())
                    .putExtra("back_poster_Path", currentMovie.getBackdrop_path())
                    .putExtra("release_Date", currentMovie.getRelease_date())
                    .putExtra("users_Rating", currentMovie.getVote_average())
                    .putExtra("overview", currentMovie.getOverview());
            startActivity(intent);
        } else {
            detailFragment.updateTabletUI(currentMovie);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.favoriteList) {
            Intent intent=new Intent(MainActivity.this, FavoriteActivity.class);
            startActivity(intent);
        }
        return super.onOptionsItemSelected(item);
    }
}

2- Base Fragment类

public class BaseFragment extends android.app.Fragment implements RecycleAdapter.GetDataFromAdapter {

    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    private static final String STATE_MOVIES = "state_movies";
    private View rootView, noView;
    private DataManager dataManager;
    private RecycleAdapter recyclerAdapter;
    private MovieResponse movieResponse;
    private List<Results> resultsList;

    private Results results;
    private OnFragmentInteractionListener mListener;
    private int menuItemPosition;
    private BroadcastReceiver receiver;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putParcelableArrayList(STATE_MOVIES, (ArrayList<? extends Parcelable>) resultsList);
        outState.putInt("menu_item", menuItemPosition);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.most_Popular:
                if(item.isChecked()){
                }else{
                    item.setChecked(true);
                    menuItemPosition = item.getItemId();
                    makeService("POPULAR");
                    return true;
                }
            case R.id.high_rated:
                if(item.isChecked()){
                }else{
                    item.setChecked(true);
                    menuItemPosition = item.getItemId();
                    makeService("TOP");
                    return true;
                }
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        // this will get called when the activity is re-created on device configuration change
        menu.findItem(menuItemPosition).setChecked(true);
    }



    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_base, container, false);            

        ButterKnife.bind(this, rootView);
        resultsList=new ArrayList<Results>();
        configRecycleView();

        if (savedInstanceState==null){
            receiver=new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                int status= NetworkStatus.getConnectivityStatus(context);
                if (status==0){
                }else{
                     makeService("POPULAR");
                }
                }
            };
            menuItemPosition = R.id.most_Popular;
        }else{
            resultsList=savedInstanceState.getParcelableArrayList(STATE_MOVIES);
            menuItemPosition = savedInstanceState.getInt("menu_item");
            recyclerAdapter.addMovieList(resultsList);
        }
        return rootView;
    }

    private void configRecycleView() {
        AutofitGridlayout layoutManager = new AutofitGridlayout(getActivity(), 200 );
        recyclerView.setHasFixedSize(true);
        recyclerView.setRecycledViewPool(new RecyclerView.RecycledViewPool());
        recyclerView.setLayoutManager(layoutManager);
        recyclerAdapter = new RecycleAdapter(getActivity(), BaseFragment.this);
        recyclerView.setAdapter(recyclerAdapter);
    }

    private void makeService(String query){
        dataManager = new DataManager();
        Call<MovieResponse> listCall;
        if (query=="TOP") {
            listCall= dataManager.getJSONData().getTopMovies();
        }else{
            listCall= dataManager.getJSONData().getPopMovies();
        }
        listCall.enqueue(new Callback<MovieResponse>() {
            @Override
            public void onResponse(Call<MovieResponse> call, Response<MovieResponse> response) {
                if (response.isSuccessful()) {
                    Results[] results = response.body().getResults();
                    resultsList = new ArrayList<Results>(Arrays.asList(results));
                    recyclerAdapter.addMovieList(resultsList);
                    Results firstResult=resultsList.get(0);
                    mListener.onTabletListener(firstResult);
                }
            }

            @Override
            public void onFailure(Call<MovieResponse> call, Throwable t) {
                Snackbar.make(rootView, R.string.Network_error, Snackbar.LENGTH_LONG)
                        .show();
            }
        });
    }

    @Override
    public void onCurrentMovie(Results currentMovie) {
        mListener.onFragmentInteraction(currentMovie);
    }

    @Override
    public void onAttach(Activity context) {
        super.onAttach(context);

        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    public interface OnFragmentInteractionListener {
        void onTabletListener(Results result);
        void onFragmentInteraction(Results result);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }
}

3- NetworkStatus类

public class NetworkStatus {

        public static int TYPE_WIFI = 1;
        public static int TYPE_MOBILE = 2;
        public static int TYPE_NOT_CONNECTED = 0;

        public static int getConnectivityStatus(Context context) {
            ConnectivityManager cm = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            if (null != activeNetwork) {
                if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
                    return TYPE_WIFI;

                if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
                    return TYPE_MOBILE;
            }
            return TYPE_NOT_CONNECTED;
        }
}

4-清单---

<manifest package="com.santossingh.popularmovieapp"
          xmlns:android="http://schemas.android.com/apk/res/android">

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity
            android:name=".Activities.MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <activity
            android:name=".Activities.FavoriteActivity"
            android:label="@string/title_activity_favorite"
            android:parentActivityName=".Activities.MainActivity"
            android:theme="@style/AppTheme.NoActionBar">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".Activities.MainActivity"/>
        </activity>
        <activity
            android:name=".Activities.VideoActivity"
            android:label="@string/title_activity_video"
            android:theme="@style/AppTheme.NoActionBar">
        </activity>
        <activity
            android:name=".Activities.DetailActivity"
            android:label="@string/title_activity_detail"
            android:parentActivityName=".Activities.MainActivity"
            android:theme="@style/AppTheme.NoActionBar">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.santossingh.popularmovieapp.Activities.MainActivity"/>
        </activity>
        <activity
            android:name=".Activities.ReviewActivity"
            android:label="@string/title_activity_review"
            android:theme="@style/AppTheme.NoActionBar">

        </activity>
    </application>

</manifest>

1 个答案:

答案 0 :(得分:1)

第一件事似乎是你没有在清单文件中设置网络接收器,所以在完成所有活动标签后的清单文件中,在应用程序标签内写下代码以注册你的接收器。

     <receiver android:name=".Activities.NetworkChangeReceiver" >
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        </intent-filter>
    </receiver>

 </application>

请注意,如果您没有接收器,请检查下面并使用它。

     import android.content.BroadcastReceiver;
     import android.content.Context;
     import android.content.Intent;
     import android.widget.Toast;

     public class NetworkChangeReceiver extends BroadcastReceiver {

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

         String status = NetworkUtil.getConnectivityStatusString(context); 
         Toast.makeText(context, status, Toast.LENGTH_LONG).show();
      }
   }