title: Android DeadObjectException
body: <p>I have developed my mobile Application based on GSM SMS Communication through the Service Implementation in Android called SmsService.java which use a Receiver as an inner class. In SmsService we use android service that run all time during application runtime. I use it through the use BinderProxy via the use of aidl (Interface Language) it works fine but after some time it will show the Exception Message.I tag the message as well as code for SmsService.java class. Sir please help me how to resolve. thanks in advance and sorry for bad English if not understand..</p>
  
  <p>The Exception log is..</p>
  
  <pre><code>04-24 12:53:04.230: E/SMSReceiver(980): Failed to notify listener aidl.com.services.MessageListener$Stub$Proxy@40528870
  
  04-24 12:53:04.230: E/SMSReceiver(980): android.os.DeadObjectException
  04-24 12:53:04.230: E/SMSReceiver(980):     at android.os.BinderProxy.transact(Native Method)
  
  04-24 12:53:04.230: E/SMSReceiver(980):     at aidl.com.services.MessageListener$Stub$Proxy.handleNewMessage(MessageListener.java:76)
  
  04-24 12:53:04.230: E/SMSReceiver(980):     at com.services.SmsService$SMSReceiver.onReceive(SmsService.java:227)
  04-24 12:53:04.230: E/SMSReceiver(980):     at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:709)
  04-24 12:53:04.230: E/SMSReceiver(980):     at android.os.Handler.handleCallback(Handler.java:587)
  04-24 12:53:04.230: E/SMSReceiver(980):     at android.os.Handler.dispatchMessage(Handler.java:92)
  04-24 12:53:04.230: E/SMSReceiver(980):     at android.os.Looper.loop(Looper.java:130)
  04-24 12:53:04.230: E/SMSReceiver(980):     at android.app.ActivityThread.main(ActivityThread.java:3683)
  04-24 12:53:04.230: E/SMSReceiver(980):     at java.lang.reflect.Method.invokeNative(Native Method)
  04-24 12:53:04.230: E/SMSReceiver(980):     at java.lang.reflect.Method.invoke(Method.java:507)
  04-24 12:53:04.230: E/SMSReceiver(980):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
  04-24 12:53:04.230: E/SMSReceiver(980):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
  04-24 12:53:04.230: E/SMSReceiver(980):     at dalvik.system.NativeStart.main(Native Method)
  </code></pre>
  
  <p>finally the code for the SmsService.java</p>
  
  <pre><code>public class SmsService extends Service {
  
      private SMSReceiver mSMSreceiver;
      private IntentFilter mIntentFilter;
      private DataBaseAdapter dba;
      private String Tag = SmsService.class.getSimpleName();
      public final Object latestSearchResultLock = new Object();
      public List&lt;MessageListener&gt; listeners = new ArrayList&lt;MessageListener&gt;();
      private static  BufferedWriter out;
      private static int id = 0;
      private static int msgId= 0;
      @Override
      public IBinder onBind(Intent arg0) {
          // TODO Auto-generated method stub
          if(SmsService.class.getName().equals(arg0.getAction())){
              Log.d(Tag, "Binding Complete" + arg0);
              return apiEndpoint;
          }else
              return null;
      }
      public SmsService(){        
          /*dba = new DataBaseAdapter(this);*/
          /*dba = DataBaseAdapter.getInstance(this);*/
          mSMSreceiver = new SMSReceiver(this);
          Log.i("On Constructor", "Assign Service");
  
      }
      private final Object findLatest = new Object();
      private MessageQueue&lt;newItem&gt; msgQueue = new MessageQueue&lt;newItem&gt;();
  
      public SmsService getService(){
          return SmsService.this;
      }
  
      private MessageReceiverApi.Stub apiEndpoint = new MessageReceiverApi.Stub(){
  
      @Override
      public void addListener(MessageListener listener) throws RemoteException {
          // TODO Auto-generated method stub
          synchronized(listeners){
              listeners.add(listener);
          }
      }
  
      @Override
      public void removeListener(MessageListener listener) throws RemoteException {
          // TODO Auto-generated method stub
          synchronized (listeners) {
              listeners.remove(listener);
          }
      }
  
      @Override
      public MessageQueue&lt;newItem&gt; getMessageQueueUpdated()
              throws RemoteException {
          // TODO Auto-generated method stub
          synchronized(findLatest){
              return msgQueue;
          }
  
      }   
      };
      @Override
      public void onCreate(){
          super.onCreate();   
          Log.i(Tag, "Service is creating");
          mIntentFilter = new IntentFilter();
          mIntentFilter.addAction(ConstantClass.SMS_RECEIVED);
          registerReceiver(mSMSreceiver,mIntentFilter);       
          Log.i(Tag, "Service is creating Successfully");
      }
      @Override 
      public int onStartCommand(Intent intent , int flags, int type){
          return START_STICKY;
      }   
  
      @Override 
      public void onDestroy(){
          super.onDestroy();  
          unregisterReceiver(mSMSreceiver);   
          /*if(dba!=null)
              DataBaseAdapter.getInstance(this).closeConnection();*/
      }   
      public class SMSReceiver extends BroadcastReceiver {
          /*private DataBaseAdapter dba;*/
          private Context context;
          @SuppressWarnings("unused")
          private String Strsql;
          private SMSSync sync;           
          private UtilityFunction utility;
          private boolean isCrdMatch;
          private String address,Phnumber, msg=null/*,panId =null*/,curMsg=null,mtemp=null;       
          private String devid,incAddr;
          @SuppressWarnings("unused")
          private Handler handle;
          private MessageQueue&lt;newItem&gt; list;
          private newItem item;
          private String Tag = SMSReceiver.class.getSimpleName();     
          public SMSReceiver(Context ctx){
              this.context = ctx;
              list=new MessageQueue &lt;newItem&gt;();
          }
          @Override
          public void onReceive(Context context,final Intent intents){            
              /*dba = new DataBaseAdapter(context);   */
              dba = DataBaseAdapter.getInstance(this.context);
              utility = new UtilityFunction(context);
              sync = new SMSSync(context);        
              if (intents.getAction().equals(ConstantClass.SMS_RECEIVED)) {           
              try{
                  Bundle bundle = intents.getExtras();            
                  if (bundle != null) {                   
                      Object[] pdus = (Object[]) bundle.get("pdus");
                      SmsMessage[] messages = new SmsMessage[pdus.length];
                      for (int i = 0; i &lt; pdus.length; i++)
                          messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);                   
  
                      for (SmsMessage message : messages) {
                          msg = message.getMessageBody();
                          incAddr = message.getOriginatingAddress();
                      }
                      /*Thread.sleep(50);*/                   
                      mtemp = getMessage(msg);
                      if(mtemp!=null){ 
                          item = new newItem(mtemp);
                          list.enqueue(item); 
                          while(!list.isEmpty()){                     
                              curMsg =  list.peek().getItem();                        
                              if(curMsg.startsWith("&lt;") &amp;&amp;  curMsg.endsWith("&gt;")){
                                  msgId = 0;
                                  char mid = curMsg.charAt(3);
                                  msgId = (int )mid;
                                  Log.i(Tag, "message id:="+ msgId);                                                      
                                  //dba.SetSynchronization();
                                  if(msgId==50 || msgId == 54 || msgId == 56 || msgId==65 || msgId == 67 || msgId == 69 || msgId == 75 || msgId == 76){
                                      utility.displayNotification(this.context,curMsg);                                   
                                  }else{                                      
                                      devid = curMsg.substring(4, 20);
                                      /*if(!dba.IsConOpenOrClose())
                                          dba.openRead();*/
                                      Cursor cur = dba.getRecordAcToID(DeviceStorage.TABLE_DEVICE, new String[]{DeviceStorage.Key_AlarmTime },
                                          DeviceStorage.Key_DevID , devid);                               
                                      if(cur.getCount()&gt;0){
                                          cur.moveToFirst();
                                          int almTime = Integer.valueOf(cur.getString(0));
                                          if(almTime==0)
                                              utility.displayNotification(this.context,curMsg);
                                      }
                                  }
                                  /*if(!dba.IsConOpenOrClose())
                                      dba.Open();*/
                                  int count = dba.getDeviceCount(DeviceCurrent.TABLE_CURRENT);                            
                                  if(count&lt;=0){
                                      dba.InsertCurrentCoord(id,id);
                                  }else{
                                      dba.updateCommon(DeviceCurrent.TABLE_CURRENT, DeviceCurrent.Key_ReceiverCoord, DeviceCurrent.Key_ID , Integer.toString(id), Integer.toString(1));   
                                      dba.updateCommon(CoordStore.TABLE_COORD, CoordStore.Key_IsReceiverUpdate, CoordStore.Key_MBID, Integer.toString(1), Integer.toString(id));
                                      Log.i(Tag, "Updateing Coordinator for Receiver");
                                  }   
                                  /*sid = dba.CurrentWorkingCoordinator(DeviceCurrent.Key_SendCoord, 1);*/                                                                                        
                                  Log.i(Tag, "Updateing DataBase Only for Record");       
                                  ConstantClass.IsReadLog=false;
                                  sync.smsProcess(curMsg);                                                        
                                  /*if(msgId==50 &amp;&amp; sid == id){
                                      panId = curMsg.substring(22, 26);
                                      authority = utility.getAuthority(); 
                                      if(authority.equals("A") &amp;&amp; panId.equals("3000")){
                                          ConstantClass.Clear_Main_Screen=false;
                                          ConstantClass.isMainOpen = false;
                                          Intent intent = new Intent(this.context,SettingScreen.class);   
                                          intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK );
                                          context.startActivity(intent);                      
                                      }
                                  }       */
                                  utility.getLicense();
                                  Log.i(Tag, "ConstantClass Log " + String.valueOf(ConstantClass.LOGS));
                                  if(ConstantClass.LOGS){
                                      WriteOnLog(curMsg,1);                                       
                                  }           
                                  abortBroadcast();
                                  /************Now deleting the SMS from the Inbox*********************/                      
                                  removeMessage(this.context, Phnumber);  
                                  list.dequeue();                                         
                              synchronized(listeners){
                                  for (MessageListener listener : listeners) {
                                      try {   
                                          /*listener.notify();*/
                                          listener.handleNewMessage();
                                          /*listener.asBinder();*/
                                          } catch (RemoteException e){
                                              Log.e(Tag, "Failed to notify listener " , e);
                                          }
                                      }
                                  }           
                              }                                       
                          }                   
                      }
                  }
              }catch(Exception e){
                  Toast.makeText(this.context, "On SMS Receiver" + e.getMessage(), Toast.LENGTH_LONG).show();
                  WriteOnLog(curMsg,0);
              } /*catch (Throwable e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }*/finally{
                  /*if(dba.IsConOpenOrClose())
                      dba.close();
                  dba=null;*/
                  utility = null;
                  sync=null;
              }
              }
              if(ConstantClass.Clear_Main_Screen==true &amp;&amp; ConstantClass.isMainOpen == true){
                  Intent intent = new Intent(context,ZigbeeActivity.class);   
                  intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                  context.startActivity(intent);      
              }       
          }   
          private void removeMessage(Context context, String fromAddress) {
              Uri uriSMS = Uri.parse("content://sms/inbox");
              Cursor cursor = null;
              /*if(!dba.IsConOpenOrClose())
                  dba.Open();*/
              try{
              cursor = context.getContentResolver().query(uriSMS, null, null, null, null);
              cursor.moveToFirst();
              if(cursor.getCount() &gt; 0){ 
                  int ThreadId = cursor.getInt(1);                     
                  context.getContentResolver().delete(Uri.parse("content://sms/conversations/"+ThreadId), "address=?",new String[]{fromAddress});
                  Log.d("Message Thread Deleted", fromAddress);         
                  }         
  
              }catch(Exception e){
              Log.e("remove Message", e.getMessage());
              }finally{
                  if(cursor!=null)
                      cursor.close();   
                  /*if(dba.IsConOpenOrClose())
                      dba.close();*/
              }
          }       
      private String getMessage(String msg){
          String newMsg = null;
          try{
              int tl = incAddr.length();
              int l = tl - ConstantClass.NO;
              address = incAddr.substring(l,tl);
              isCrdMatch = MatchCoord(address);                           
              if(isCrdMatch == true) {                                
                  if(msg.startsWith("&lt;") &amp;&amp; msg.contains("&gt;")){                   
                      int len = Integer.valueOf(msg.substring(1, 3), 16).intValue();
                      int index = msg.indexOf("&gt;");
                      Log.i(Tag, "Value is:" + len);
                      Log.i(Tag, "index value is:" + index);
                      if(len==index+1){
                          newMsg = msg.substring(0, len); //getting the length of the whole message and except the Garbage / 
                          Log.i(Tag, "receiving msg length is:=" + len);
                          Log.i(Tag, "receiving msg is:=" + newMsg);
                          return newMsg;  
                      }else{
                          Toast.makeText(this.context, "message Corrupt" + address, Toast.LENGTH_LONG).show();
                      }
                  }
              }
          }catch(Exception e){
              e.printStackTrace();
          }
          return newMsg;
      }
          private boolean MatchCoord(String no){
              boolean isMatched = false;
              String crdNo = null;
              Cursor cursor = null;           
              try{
              cursor = dba.SelectCommon(CoordStore.TABLE_COORD, new String[]{CoordStore.Key_MBID,CoordStore.Key_MbNo}, 
                      CoordStore.Key_MbNo , new String[]{no});
              if(cursor.getCount()&gt;0)
                  cursor.moveToFirst();
              do{
                  crdNo = cursor.getString(cursor.getColumnIndex(CoordStore.Key_MbNo));
                  if(crdNo.equals(no)){               
                      id = cursor.getInt(cursor.getColumnIndex(CoordStore.Key_MBID));
                      Phnumber = crdNo;
                      Log.i(Tag, "Crd No is:" + Phnumber);
                      isMatched = true;
                      break;
                  }
              }while(cursor.moveToNext());            
              }catch(Exception e){
                  Log.e(Tag, e.getMessage());
              }finally{
                  if(cursor!=null)
                      cursor.close();
              }
              return isMatched;
          }
          private void WriteOnLog(String msg,int crpt){
              File exportDir =  new File("/sdcard/CIH");     
              if (!exportDir.exists())          {              
              exportDir.mkdirs();          
              }   
              String fileName;            
                  fileName = "log" + ".txt";          
              File file = new File(exportDir,fileName); 
              String txt=null ;
              try {
                  if(!file.exists()){
                      file.createNewFile();
                      FileWriter Write = new FileWriter(file,true);
                      out = new BufferedWriter(Write);
                      txt = "Date Time |" + " Send/Receive |" + " Controller No |" + " Success |" +" Message " + " | Corrupt";
                       out.write( txt + "\r\n" );
                       out.flush();
                       out.close();
                  }
                  /*FileWriter Write = new FileWriter(file,true); 
                  out = new BufferedWriter(Write);*/
                  //txt = "Date Time |" + " Send/Receive |" + " Controller No |" +" Message " ;
                  String header = "Date Time |" + " Send/Receive |" + " Controller No |" + " Success |" +" Message " + "| Corrupt \r\n" ;
                  String dd=null,mm=null,yy=null,hh=null,min=null,ss=null,dt=null;    
                  SimpleDateFormat sdfDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
                  String newtime =  sdfDateTime.format(new Date(System.currentTimeMillis()));             
                  yy = newtime.substring(2, 4);
                  mm = newtime.substring(5, 7);
                  dd = newtime.substring(8, 10);
                  hh = newtime.substring(11, 13);
                  min = newtime.substring(14, 16);
                  ss = newtime.substring(17); 
                  dt = dd+"-"+mm+"-"+yy +" " + hh + ":" + min +":"+ ss;
                  if(crpt == 0)
                      txt = dt + " | " +" Receive " + "| " + address + " | " + " Successfull |" + msg.toUpperCase() +" | " + " Yes \r\n" ;
                  else
                      txt = dt + " | " +" Receive " + "| " + address + " | " + " Successfull |" + msg.toUpperCase() + "| No \r\n"; 
  
                  prepend(file.getAbsolutePath(),txt,header);
                  /*out.write( txt + "\n");       
                  out.flush();*/          
              }          
              catch(IOException sqlEx)  {              
              Log.e("MainActivity", sqlEx.getMessage(), sqlEx);        
              }   
          }
          public  void prepend(String filename,String data,String Header) throws IOException{
  
               BufferedReader in = new BufferedReader(new FileReader(filename));
               StringBuilder reply = new StringBuilder();
  
               String str = new String();     
               reply.append(Header);       
               //////////now appending the data that current sms /////////
               reply.append(data);
               int i = 0;
               while( (str = in.readLine())!=null ){
                   if(i!=0)
                       reply.append(str + "\r\n");
                 i++;
               }
  
               str = reply.toString();
               BufferedWriter out= new BufferedWriter(new FileWriter(filename));
               out.write(str);        
  
               if(in !=null){
               try{ 
                   in.close();
                   } catch(IOException e){
                   e.printStackTrace();
                   }
               if(out!=null)
                  try{
                      out.close();
                  } catch(IOException ex) {
                      ex.printStackTrace();
                  }
              }
              }       
          }
      }
  </code></pre>