Monday, November 9, 2015

Blocking a call without user intervention in android with an example

I was very much in search of the way in which we can control calls in Android and faced a lot of difficulties implementing it at the beginning. So I thought to share some knowledge about the same which I gained in the journey.
Now, let’s start.
First create a package in the ‘src’ folder in your project named com.android.internal.telephony and within that package create a file and copy paste the interface ITelephony(I’ve given the interface below) and save the file as ITelephony.aidl. When you compile the project you will get a corresponding java file for the ITelephony in the ‘gen’ folder.
Code for ITelephony.aidl:
package com.w7app.internal.telephony;
interface ITelephony {

 boolean endCall();

 void answerRingingCall();

 void silenceRinger();
}
com.android.internal.telephony is an internal hidden class in the Android Telephony framework. As com.android.internal.telephony is not a public class in the sdk, we use java reflections for retrieving the internal class’s methods.
Now let’s see the permissions needed in the Manifest file:
<uses-permission android:name=”android.permission.READ_PHONE_STATE”/>
<uses-permission android:name=”android.permission.MODIFY_PHONE_STATE”/>
<uses-permission android:name=”android.permission.CALL_PHONE”/>
Now let’s look at the XML file where I’ve added a checkbox enabling which would block the incoming calls.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:orientation="vertical" >
<CheckBox
 android:id="@+id/cbBlockAll"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="Block all Calls" />
