Sunday, September 22, 2019

Call forwarding in android app



Thursday, September 19, 2019

Recycler view different view type- android studio

public class LiteratureAdapter extends RecyclerView.Adapter {

    private List<Literature> mLiteratureList;

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView;
        switch (viewType) {
            case Literature.TYPE_BOOK:
                itemView = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.your_layout, parent, false);
                return new BookViewHolder(itemView);
            case Literature.TYPE_MAGAZINE:
                itemView = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.your_layout, parent, false);
                return new MagazineViewHolder(itemView);
            default: // TYPE_NEWSPAPER
                itemView = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.your_layout, parent, false);
                return new NewspaperViewHolder(itemView);
        }
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        switch (getItemViewType(position)) {
            case Literature.TYPE_BOOK:
                ((BookViewHolder) holder).bindView(position);
                break;
            case Literature.TYPE_MAGAZINE:
                ((MagazineViewHolder) holder).bindView(position);
                break;
            case Literature.TYPE_NEWSPAPER:
                ((NewspaperViewHolder) holder).bindView(position);
                break;
        }
    }

    @Override
    public int getItemCount() {
        if (mLiteratureList == null) {
            return 0;
        } else {
            return mLiteratureList.size();
        }
    }

    @Override
    public int getItemViewType(int position) {
        return mLiteratureList.get(position).getType();
    }

    public void setLiteratureList(List<? extends Literature> literatureList) {
        if (mLiteratureList == null){
            mLiteratureList = new ArrayList<>();
        }
        mLiteratureList.clear();
        mLiteratureList.addAll(literatureList);
        notifyDataSetChanged();
    }

    class BookViewHolder extends RecyclerView.ViewHolder {

        public BookViewHolder(View itemView) {
            super(itemView);
            // get reference to views
            // itemView.findViewById...
        }

        void bindView(int position) {
            Book book = (Book) mLiteratureList.get(position);
            // bind data to the views
            // textView.setText()...
        }
    }

    class MagazineViewHolder extends RecyclerView.ViewHolder {

        public MagazineViewHolder(View itemView) {
            super(itemView);
            // get reference to views
        }

        void bindView(int position) {
            Magazine magazine = (Magazine) mLiteratureList.get(position);
            // bind data to the views
        }
    }

    class NewspaperViewHolder extends RecyclerView.ViewHolder {

        public NewspaperViewHolder(View itemView) {
            super(itemView);
            // get reference to views
        }

        void bindView(int position) {
            Newspaper newspaper = (Newspaper) mLiteratureList.get(position);
            // bind data to the views
        }
    }
}

internet connection check in android studio

public class InternetConnectionDetector {

    private Context context;

    public InternetConnectionDetector(Context context) {
        this.context = context;
    }

