2

그래서 사용자가 WiFi 또는 4G를 사용하여 로그인 한 후 데이터를 가져올 것인지 결정할 수있는 앱을 만들고 있습니다. 누구든지 여기에 추가하고 싶지 않으면 나중에 결정하십시오.) 그래서 현재 MainActivity.java가 있는데 이것은 (아직 구현하지 않은) 로그인을 처리 할 것이고 Navigation Drawer에 NavDrawerActivity.java를 가지고 있습니다. 이제 분명히 "로그인"을하면 Nav Drawer로 이동합니다. 그러나 사용자가 로그인하기 전에 Wi-Fi 또는 데이터를 사용할 것인지 아닌지를 선택할 수 있어야하고 로그인 한 후에 선택할 수 있어야합니다. 두 부분으로 된 질문입니다. 어떻게 구현할까요? 글쎄, 로그인 화면에 넣는 것이 좋은 생각입니까? 또는 WiFi를 변경하지 않는 한 항상 WiFi를 사용하도록 기본값을 설정해야하며 WiFi가 활성화되어 있지 않으면 사용하도록 설정해야합니까?다른 활동에서 Nav Drawer 설정 사용하기

는 MainActivity.java 코드

package com.example.jamessingleton.chffrapi; 

import android.content.Context; 
import android.content.Intent; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.support.v7.app.AppCompatActivity; 
import android.support.v7.widget.Toolbar; 
import android.util.Log; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.ProgressBar; 
import android.widget.TextView; 


import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 
import org.json.JSONTokener; 

import java.io.BufferedReader; 
import java.io.InputStreamReader; 
import java.net.HttpURLConnection; 
import java.net.URL; 


public class MainActivity extends AppCompatActivity { 

    EditText emailText; 
    TextView responseView; 
    ProgressBar progressBar; 
    static final String API_KEY = "USE_YOUR_OWN_API_KEY"; 
    static final String API_URL = "https://api.fullcontact.com/v2/person.json?"; 
    static final String ClientId= ""; 
    static final String ClientSecret = ""; 



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

     responseView = (TextView) findViewById(R.id.responseView); 
     emailText = (EditText) findViewById(R.id.emailText); 
     progressBar = (ProgressBar) findViewById(R.id.progressBar); 
     final Context context = this; 
     Button queryButton = (Button) findViewById(R.id.queryButton); 
     queryButton.setOnClickListener(new View.OnClickListener() { 


      @Override 
      public void onClick(View v) { 
       new RetrieveFeedTask().execute(); 

       Intent intent = new Intent(context, NavDrawerActivity.class); 
       startActivity(intent); 
      } 
     }); 
    } 


    class RetrieveFeedTask extends AsyncTask<Void, Void, String> { 

     private Exception exception; 

     protected void onPreExecute() { 
      progressBar.setVisibility(View.VISIBLE); 
      responseView.setText(""); 
     } 

     protected String doInBackground(Void... urls) { 
      String email = emailText.getText().toString(); 
      // Do some validation here 

      try { 
       URL url = new URL(API_URL + "email=" + email + "&apiKey=" + API_KEY); 
       HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 
       try { 
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); 
        StringBuilder stringBuilder = new StringBuilder(); 
        String line; 
        while ((line = bufferedReader.readLine()) != null) { 
         stringBuilder.append(line).append("\n"); 
        } 
        bufferedReader.close(); 
        return stringBuilder.toString(); 
       } 
       finally{ 
        urlConnection.disconnect(); 
       } 
      } 
      catch(Exception e) { 
       Log.e("ERROR", e.getMessage(), e); 
       return null; 
      } 
     } 

     protected void onPostExecute(String response) { 
      if(response == null) { 
       response = "THERE WAS AN ERROR"; 
      } 
      progressBar.setVisibility(View.GONE); 
      Log.i("INFO", response); 
      responseView.setText(response); 
      // TODO: check this.exception 
      // TODO: do something with the feed 

//   try { 
//    JSONObject object = (JSONObject) new JSONTokener(response).nextValue(); 
//    String requestID = object.getString("requestId"); 
//    int likelihood = object.getInt("likelihood"); 
//    JSONArray photos = object.getJSONArray("photos"); 
//    . 
//    . 
//    . 
//    . 
//   } catch (JSONException e) { 
//    e.printStackTrace(); 
//   } 
     } 
    } 
} 