</LinearLayout>
First, we need to use a BroadcastReceiver which responds to the incoming call with action android.intent.action.PHONE_STATE  to detect the incoming call and also we need a PhoneStateListener  to listen to the call state and check whether the state is CALL_STATE_RINGINGIf yes, then end the call using endcall() method.
BroadcastReceiver CallBlocker;
To get the Telephony services,
TelephonyManager telephonyManager;
To get the ITelephony methods:
ITelephony telephonyService;
Now look at the code snippet below which blocks calls when the checkbox is enabled.
blockAll_cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {

 @Override
 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
 // TODO Auto-generated method stub
 CallBlocker =new BroadcastReceiver()
 {
 @Override
 public void onReceive(Context context, Intent intent) {
 // TODO Auto-generated method stub
 telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
 //Java Reflections
 Class c = null;
 try {
 c = Class.forName(telephonyManager.getClass().getName());
 } catch (ClassNotFoundException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 Method m = null;
 try {
 m = c.getDeclaredMethod("getITelephony");
 } catch (SecurityException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 } catch (NoSuchMethodException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 m.setAccessible(true);
 try {
 telephonyService = (ITelephony)m.invoke(telephonyManager);
 } catch (IllegalArgumentException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 } catch (IllegalAccessException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 } catch (InvocationTargetException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 telephonyManager.listen(callBlockListener, PhoneStateListener.LISTEN_CALL_STATE);
 }//onReceive()
 PhoneStateListener callBlockListener = new PhoneStateListener()
 {
 public void onCallStateChanged(int state, String incomingNumber)
 {
 if(state==TelephonyManager.CALL_STATE_RINGING)
 {
 if(blockAll_cb.isChecked())
 {
 try {
 telephonyService.endCall();
 } catch (RemoteException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 }
 }
 }
 };
 };//BroadcastReceiver
 IntentFilter filter= new IntentFilter("android.intent.action.PHONE_STATE");
 registerReceiver(CallBlocker, filter);
 }
 });
Here we use java reflections to get the instance of com.android .intenal.telephony class.
The code snippet is shown below:
Class c = null;
 try {
 c = Class.forName(telephonyManager.getClass().getName());
 } catch (ClassNotFoundException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 Method m = null;
 try {
 m = c.getDeclaredMethod("getITelephony");
 } catch (SecurityException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 } catch (NoSuchMethodException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 m.setAccessible(true);
 try {
 telephonyService = (ITelephony)m.invoke(telephonyManager);
 } catch (IllegalArgumentException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 } catch (IllegalAccessException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 } catch (InvocationTargetException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
Now use the internal methods in the internal class to block calls as shown below:
Here endcall() is used to end a call without user intervention.
telephonyService.endCall();
Register the receiver as shown below:
IntentFilter filter= new IntentFilter("android.intent.action.PHONE_STATE");
 registerReceiver(CallBlocker, filter);
We need to unregister the receiver after use. This is done in the onDestroy() callback.
protected void onDestroy() {
 // TODO Auto-generated method stub
 super.onDestroy();
 if (CallBlocker != null)
 {
 unregisterReceiver(CallBlocker);
 CallBlocker = null;
 }
 }
Now the whole code:
package com.w7app.mycallcontroller;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import com.android.internal.telephony.ITelephony;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.Bundle;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.telephony.PhoneNumberUtils;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
public class MyCallControllerActivity extends Activity {
 /** Called when the activity is first created. */
 CheckBox blockAll_cb;//,blockcontacts_cb;
 BroadcastReceiver CallBlocker;
 TelephonyManager telephonyManager;
 ITelephony telephonyService;
@Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);
 initviews();
 blockAll_cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {

 @Override
 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
 // TODO Auto-generated method stub
 CallBlocker =new BroadcastReceiver()
 {
 @Override
 public void onReceive(Context context, Intent intent) {
 // TODO Auto-generated method stub
 telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
 //Java Reflections
 Class c = null;
 try {
 c = Class.forName(telephonyManager.getClass().getName());
 } catch (ClassNotFoundException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 Method m = null;
 try {
 m = c.getDeclaredMethod("getITelephony");
 } catch (SecurityException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 } catch (NoSuchMethodException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 m.setAccessible(true);
 try {
 telephonyService = (ITelephony)m.invoke(telephonyManager);
 } catch (IllegalArgumentException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 } catch (IllegalAccessException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 } catch (InvocationTargetException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 telephonyManager.listen(callBlockListener, PhoneStateListener.LISTEN_CALL_STATE);
 }//onReceive()
 PhoneStateListener callBlockListener = new PhoneStateListener()
 {
 public void onCallStateChanged(int state, String incomingNumber)
 {
 if(state==TelephonyManager.CALL_STATE_RINGING)
 {
 if(blockAll_cb.isChecked())
 {
 try {
 telephonyService.endCall();
 } catch (RemoteException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 }
 }
 }
 };
 };//BroadcastReceiver
 IntentFilter filter= new IntentFilter("android.intent.action.PHONE_STATE");
 registerReceiver(CallBlocker, filter);
 }
 });
}
 public void initviews()
 {
 blockAll_cb=(CheckBox)findViewById(R.id.cbBlockAll);
 //blockcontacts_cb=(CheckBox)findViewById(R.id.cbBlockContacts);
 }
 @Override
 protected void onDestroy() {
 // TODO Auto-generated method stub
 super.onDestroy();
 if (CallBlocker != null)
 {
 unregisterReceiver(CallBlocker);
 CallBlocker = null;
 }
 }
}
Now the Screen Shots:
Hope this helped :) Happy Coding :)

Toggle Button in android

Today I thought of posting something which I came across recently. Toggle button.
As its name suggests, it toggles or switches between two states namely, ‘on’ and ‘off’. It is similar to a radio button.
Now, let’s see how this is implemented. I’ve given a simple example below to make you understand Togglebutton easily.
Firstly let’s go to our UI part. Inside our XML file we can add ToggleButton widget and set its attributes.
The XML code is shown below:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
          <ToggleButton
              android:id="@+id/tglbtn"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:textOn="ON"
              android:textOff="OFF"
              />
</LinearLayout>
The attribute   android:textOn=”ON” means  that the text on the button is  ‘ON’ when the it is in the ‘on’ state and   android:textOff=”OFF” specifies that the text on the button is ‘OFF’ when it is in the ‘off’ state.
Next step.
When the user clicks the button some action has to be done.
Here, I’ve given a Toast when the user clicks the button.
Here is the code. Just have a look.
package com.w7app.mytogglebutton;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MyToggleButtonActivity extends Activity {
    /** Called when the activity is first created. */
    ToggleButton toggle;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        toggle=(ToggleButton)findViewById(R.id.tglbtn);
        toggle.setOnClickListener(new OnClickListener() {
              public void onClick(View v) {
               // TODO Auto-generated method stub
              if(toggle.isChecked())
              {
               Toast.makeText(getApplicationContext(), "The state is changed to on", Toast.LENGTH_LONG).show();
               }
                else
                {
                  Toast.makeText(getApplicationContext(), "The state is changed to off", Toast.LENGTH_LONG).show();
                 }
                 }
                 });
    }
}
The Output looks like this:
When checked:
When Unchecked:

How to change the usual icon of your application in Android?

Usually when you run your application in your emulator, you may see the usual ic_launcher image as its icon. You can, of course change the icon of your application with the image you want. For that make these changes in the Manifest file.
Within application tag
<application
android:icon=“@drawable/flower” >
</application>
Here, flower is an image with extension .png(You can use images with extension .jpg, .gif, .png, .bmp, or .webp)
This is how the icon looks in your emulator:
Check the icon of the application named Deepthi in the picture below.
I just thought of blogging about this as I was curious about how the usual icon is changed at the beginning. Hope this post  was useful.

Tuesday, November 3, 2015

how to Link web page from android

Use this bellow code in xml layout

<TextView   
 android:layout_width="wrap_content"  
  android:layout_height="wrap_content"  
  android:autoLink="web"   
  android:textSize="15sp"  
  android:layout_marginTop="10dp"  
  android:layout_centerHorizontal="true" 
  android:text="google.com"   
  android:textColor="#000"   
  android:layout_below="@+id/textView"  
  android:textStyle="italic"/>




Use this bellow code in android manifest


<uses-permission android:name="android.permission.INTERNET"></uses-permission>
 

Sunday, October 25, 2015

Navigation Drawer with TabView in Android

How to place hyperlink to a website on android app

Use This code in Activity class in Oncreate.

// 1) How to replace link by text like "Click Here to visit Google" and
    // the text is linked with the website url ?
    TextView link = (TextView) findViewById(R.id.textView1);
    String linkText = "Visit the <a href='http://stackoverflow.com'>StackOverflow</a> web page.";
    link.setText(Html.fromHtml(linkText));
    link.setMovementMethod(LinkMovementMethod.getInstance());

Sunday, October 18, 2015

Vibrate and Sound defaults on notification in android

Its work fine to me,You can try it.
 protected void displayNotification() {

        Log.i("Start", "notification");

      // Invoking the default notification service //
        NotificationCompat.Builder  mBuilder =
                new NotificationCompat.Builder(this);
        mBuilder.setAutoCancel(true);

        mBuilder.setContentTitle("New Message");
        mBuilder.setContentText("You have "+unMber_unRead_sms +" new message.");
        mBuilder.setTicker("New message from PayMe..");
        mBuilder.setSmallIcon(R.drawable.icon2);

      // Increase notification number every time a new notification arrives //
        mBuilder.setNumber(unMber_unRead_sms);

      // Creates an explicit intent for an Activity in your app //

        Intent resultIntent = new Intent(this, FreesmsLog.class);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(FreesmsLog.class);

      // Adds the Intent that starts the Activity to the top of the stack //
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent =
                stackBuilder.getPendingIntent(
                        0,
                        PendingIntent.FLAG_UPDATE_CURRENT
                );
        mBuilder.setContentIntent(resultPendingIntent);

      //  mBuilder.setOngoing(true);
        Notification note = mBuilder.build();
        note.defaults |= Notification.DEFAULT_VIBRATE;
        note.defaults |= Notification.DEFAULT_SOUND;

        mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
      // notificationID allows you to update the notification later on. //
        mNotificationManager.notify(notificationID, mBuilder.build());

    }