Showing posts with label android. Show all posts
Showing posts with label android. Show all posts

Wednesday, February 10, 2016

How to read precise state of an outgoing call in Android programatically


In this example I will show you how to get precise call state in Android programatically using java reflection API. 


Add this in Android Manifest file. Declare Broadcast receiver.




<receiver
        android:name=".OutCallLogger"
        android:enabled="true"
        android:exported="true" >
            <intent-filter>
                <action android:name="android.intent.action.PRECISE_CALL_STATE" />
                <action android:name="android.intent.action.NEW_OUTGOING_CALL" />
            </intent-filter>
    </receiver>
Add below permissions in android manifest file.
<uses-permission android:name="android.permission.READ_PHONE_STATE" />  
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
<uses-permission android:name="android.permission.READ_PRECISE_PHONE_STATE" />
Also add this line in manifest file.
 <uses-feature android:name="android.hardware.telephony"></uses-feature>
And this is your class which will be used for getting precised call state for outgoing calls.
 public class OutCallLogger extends BroadcastReceiver {
public OutCallLogger() {
}
TelephonyManager Tm;
ITelephony telephonyService;
Class c = null;
Method methodGetInstance = null;
Method methodGetActiveFgCallState=null;
String TAG="Tag";
Object objectCallManager=null;
Context context1;
Class<?> classCallManager;

Class telephonyClass;
Class telephonyStubClass;
Class serviceManagerClass;
Class serviceManagerStubClass;
Class serviceManagerNativeClass;
Class serviceManagerNativeStubClass;

Method telephonyCall;
Method telephonyEndCall;
Method telephonyAnswerCall;
Method getDefault;

Method[] temps;
Constructor[] serviceManagerConstructor;

// Method getService;
Object telephonyObject;
Object serviceManagerObject;
private Timer timer= null;

@Override
public void onReceive(Context context, Intent intent) {
    // TODO: This method is called when the BroadcastReceiver is receiving
    // an Intent broadcast.



    this.context1= context;
 Tm=(TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
final ClassLoader classLoader = this.getClass().getClassLoader();
try {
     classCallManager = classLoader.loadClass("com.android.internal.telephony.CallManager");
    Log.e(TAG, "CallManager: Class loaded " + classCallManager.toString());
    methodGetInstance = classCallManager.getDeclaredMethod("getInstance");
    methodGetInstance.setAccessible(true);
    Log.e(TAG, "CallManager: Method loaded " + methodGetInstance.getName());
    objectCallManager = methodGetInstance.invoke(null);
    Log.e(TAG, "CallManager: Object loaded " + objectCallManager.getClass().getName());
    Method[] aClassMethods = classCallManager.getDeclaredMethods();
    for(Method m : aClassMethods)
    {
        Log.e("MEthods", m.getName());
    }
    methodGetActiveFgCallState = classCallManager.getDeclaredMethod("getActiveFgCallState");
    Log.e(TAG, "CallManager: Method loaded " + methodGetActiveFgCallState.getName());

    Log.e(TAG, "CallManager: What is the Call state = " + methodGetActiveFgCallState.invoke(objectCallManager));
}
catch (ClassNotFoundException e) {
    Log.e(TAG, e.getClass().getName() + e.toString());
}
catch (NoSuchMethodException e) {
    Log.e(TAG, e.getClass().getName() + e.toString());
}
catch (InvocationTargetException e) {
    Log.e(TAG, e.getClass().getName() + e.toString());
}
catch (IllegalAccessException e) {
    Log.e(TAG, e.getClass().getName() + e.toString());
}
Tm.listen(new PhoneStateListener(){
    public void  onCallStateChanged(int state,String number) {
        super.onCallStateChanged(state, number);

        try {
            if (methodGetActiveFgCallState.invoke(objectCallManager).toString().toLowerCase() .equals("idle"))
            {
                //Toast.makeText(context1, "I am in idle state", Toast.LENGTH_LONG).show();            }
            if (methodGetActiveFgCallState.invoke(objectCallManager).toString().toLowerCase() .equals("active"))
            {
                //Toast.makeText(context1, "I am in active state", Toast.LENGTH_LONG).show();            }

            Toast.makeText(context1, " "+methodGetActiveFgCallState.invoke(objectCallManager).toString(), Toast.LENGTH_LONG).show();


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

    }

}, PhoneStateListener.LISTEN_CALL_STATE);
}

A Toast will appear which will tell you about call state. Find a line which shows Toast.

Saturday, October 3, 2015

Android listen for Incoming and Outgoing calls and block calls automatically in android using java reflection


First of all create a new aidl directory, and add ITelephony.aidl.
ITelephony.aidl file should be like this. Its package name must be same as below.


package com.android.internal.telephony; 
interface ITelephony {

 
   boolean endCall();
    void answerRingingCall();
     void silenceRinger();
 }


Create a new class named PhoneCallReceiver add Add these lines in Manifest.xml

<receiver android:name=".PhoneCallReceiver">
<intent-filter><action android:name="android.intent.action.PHONE_STATE"/></intent-filter>
</receiver>
If you want to enable/disable this broadcast receiver. You can add following code inActivity from where you want to start/stop this call blocking functionality.
extends PhoneCallReceiver class from BroadCastReceiver and implement onReceive method,onReceive method will be called whenever Phone_STATE will be changed which we added as action in intent-filter in manifest file
public void onReceive(Context context, Intent intent) {
    Log.v(TAG, "Receving....");    telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
If statement will be true if there is Incoming Call, if you want to block Outgoing calls
add this code in else body which is below. 
if(intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_RINGING)) {
You can get Caller number using below line of code.
      caller_number = intent.getStringExtra("incoming_number");
       
 try {
           Class c = Class.forName(telephony.getClass().getName()); 
           Method m = c.getDeclaredMethod("getITelephony");
           m.setAccessible(true);
           telephonyService = (ITelephony) m.invoke(telephony);
           telephonyService.endCall();
           Log.d("CallBlocked", "CallBlocked");
           
        }
 catch (Exception e) {
            e.printStackTrace();      
  }

    } else {

        If you want to block Outgoing calls add the above code here...
    }
}

Wednesday, September 30, 2015

asmack Android XMPP Login and Multi User Chat


ConnectionConfiguration config = new ConnectionConfiguration(SERVER_IPADDRESS, SERVER_PORT);
config.setDebuggerEnabled(true);
XMPPConnection connection = new XMPPConnection(config);
SmackConfiguration.setPacketReplyTimeout(100000);
connection.connect();

Now you are connected to server.

ChatManager chatManager = connection.getChatManager();

If you want to create group you have to login to the server using XMPP connection object like below.
connection.login("userName", "Password");

You can also login anonymously like this if your server allows you.
connection.LoginAnonymously();

Log.v("LoggedIn : ", "hammad");


// connection.getRoster().createGroup("hammamd");

If you donot specify correct Domain Name which your server recognize you will get Exception.
like Remote Server Not found or Not Authorised or Service not available.


MultiUserChat multiUserChat = new MultiUserChat(connection,"admin" + "@" + DOMAIN_NAME);

Log.v("Group join : ", "hammad");

This statment will join group with nick name hammad. if no group exist it will create a new group.
multiUserChat.join("hammad");


Than you can add message listner for reading/parsing incoming messages. like below. here you should extract message from packet object by converting it into message type class. 
PacketFilter filter = new MessageTypeFilter(org.jivesoftware.smack.packet.Message.Type.groupchat);connection.addPacketListener(new PacketListener() {
    @Override    public void processPacket(Packet packet) {
        org.jivesoftware.smack.packet.Message message = (org.jivesoftware.smack.packet.Message) packet;        if (message.getBody() != null) {
            String from = message.getFrom();            String Body = message.getBody();            // Add incoming message to the list view or similar        }
    }
}, filter);

with this line a message will be sent to group..

multiUserChat.sendMessage("hi group, I am Hammad");

If you want to get all registered users from server use below code.
You will need this code when you want to sync phone contacts with server, after getting all registered users from server in a list, read your android phone contacts and compare for contacts syncing.
If you want to search for a specific user from server replace * in the code with user name which you want to search.
do not forget to send configurations. use this this link for refrence, how to add configurations.
get Registered users from openfire server.


UserSearchManager search = new UserSearchManager(connection);try {
    Form searchForm = search.getSearchForm("search." + connection.getServiceName());    Form answerForm = searchForm.createAnswerForm();    answerForm.setAnswer("Username", true);    answerForm.setAnswer("search", "*");    System.out.println("search form");    ReportedData data = search.getSearchResults(answerForm, "search." + connection.getHost();    if (data.getRows() != null) {
        Iterator<ReportedData.Row> it = data.getRows();        while (it.hasNext()) {
            
            ReportedData.Row row = it.next();            Iterator iterator = row.getValues("jid");            if (iterator.hasNext()) {
                String value = iterator.next().toString();                user_list.add(value);
                // use variable user_list. List<String> user_list. initialize this variable.

             }
        }
    } else {
             // No contacts Found
    }
} catch (XMPPException e1) {
    // TODO Auto-generated catch block    e1.printStackTrace();}




There is another method of creating and joinning multi user group chat which is available at
below link.

http://stackoverflow.com/questions/32822357/create-persistent-group-in-xmpp-clientusingasmacklibrary-in-android





Thursday, September 10, 2015

Android NFC and Android Beam Tutorial


ABOUT ANDROID NFC:

Below are the few important things you need to know before starting development for P2P communication using Android based NFC devices.

 NFC allows sharing of files/data between devices using wireless technology. Required distance is cm  or less to initiate connection. Maximum distance can be 10 cm.

 Data transmission rate 424 kbits/s.

 Peer to peer communication mode of NFC is known as Android Beam.

Android Beam only works when the application sending the data is running in the foreground and the device receiving the data is unlocked.

Android Beam has two API’s.

NDEF Transfer API (for small data like URL or contact)
File Transfer API (for large data like videos)

User can exchange URL’s, contacts, images, videos.

Both devices can recognize each other and can transmit data simultaneously.

NFC P2P mode communication is available since API level 14 (since 4.0, Ice Cream Sandwich).

Device identifications must be implemented in application protocols, when needed.

In Android Beam, it has two options NFCIP-1 and LLCP.

In NFCIP mode, before starting communication devices can be defined, meaning which device will start communication (initiate) and which device will respond (reply). However in LLCP mode after initial handshake, decision is made by application.

The Android Beam animation is normally is shown when two NFC-capable devices come into range.

If application has to send large data it can hand over connection to Wi-Fi/Bluetooth. This results in faster transfer speeds between devices.
For beaming of specific content, an app is allowed to control the content being sent when adding Android Beam support. If the app does not specify data, beaming the app will open it on the receiving device. If the receiving device does not have the app, it will open the application page in the Play Store.

References:
http://stackoverflow.com/questions/tagged/nfc-p2p
http://open-nfc.org/wp/home/features/
http://code.tutsplus.com/tutorials/sharing-files-with-nfc-on-android--cms-22501
http://www.nfc.cc/2011/12/28/development-android-beam-and-nfc-peer-2-peer/


Kotlin Android MVP Dagger 2 Retrofit Tutorial

http://developine.com/building-android-mvp-app-in-kotlin-using-dagger-retrofit/