NavDrawerActivity.java 코드는

package com.example.jamessingleton.chffrapi; 

import android.app.FragmentManager; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.os.Bundle; 
import android.support.design.widget.FloatingActionButton; 
import android.support.design.widget.Snackbar; 
import android.view.View; 
import android.support.design.widget.NavigationView; 
import android.support.v4.view.GravityCompat; 
import android.support.v4.widget.DrawerLayout; 
import android.support.v7.app.ActionBarDrawerToggle; 
import android.support.v7.app.AppCompatActivity; 
import android.support.v7.widget.Toolbar; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.widget.RadioButton; 
import android.widget.RadioGroup; 




public class NavDrawerActivity extends AppCompatActivity 
     implements NavigationView.OnNavigationItemSelectedListener{ 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_nav_drawer); 
     Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 

     FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 

      fab.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View view) { 
        //Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) 
        //.setAction("Action", null).show(); 
        Intent sendIntent = new Intent(); 
        sendIntent.setAction(Intent.ACTION_SEND); 
        sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send."); 
        sendIntent.setType("text/plain"); 
        startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to))); 
       } 
      }); 


     DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
     ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
       this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); 
     drawer.setDrawerListener(toggle); 
     toggle.syncState(); 

     NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); 
     navigationView.setNavigationItemSelectedListener(this); 
    } 


    @Override 
    public void onBackPressed() { 
     DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
     if (drawer.isDrawerOpen(GravityCompat.START)) { 
      drawer.closeDrawer(GravityCompat.START); 
     } else { 
      super.onBackPressed(); 
     } 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.nav_drawer, menu); 
     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 
     FragmentManager fragmentSettingsManager = getFragmentManager(); 
     //noinspection SimplifiableIfStatement 
     if (id == R.id.action_settings) { 
      fragmentSettingsManager.beginTransaction().replace(R.id.content_frame, new SettingsFragment()).commit(); 
      setTitle(R.string.action_settings); 
      FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 
      fab.setVisibility(View.GONE); 
     } 
     return super.onOptionsItemSelected(item); 
    } 

    @SuppressWarnings("StatementWithEmptyBody") 
    @Override 
    public boolean onNavigationItemSelected(MenuItem item) { 
     // Handle navigation view item clicks here. 
     int id = item.getItemId(); 
     FragmentManager fragmentManager = getFragmentManager(); 
     if (id == R.id.nav_first_layout) { 
      fragmentManager.beginTransaction().replace(R.id.content_frame, new FirstFragment()).commit(); 
      setTitle(R.string.speed_graph); 
      FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 
      fab.setVisibility(View.VISIBLE); 
     } else if (id == R.id.nav_second_layout) { 
      fragmentManager.beginTransaction().replace(R.id.content_frame, new SecondFragment()).commit(); 
      setTitle(R.string.drive_player); 
      FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 
      fab.setVisibility(View.VISIBLE); 
     } else if (id == R.id.nav_third_layout) { 
      fragmentManager.beginTransaction().replace(R.id.content_frame, new ThirdFragment()).commit(); 
      setTitle(R.string.google_maps); 
      FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 
      fab.setVisibility(View.VISIBLE); 
     } else if (id == R.id.nav_share) { 
      Intent sendIntent = new Intent(); 
      sendIntent.setAction(Intent.ACTION_SEND); 
      sendIntent.putExtra(Intent.EXTRA_TEXT, "Go Check Out All Driving Data in the Play Store!"); 
      sendIntent.setType("text/plain"); 
      startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to))); 
     } 

     DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
     drawer.closeDrawer(GravityCompat.START); 
     return true; 
    } 
} 

나를 당신들이 필요로 아무것도가 있는지 알고있는 모든 도움 :

위해 너희들을 감사하자

다음은 WifivsDataDialog 코드입니다.

