I am trying to develop an android app to measure QoS of networks. The app sends UDP packets to a UDP server running on my system. Since this is a long running process, I have implemented the UDP connection in a class which extends IntentService.The reason behind using IntentService is that I need to pass some parameters to the Service. I have a BroadcastReceiver in my activity which listens for messages from the IntentService and prints it. My problem is that although the IntentService is running smoothly, but the activity is not receiving the messages from it. I am new to android development, so please excuse my lack of understanding and any guidance/suggestions will be deeply appreciated. I am posting some parts of my code below. The Logcat does not show any errors.
I have seen intent.setAction() method being used in some examples, but I am not very clear about how to use it in my case.
The BroadcastReceiver (defined within my Activity class)
public class UdpResponseReceiver extends BroadcastReceiver {
public static final String ACTION_RESP = "com.example.udpmessageclient.intent.action.MESSAGE_PROCESSED";
#Override
public void onReceive(Context context, Intent intent) {
System.out.println(UdpService.PARAM_OUT_MSG);
}
I have registered the receiver:
IntentFilter filter = new IntentFilter(UdpResponseReceiver.ACTION_RESP);
filter.addCategory(Intent.CATEGORY_DEFAULT);
receiver = new UdpResponseReceiver();
registerReceiver(receiver, filter);
IntentService class:
public class UdpService extends IntentService {
//..variable declarations
public UdpService() {
// TODO Auto-generated constructor stub
super("UdpService");
}
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
host = intent.getStringExtra("host");
port = intent.getIntExtra("port", 4000);
pType= intent.getIntExtra("pType", 0);
delay = intent.getIntExtra("delay", 0);
msg= intent.getStringExtra("msg");
broadcastIntent = new Intent();
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
broadcastIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
try {
addr = InetAddress.getByName(host);
// addr=InetAddress.getLocalHost();
socket = new DatagramSocket();
// socket.connect(addr,port);
System.out.println("\nSocket Connected");
} catch (Exception e) {
System.out.println("\nConnection failed");
return;
}
send=true;
switch (pType) {
case 0:
while (send) {
sendPacket(msg);
}
case 1:
while (send) {
try {
Thread.currentThread().sleep(delay);
} catch (Exception e) {
}
sendPacket(msg);
}
case 2:
while (send) {
int u = want(30);
String data1 = "";
while ((u--) > 0)
data1 = data1 + msg;
sendPacket(data1);
}
case 3:
while (send) {
int u = want(30);
System.out.println(u);
String data1 = "";
while ((u--) > 0)
data1 = data1 + msg;
System.out.println("data length :" + data1.length());
try {
Thread.currentThread().sleep(delay);
} catch (Exception e) {
}
sendPacket(data1);
}
}
}
public void onDestroy(){
super.onDestroy();
send=false;
socket.close();
socket=null;
}
void sendPacket(String text) {
try {
System.out.println("\nClient:: Sending packet: " + " to " + addr
+ port);
byte[] data = text.getBytes();
spacket = new DatagramPacket(data, data.length, addr, port);
socket.send(spacket);
String resultTxt="Sent Packet at:"+DateFormat.format("MM/dd/yy h:mmaa", System.currentTimeMillis());
// this is where I am trying to send message back to the activity
broadcastIntent.putExtra(PARAM_OUT_MSG, resultTxt);
sendBroadcast(broadcastIntent);
} catch (Exception e) {
System.out.println("Error:" + e.getMessage());
e.printStackTrace();
return;
}
}
}
logcat error messages when the service is stopped:
01-14 15:53:41.446: W/System.err(1176): java.lang.NullPointerException
01-14 15:53:41.456: W/System.err(1176): at com.example.udpmessageclient.UdpService.sendPacket(UdpService.java:123)
01-14 15:53:41.466: W/System.err(1176): at com.example.udpmessageclient.UdpService.onHandleIntent(UdpService.java:74)
01-14 15:53:41.466: W/System.err(1176): at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
01-14 15:53:41.466: W/System.err(1176): at android.os.Handler.dispatchMessage(Handler.java:99)
01-14 15:53:41.466: W/System.err(1176): at android.os.Looper.loop(Looper.java:137)
01-14 15:53:41.476: W/System.err(1176): at android.os.HandlerThread.run(HandlerThread.java:60)
Change the code of UdpService as ...
broadcastIntent = new Intent(UdpResponseReceiver.ACTION_RESP); // You forgot to add your custom intent filter
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
//broadcastIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); // I don't think you really need it. So you can remove this flag.
UPDATE
public static final String ACTION_RESP = "com.example.udpmessageclient.intent.action.MESSAGE_PROCESSED";
private final BroadcastReceiver UdpResponseReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//TODO handle results
}
};
And register it as
registerReceiver(UdpResponseReceiver, new IntentFilter(ACTION_RESP))
Related
I have a classe for download files by an executor :
this.getFreshGoolgletoken(new CallBackTokenRefresh() {
#Override
public void getFreshGoogleToken(String token,String userEmail) {
ArrayList<ExecuteSynchroneRequest> mesRequetes = new ArrayList<>();
Intent mServiceIntent = new Intent(context, TraitementPermisLoaded.class);
for (CollectionPermis permis : collectionPermis){
// stocker les permis + les s3Key
int revision = permis.revision;
final String uuid = permis.uuid;
Log.i(LOG_TAG,"synchro OnLoop permis num & revision :"+uuid+"/"+revision);
Map<String,String> params = new HashMap<>();
params.put("uuid",uuid);
params.put("revision",String.valueOf(revision));
mesRequetes.add(new ExecuteSynchroneRequest(AwsEworkPermitsRoutes.PERMITS,params,context,token,apiClient,uuid,handler,mServiceIntent,callBack));
}
ExecutorService execute = Executors.newSingleThreadExecutor();
for(Runnable r : mesRequetes){
execute.execute(r);
}
execute.shutdown();
}
In this methode i have an IntentService(mServiceIntent) for handle a long treatement on my download. My executor class handle intentService like this in switch command :
case PERMITS:
if(mServiceIntent == null) break;
mServiceIntent.setData(Uri.parse(responseData));
mServiceIntent.putExtra("myHandler", new Messenger(handler));
mServiceIntent.putExtra("ptUuid", uuid);
context.startService(mServiceIntent);
break;
mServiceIntent Class is :
public class TraitementPermisLoaded extends IntentService {
static final String LOG_TAG = "ewp-executor ";
SharedPreferences sharedPreferences;
Handler handler;
public TraitementPermisLoaded() {
super("TraitementPermisLoaded");
setIntentRedelivery(true);
Log.i(LOG_TAG," service traitement permis called 2 ");
}
#Override
protected void onHandleIntent(Intent workIntent) {
this.sharedPreferences = getApplicationContext().getSharedPreferences("DATA", Context.MODE_PRIVATE);
// Gets data from the incoming Intent
String responseData = workIntent.getDataString();
Messenger messenger = null;
String ptUuid = "";
Bundle extras=workIntent.getExtras();
if (extras!=null) {
messenger=(Messenger)extras.get("myHandler");
ptUuid = extras.getString("ptUuid");
}
String permisUuid = "";
PtWrapper pt = null;
try {
ObjectMapper mapper = new ObjectMapper();
pt = mapper.readValue(responseData, PtWrapper.class);
HandleJson handleJson = HandleJson.getInstance(getApplicationContext());
permisUuid = pt.getPermisTravailFormContext().permisTravail.uuid;
if (permisUuid != null) {
handleJson.writeInInterneFileSysteme(sharedPreferences.getString("email",null),pt, permisUuid);
} else {
throw new HandleJsonNoPermisException("le UUID est null on ne peut pas enregistrer ce permis");
}
handleJson.setKpi(pt);
Message message = Message.obtain();
Bundle bundle= new Bundle();
bundle.putString("myevent", "un permis ok");
message.setData(bundle);
messenger.send(message);
} catch (IOException e) {
Log.i(LOG_TAG, e.getMessage());
e.printStackTrace();
Message message = Message.obtain();
Bundle bundle= new Bundle();
bundle.putString("error", ErrorsCodes.CODE_40.toString()+" / permit uuid : "+ptUuid);
message.setData(bundle);
try {
messenger.send(message);
} catch (RemoteException e1) {
e1.printStackTrace();
Log.i(LOG_TAG,"erreur messager : "+e1.getMessage());
}
} catch (HandleJsonNoPermisException e) {
Log.i(LOG_TAG, e.getMessage());
e.printStackTrace();
} catch (RemoteException e) {
Log.i(LOG_TAG,e.getMessage());
e.printStackTrace();
}catch(Exception e){
Log.i(LOG_TAG,e.getMessage());
e.printStackTrace();
}
}
}
I load 27 files but only 14 get a treatment, the Intentservice stop to work, it'seems to be after activity change but not sure. After loaded files, I change my activity by another, but intentService get all request in the queue. I have use IntentService because it will finish working all process before stopping?
What did I do wrong?
Thanks
the error source is the size of data in myService.setData(mydata>250ko). For all data more than 250 ko the service stop with this error message :
A/ActivityManager: Service done with onDestroy, but executeNesting=2:
ServiceRecord{5c8e958 u0
com.alit.aws.android.eworkpermit/.lib.TraitementPermisLoaded
There is another way to pass large data more than 250 k to my intentService ? I have tried :
->mServiceIntent.setData(Uri.parse(responseData));
->mServiceIntent.putExtra("myData",responseData);
I have found a solution, remove the "setData(responseData)" and replace it by a globalHasMap. After the end of treatment I remove item in hashMap.
May be it's not awesome but i have not found a better solution.
If someone can show me a better way, do it ;-)
Thanks
I am using following UsbSerial example from below link https://github.com/felHR85/SerialPortExample. I want receive data from over usb from the device shown in the photo.
Device is basically a counter machine which is sending counter data over serial port.
I am able to connect device and open port from it but unable to read data stream from it. Below is the code used. code is not giving any error
Mainactivity class
public class MainActivity extends AppCompatActivity {
/*
* Notifications from UsbService will be received here.
*/
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case UsbService.ACTION_USB_PERMISSION_GRANTED: // USB PERMISSION GRANTED
Toast.makeText(context, "USB Ready", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_PERMISSION_NOT_GRANTED: // USB PERMISSION NOT GRANTED
Toast.makeText(context, "USB Permission not granted", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_NO_USB: // NO USB CONNECTED
Toast.makeText(context, "No USB connected", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_DISCONNECTED: // USB DISCONNECTED
Toast.makeText(context, "USB disconnected", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_NOT_SUPPORTED: // USB NOT SUPPORTED
Toast.makeText(context, "USB device not supported", Toast.LENGTH_SHORT).show();
break;
}
}
};
private UsbService usbService;
private TextView display;
private EditText editText;
private MyHandler mHandler;
private final ServiceConnection usbConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
usbService = ((UsbService.UsbBinder) arg1).getService();
usbService.setHandler(mHandler);
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
usbService = null;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHandler = new MyHandler(this);
display = (TextView) findViewById(R.id.textView1);
editText = (EditText) findViewById(R.id.editText1);
Button sendButton = (Button) findViewById(R.id.buttonSend);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!editText.getText().toString().equals("")) {
String data = editText.getText().toString();
if (usbService != null) { // if UsbService was correctly binded, Send data
display.append(data);
usbService.write(data.getBytes());
}
}
}
});
}
#Override
public void onResume() {
super.onResume();
setFilters(); // Start listening notifications from UsbService
startService(UsbService.class, usbConnection, null); // Start UsbService(if it was not started before) and Bind it
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(mUsbReceiver);
unbindService(usbConnection);
}
private void startService(Class<?> service, ServiceConnection serviceConnection, Bundle extras) {
if (!UsbService.SERVICE_CONNECTED) {
Intent startService = new Intent(this, service);
if (extras != null && !extras.isEmpty()) {
Set<String> keys = extras.keySet();
for (String key : keys) {
String extra = extras.getString(key);
startService.putExtra(key, extra);
}
}
startService(startService);
}
Intent bindingIntent = new Intent(this, service);
bindService(bindingIntent, serviceConnection, Context.BIND_AUTO_CREATE);
}
private void setFilters() {
IntentFilter filter = new IntentFilter();
filter.addAction(UsbService.ACTION_USB_PERMISSION_GRANTED);
filter.addAction(UsbService.ACTION_NO_USB);
filter.addAction(UsbService.ACTION_USB_DISCONNECTED);
filter.addAction(UsbService.ACTION_USB_NOT_SUPPORTED);
filter.addAction(UsbService.ACTION_USB_PERMISSION_NOT_GRANTED);
registerReceiver(mUsbReceiver, filter);
}
/*
* This handler will be passed to UsbService. Data received from serial port is displayed through this handler
*/
private static class MyHandler extends Handler {
private final WeakReference<MainActivity> mActivity;
public MyHandler(MainActivity activity) {
mActivity = new WeakReference<>(activity);
}
#Override
public void handleMessage(Message msg) {
mActivity.get().display.append("Handle:");
switch (msg.what) {
case UsbService.MESSAGE_FROM_SERIAL_PORT:
String data = (String) msg.obj;
mActivity.get().display.append(data);
break;
}
}
}
}
I know it's bit late, however just to help others who might come across similar issue, did you find solution to your problem? If not, I cannot see the other java file corresponding to the service (USBService.java) as described in the example referred by you. The same file contains following code snippet which you would like to debug to find out what's going wrong (could be a problem with byte to string conversion or so). Hope this helps.
/*
* Data received from serial port will be received here. Just populate onReceivedData with your code
* In this particular example. byte stream is converted to String and send to UI thread to
* be treated there.
*/
private UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback()
{
#Override
public void onReceivedData(byte[] arg0)
{
try
{
String data = new String(arg0, "UTF-8");
if(mHandler != null)
mHandler.obtainMessage(MESSAGE_FROM_SERIAL_PORT,data).sendToTarget();
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
};
Is there any way to directly communicate with a WallpaperService from an Activity? It doesn't look like I can use the normal service communication classes because the onBind method is declared final in the WallpaperService class I'm extending. Worth noting that I'm referring to my WallpaperService not any.
Any workarounds if this isn't possible?
My solution was to use local sockets. I created an instance of a LocalServerSocket in the constructor of my wallpaper's Engine. Here's a quick implementation. Server runs on a separate thread and is directly tied to the lifecycle of MyEngine. The thread will stop when continueSocket is set to false. This happens onDestroy. Problem is that LocalServerSocket.accept() blocks until there's something to do. The workaround is to send a message to our own server so it will run through the loop again and check continueSocket (which is now false), closing the server. Check the closeSocketServer method. I have it running in onDestroy in the example but you might want to use it elsewhere like onSurfaceDestroyed and add your own sanity checks.
public class MyWallpaperService extends WallpaperService {
#Override
public Engine onCreateEngine() {
return new MyEngine();
}
private class MyEngine extends Engine {
private boolean continueSocket = true;
MyEngine() {
new Thread() {
#Override
public void run() {
try {
LocalServerSocket server = new LocalServerSocket("MyAddress");
Log.d("SERVER READY", "Server is ready.");
while(continueSocket) {
LocalSocket receiver = server.accept();
if(receiver != null) {
InputStream input = receiver.getInputStream();
byte[] data = IOUtils.toByteArray(input);
Log.d("GOT DATA", new String(data));
}
}
server.close();
} catch (IOException ex) {
Log.wtf("IOEXCEPTION", ex);
}
}
}.start();
}
#Override
public void onDestroy() {
closeSocketServer();
super.onDestroy();
}
private void closeSocketServer() {
continueSocket = false;
try {
LocalSocket socket = new LocalSocket();
socket.connect(new LocalSocketAddress("MyAddress"));
socket.getOutputStream().write(new byte[0]);
socket.getOutputStream().close();
socket.close();
} catch (IOException ex) {
//
}
}
}
}
And in my Activity it can be as simple as this...
try {
LocalSocket sender = new LocalSocket();
sender.connect(new LocalSocketAddress("MyAddress"));
String data = "Hello world!";
Log.d("SENT DATA", data);
sender.getOutputStream().write(data.getBytes());
sender.getOutputStream().close();
sender.close();
} catch (IOException ex) {
Log.wtf("IOEXCEPTION", ex);
}
Logcat ends up looking like this:
D/SERVER READY﹕ Server is ready. (when the wallpaper starts up)
D/SENT DATA﹕ Hello world! (when the activity sends data)
D/GOT DATA﹕ Hello world! (when the wallpaper gets the data)
In your WallpaperService onCreateEngine:
IntentFilter intentFilter = new IntentFilter("your.package.your.action");
MyBroadcastReceiver mReceiver = new MyBroadcastReceiver(mRenderer);
LocalBroadcastManager.getInstance(getApplicationContext())
.registerReceiver(mReceiver, intentFilter);
In mRenderer's class:
public void receiveCommand(int i) {
Log.d("got", String.valueOf(i));
}
Receiver class:
public class MyBroadcastReceiver extends BroadcastReceiver {
private final MyRenderer _mRenderer;
public MyBroadcastReceiver(MyRenderer mRenderer) {
_mRenderer = mRenderer;
}
#Override
public void onReceive(Context context, Intent intent) {
_mRenderer.receiveCommand(intent.getExtra("msg", -1));
}
}
Now call from activity:
Intent in = new Intent();
in.setAction("your.package.your.action");
in.setExtra("msg", 42);
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(in);
My application has a database where queued items will be stored if it doesn't notice any connectivity to Wifi or mobile network, like 3G og 4G. My problem is:
I have a BroadcastReciever which is registrered this way:
#Override
public void onResume() {
super.onResume();
if(networkMonitor == null)
networkMonitor = new CaseQueueReceiver();
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(networkMonitor, filter);
}
My BroadcastReciever is starting a Service to pick out items from this database and send them over either a webservice or mail. My BrodcastReciever is like this:
public class CaseQueueReceiver extends BroadcastReceiver {
boolean available;
QueueDB queueDB;
int count;
public CaseQueueReceiver() {
queueDB = new QueueDB(ContextHelper.context());
count = queueDB.countUnsentCases();
}
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
NetworkInfo info = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
String typeName = info.getTypeName();
String subtypeName = info.getSubtypeName();
available = info.isAvailable();
Log.i("Network Monitor", "Network Type: " + typeName + ", subtype: " + subtypeName + ", available: " + available);
if (available && count > 0) {
Intent service = new Intent(context, SendQueuedCasesService.class);
context.startService(service);
}
}
}
}
As you can see if the internet connection is available and the database contains something, I will start a service to send these items in the database.
My Service looks like this:
public class SendQueuedCasesService extends Service {
boolean available;
DatabaseHandler db;
QueueDB queueDB;
HashMap<String, String> queueHashMap;
CreateTransaction transaction;
String pcn, file;
int sent;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
db = new DatabaseHandler(ContextHelper.context());
queueDB = new QueueDB(ContextHelper.context());
queueHashMap = new HashMap<String, String>();
transaction = new CreateTransaction(ContextHelper.context());
queueDB = new QueueDB(this);
int count = queueDB.countUnsentCases();
Log.w("Unsent cases count: ", Integer.toString(count));
if (count > 0) {
queueHashMap = queueDB.getUnsetCases();
Iterator<Entry<String, String>> it = queueHashMap.entrySet().iterator();
while(it.hasNext()) {
Map.Entry pairs = it.next();
pcn = pairs.getKey().toString();
Log.w("PCN in Queued Cases: ", pcn);
file = pairs.getKey().toString();
Log.w("Nist File Path: ", file);
try
{
sent = transaction.createTransaction(pcn, file);
if(sent == -2)
{
queueDB.deleteUnSentCase(pcn);
db.updateDB(pcn, "");
}
else
break;
} catch(MailException e) {
Log.e("MailException: ", e.getMessage());
}
}
Intent i = new Intent(this, WorkflowChooser.getCurrentWorkflow());
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
}
}
My problem is that when I start the application this will block the UI for a while and then show the UI. A other problems is that this service isn't triggered if I turn off and the on the WiFi again. Why is this happening?
My problem is that when I start the application this will block the UI for a while and then show the UI.
Service runs in UI thread. That's the problem.
You can try to use IntentService. It will handle all the threading for you automatically.
You should create an AsyncTask or a new thread which handles the Service.
I want to block a specific phone number that is in my database
I do a comparison between the number the user dialed, and the number in memory. If they are equal, I block the call.
My code:
public void onReceive(Context context, Intent intent) {
PlaceDataSQL placeDataSQL =new PlaceDataSQL(context);
ArrayList<String> getUsersPhoneNumbers= placeDataSQL.getUsersPhoneNumbers();
//TODO
//===========
//here I need to check the number
Bundle b = intent.getExtras();
String incommingNumber = b.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
//String outGoingNumber = b.getString(TelephonyManager.);
Boolean find=false;
try {
for(int i=0;i<getUsersPhoneNumbers.size();i++)
{
if(incommingNumber.equals(getUsersPhoneNumbers.get(i)))
{
find=true;
break;
}
}
} catch (Exception e) {
incommingNumber="";
}
// ========================================
//here the problem
//=========================================
String phonenumber=b.getString(Intent.EXTRA_PHONE_NUMBER);
try {
for(int i=0;i<getUsersPhoneNumbers.size();i++)
{
if(phonenumber.equals(getUsersPhoneNumbers.get(i)))
{
find=true;
break;
}
}
if (!find)
return;
}catch (Exception e) {
phonenumber="";
}
if (!find)
return;
/* examine the state of the phone that caused this receiver to fire off */
String phone_state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if (phone_state.equals(TelephonyManager.EXTRA_STATE_RINGING))
{
logMe("Phone Ringing: the phone is ringing, scheduling creation call answer screen activity");
Intent i = new Intent(context, CallAnswerIntentService.class);
i.putExtra("delay", 100L);
i.putExtra("number", incommingNumber);
context.startService(i);
logMe("Phone Ringing: started, time to go back to listening");
}
if (phone_state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK))
{
Intent i = new Intent(context,InCallScreenGuardService.class);
i.putExtra("delay", 100L);
i.putExtra("number", phonenumber);
logMe("Phone Offhook: starting screen guard service");
context.startService(i);
}
if (phone_state.equals(TelephonyManager.EXTRA_STATE_IDLE))
{
Intent i = new Intent(context,InCallScreenGuardService.class);
logMe("Phone Idle: stopping screen guard service");
context.stopService(i);
}
return;
}
The problem:
I can get incoming numbers but I can't get outgoing numbers?
You will need a BroadcastReciever for this.
public class OutgoingCallReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if(null == bundle)
return;
String phonenumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
Log.i("OutgoingCallReceiver",phonenumber);
Log.i("OutgoingCallReceiver",bundle.toString());
String info = "Detect Calls sample application\nOutgoing number: " + phonenumber;
Toast.makeText(context, info, Toast.LENGTH_LONG).show();
}
}