Sunday, September 22, 2019

Call forwarding in android app


package com.danielthat.callforwarding;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.Button;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
/*
* Android programming - Call forwarding
* See http://danielthat.blogspot.com/2013/03/android-programming-call-forwarding.html
* Also see http://stackoverflow.com/questions/3465707/call-forwarding/8132536#8132536
*/
public class CallForwarding extends Activity
{
Button buttonCallForwardOn;
Button buttonCallForwardOff;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.call_forwarding_layout);
buttonCallForwardOn = (Button) findViewById(R.id.buttonCallForwardOn);
buttonCallForwardOn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
callforward("*21*0123456789#"); // 0123456789 is the number you want to forward the calls.
}
});
buttonCallForwardOff = (Button) findViewById(R.id.buttonCallForwardOff);
buttonCallForwardOff.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
callforward("#21#");
}
});
}
private void callforward(String callForwardString)
{
PhoneCallListener phoneListener = new PhoneCallListener();
TelephonyManager telephonyManager = (TelephonyManager)
this.getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);
Intent intentCallForward = new Intent(Intent.ACTION_CALL);
Uri mmiCode = Uri.fromParts("tel", callForwardString, "#");
intentCallForward.setData(mmiCode);
startActivity(intentCallForward);
}
private class PhoneCallListener extends PhoneStateListener
{
private boolean isPhoneCalling = false;
@Override
public void onCallStateChanged(int state, String incomingNumber)
{
if (TelephonyManager.CALL_STATE_RINGING == state)
{
// phone ringing
}
if (TelephonyManager.CALL_STATE_OFFHOOK == state)
{
// active
isPhoneCalling = true;
}
if (TelephonyManager.CALL_STATE_IDLE == state)
{
// run when class initial and phone call ended, need detect flag
// from CALL_STATE_OFFHOOK
if (isPhoneCalling)
{
// restart app
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage(getBaseContext().getPackageName());
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
isPhoneCalling = false;
}
}
}
}
}

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 |

Wednesday, September 18, 2019

android-phonestatelistener-phone-call-broadcast-receiver-tutorial


<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<receiver android:name=".IncomingCallReceiver" android:enabled="true" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
-------------- package should be same as below-----------
package com.android.internal.telephony;
/**
* Created by Md. Amirul Islam on 22-Sep-19.
* Email : amirul.islam@uslbd.com
* Unisoft™ Systems Limited
*/
public interface ITelephony {
boolean endCall();
void answerRingingCall();
void silenceRinger();
}
----------------------------
IncomingCallReceiver.java
public class IncomingCallReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ITelephony telephonyService;
try {
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
String number = intent.getExtras().getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
if(state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_RINGING)){
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
try {
Method m = tm.getClass().getDeclaredMethod("getITelephony");
m.setAccessible(true);
telephonyService = (ITelephony) m.invoke(tm);
if ((number != null)) {
telephonyService.endCall();
Toast.makeText(context, "Ending the call from: " + number, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(context, "Ring " + number, Toast.LENGTH_SHORT).show();
}
if(state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_OFFHOOK)){
Toast.makeText(context, "Answered " + number, Toast.LENGTH_SHORT).show();
}
if(state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_IDLE)){
Toast.makeText(context, "Idle "+ number, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
=================================
MainActivity.java
-----------------
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkPerms();
}
}
@RequiresApi(api = Build.VERSION_CODES.M)
private void checkPerms() {
String[] perms = new String[]{
Manifest.permission.CALL_PHONE,
Manifest.permission.READ_PHONE_STATE
};
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);
}
}
}
-------------------------------
view raw Callblock.java hosted with ❤ by GitHub



https://stackoverflow.com/questions/5990590/how-to-detect-phone-call-broadcast-receiver-in-android


https://gist.github.com/ftvs/e61ccb039f511eb288ee


http://droidcodesnippets.blogspot.com/2012/08/block-all-calls.html

http://www.nikola-breznjak.com/blog/android/make-native-android-app-can-block-phone-calls/

https://www.studytutorial.in/android-phonestatelistener-phone-call-broadcast-receiver-tutorial

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();
  }

}