package com.example.jamessingleton.chffrapi; 

import android.app.AlertDialog; 
import android.app.Dialog; 
import android.app.DialogFragment; 
import android.content.DialogInterface; 
import android.os.Bundle; 

/** 
* Created by James Singleton on 8/9/2016. 
*/ 

public class WifivsDataDialog extends DialogFragment { 
    @Override 
    public Dialog onCreateDialog(Bundle savedInstanceState) { 
     // Use the Builder class for convenient dialog construction 
     AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); 
     builder.setMessage(R.string.dialog_box) 
       .setPositiveButton(R.string.WiFi, new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int id) { 
         // FIRE ZE MISSILES! 
        } 
       }) 
       .setNegativeButton(R.string.Cell_Data, new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int id) { 
         // User cancelled the dialog 
        } 
       }); 
     // Create the AlertDialog object and return it 
     return builder.create(); 
    } 
} 

답변

1

달성하고자하는 것이 명확하지 않습니다.

데이터를 가져와야합니까? 사용자가 기기에서 Wi-Fi 및 모바일 네트워크를 모두 사용 중지 한 경우 어떻게됩니까? Wi-Fi를 사용하도록 선택했지만 기기에서 모바일 네트워크 만 사용하도록 설정 한 경우 어떻게해야합니까?

나는이 내용을 설명하는 앱의 시작 부분에 Dialog을 만들었으며 과 함께 모바일 네트워크 또는 Wi-Fi에서만 데이터를 가져올 수 있도록 허용할지 사용자가 선택할 수 있도록했습니다. "표시하지 않음 대화 상자가 다시 표시됩니다. "CheckBox.

사용자가 CheckBox을 선택하면 추가 실행시 기본 동작이됩니다 (환경 설정/설정에서 변경할 수 있음).

로그인 ActivityonCreate()에서 Dialog을 표시 할 수 있습니다.

connection_dialog.xml :

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
       android:layout_width="match_parent" 
       android:layout_height="match_parent" 
       android:orientation="vertical"> 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Would you like to allow fetching data on mobile network?"/> 

    <RadioGroup 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:orientation="vertical"> 

     <RadioButton 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="Yes"/> 

     <RadioButton 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="No, allow Wi-Fi only"/> 
    </RadioGroup> 

    <Button 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_gravity="end" 
     android:text="OK"/> 

</LinearLayout> 

ConnectionDialogFragment.java : 예를 들어

import android.os.Bundle; 
import android.support.annotation.Nullable; 
import android.support.v4.app.DialogFragment; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 

public class ConnectionDialogFragment extends DialogFragment { 

    public ConnectionDialogFragment() { 
    } 

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

     // set up your View here 

     return view; 
    } 
} 

그리고 당신의 Activity :

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

    // ... 

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); 
    if(prefs.getBoolean("show_dialog", true)) { 
     showDialog(); 
    } 
} 

private void showDialog() { 
    ConnectionDialogFragment dialog = new ConnectionDialogFragment(); 
    dialog.show(getSupportFragmentManager(), "connection_dialog"); 
} 

Dialogs의 개발자 가이드를 확인하십시오.에 따라

// this method will return either 
// ConnectivityManager.TYPE_MOBILE 
// or 
// ConnectivityManager.TYPE_WIFI 
// or -1 (if no connection is available) 
private int checkAvailableConnectionType() { 
    ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); 
    NetworkInfo activeNetwork = manager.getActiveNetworkInfo(); 
    int type = activeNetwork.getType(); 
    if(activeNetwork.isConnected() && (type == ConnectivityManager.TYPE_MOBILE || 
      type == ConnectivityManager.TYPE_WIFI)) { 
     return type; 
    } 
    return -1; 
} 

그리고 당신의 물건을 할 : 사용자가 그들이 Wi-Fi 만 사용하거나 모바일 네트워크, 당신은 이런 일에 사용할 수있는 연결을 확인 할 수 있도록할지 여부를 선택했다

사용자의 선택 및 현재 활성화 된 연결 (예 : Wi-Fi를 켜도록 사용자에게 알립니다).