Ich möchte Netzwerkänderung Listener in meiner App archivieren. Beispiel: Wenn ich meine App ohne ON Mobile Data und Wifi starte, wird "Network unavailable!" Angezeigt. Danach wenn ich ON Wifi oder Mobile Data als das es automatisch Daten online und auf der Benutzeroberfläche anzeigen.Warum funktioniert Network Change Listener nicht in meiner App?
Ich habe Main-Aktivität, die bereits erweitert Fragment implementiert Schnittstelle sowie Basis-Fragment zu. Ich habe Broadcast Receiver versucht, aber es funktioniert nicht. Wenn ich App ohne Netzwerk starte, zeigt es zwei Mal keine Internetverbindung. Und nach Wifi ON nicht automatisch aktualisieren, aber wenn ich im Menü auf andere Option klickte, dann UI zeigt. Bitte helfen Sie mir ...
1- Hauptaktivität
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- Basis Fragment Klasse
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- network Klasse
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- manifestieren ---
<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>
Aber wie und wo NetworkChangeReceiver-Klasse in BaseFragment-Klasse aufrufen? – Santosh
Sie müssen es nicht aufrufen, da es jetzt aus der Manifest-Datei registriert ist. Es wird also initialisiert, sobald die App gestartet wird, und es wird gestartet, um die Internetverbindung zu melden. – Vickyexpert