    /**     * Checking for all possible Internet providers     * **/    public boolean isConnectedToInternet() {
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null)
                for (int i = 0; i < info.length; i++)
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
        }
        return false;
    }

    /**     *     * @param context     * @param enabled     * @throws Exception     */
    public void connectToDataConnection(Context context, boolean enabled) throws Exception {
        final ConnectivityManager conman = (ConnectivityManager)  context.getSystemService(Context.CONNECTIVITY_SERVICE);
        final Class conmanClass = Class.forName(conman.getClass().getName());
        final Field connectivityManagerField = conmanClass.getDeclaredField("mService");
        connectivityManagerField.setAccessible(true);
        final Object connectivityManager = connectivityManagerField.get(conman);
        final Class connectivityManagerClass =  Class.forName(connectivityManager.getClass().getName());
        final Method setMobileDataEnabledMethod = connectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
        setMobileDataEnabledMethod.setAccessible(true);

        try {
            setMobileDataEnabledMethod.invoke(connectivityManager, enabled);
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    /**     *     * @param context     * @param ON     * @throws Exception     */
    public void connectToWifi(Context context, boolean ON) throws Exception
    {

        WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
        wifiManager.setWifiEnabled(ON);

    }
}

----------------------------------------------

/** * to checkInternet Connection in mobile devices */public void checkInternetConnection() {
    if (!internetDetector.isConnectedToInternet()) {
        showPopUp();
    }
}

--------------------
/** * show popup message to user. */public void showPopUp() {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);

    // Setting Dialog Title    alertDialog.setTitle("No Internet :(");

    // Setting Dialog Message    alertDialog.setMessage("Network connection is not available. Choose either of the options to get connected to a network.");

    // Setting Icon to Dialog    alertDialog.setIcon(R.drawable.nointernet);

    // Setting WiFi Yes Button    alertDialog.setPositiveButton("WiFi",
            new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog,
                                    int which) {

                    try {
                        internetDetector.connectToWifi(getApplicationContext(), true);


                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    Toast.makeText(getApplicationContext(),
                            "Wifi Turned On",
                            Toast.LENGTH_SHORT).show();

                }
            });
    // Setting Data Connection Button    alertDialog.setNeutralButton("Mobile Data",
            new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog,
                                    int which) {

                    Intent intent = new Intent();
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setAction(Settings.ACTION_DATA_ROAMING_SETTINGS);
                    startActivity(intent);
                }
            });
    // Setting Positive "Cancel" Button    alertDialog.setNegativeButton("Cancel",
            new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog,
                                    int which) {
                    Toast.makeText(getApplicationContext(),
                            "Process Terminated!", Toast.LENGTH_SHORT)
                            .show();
                }
            });
    // Showing Alert Message    alertDialog.show();
}

How to apply JUST Admission 2019-2020 |

Tuesday, September 17, 2019

Permission on android studio

private void checkPerms() {

    String[] perms = new String[]{
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.READ_CONTACTS,
            Manifest.permission.PROCESS_OUTGOING_CALLS    };

    List<String> requestingPerms = new ArrayList<>();

    for (String perm : perms) {
        if (checkSelfPermission(perm) !=
                PackageManager.PERMISSION_GRANTED) {
            requestingPerms.add(perm);
        }
    }

    if (requestingPerms.size() > 0) {
        requestPermissions(requestingPerms.toArray(new String[requestingPerms.size()]), 0);
    }

}




check permission:
PackageManager pm = getPackageManager();
int hasPerm = pm.checkPermission(Manifest.permission.CAMERA, getPackageName());
if (hasPerm == PackageManager.PERMISSION_GRANTED) {

    selectFile();


}else{

checkPerms()

}

Android Audio Recording Tutorial best practices

package com.benmccann.android.hello;

import java.io.File;
import java.io.IOException;

import android.media.MediaRecorder;
import android.os.Environment;

/**
 * @author <a href="http://www.benmccann.com">Ben McCann</a>
 */
public class AudioRecorder {

  final MediaRecorder recorder = new MediaRecorder();
  final String path;

  /**
   * Creates a new audio recording at the given path (relative to root of SD card).
   */
  public AudioRecorder(String path) {
    this.path = sanitizePath(path);
  }

  private String sanitizePath(String path) {
    if (!path.startsWith("/")) {
      path = "/" + path;
    }
    if (!path.contains(".")) {
      path += ".3gp";
    }
    return Environment.getExternalStorageDirectory().getAbsolutePath() + path;
  }

  /**
   * Starts a new recording.
   */
  public void start() throws IOException {
    String state = android.os.Environment.getExternalStorageState();
    if(!state.equals(android.os.Environment.MEDIA_MOUNTED))  {
        throw new IOException("SD Card is not mounted.  It is " + state + ".");
    }

    // make sure the directory we plan to store the recording in exists
    File directory = new File(path).getParentFile();
    if (!directory.exists() && !directory.mkdirs()) {
      throw new IOException("Path to file could not be created.");
    }

    recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    recorder.setOutputFile(path);
    recorder.prepare();
    recorder.start();
  }

  /**
   * Stops a recording that has been previously started.
   */
  public void stop() throws IOException {
    recorder.stop();
    recorder.release();
  }

}