2014-02-24 129 views
1

我正在开发一个应用程序,通过web服务发送有关最后拨打的号码,呼叫状态和呼叫持续时间的信息。Android服务重新启动,但应用程序没有

该应用程序工作得很好,但是当设备关闭应用程序时,android服务会重新启动,但活动不会启动。

我确信的方式是当服务启动时我有Toasts:“Servicio TRUCKA iniciado”和“Servicio TRUCKA creado”告诉我服务已经创建并开始。

当信息发送到web服务时,我有面包说:“Enviandoinformación...”和“Informaciónenviada”。

但是,当应用程序关闭时(通过自动关闭应用程序的android任务管理器),来自服务“Servicio TRUCKA iniciado”和“Servicio TRUCKA creado”的消息确实出现,但来自信息发送部分的敬酒不会。

我希望有人能帮助我,告诉我做错了什么? :)

这是我的活动:

package com.trucka.llamadasdrivers; 

import java.text.DateFormat; 
import java.util.Calendar; 
import java.util.Date; 

import com.trucka.llamadasdrivers.R; 

import android.annotation.SuppressLint; 
import android.app.Activity; 
import android.app.AlarmManager; 
import android.app.PendingIntent; 
import android.content.Context; 
import android.content.Intent; 
import android.database.Cursor; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.provider.CallLog; 
import android.widget.TextView; 
import android.widget.Toast; 
import android.telephony.*; 
import android.util.Log; 

import java.text.SimpleDateFormat; 
import org.ksoap2.SoapEnvelope; 
import org.ksoap2.serialization.PropertyInfo; 
import org.ksoap2.serialization.SoapObject; 
import org.ksoap2.serialization.SoapSerializationEnvelope; 
import org.ksoap2.transport.HttpTransportSE; 

public class ActividadLlamadasDrivers extends Activity { 
    TextView txtInformacion = null; 
    TextView txtDetalles = null; 
    TextView tv = null; 
    // Comunicación con el webservice. 
    private final String NAMESPACE = "http://truckanet.com/MensajeOperador"; 
    // private final String URL = 
    // "http://192.168.10.94/MensajeOperador/MensajeOperador.asmx"; 
    private final String URL = "http://200.76.187.148/MensajeOperador/MensajeOperador.asmx"; 
    private final String SOAP_ACTION = "http://truckanet.com/MensajeOperador/ActualizarFede"; 
    private final String METHOD_NAME = "ActualizarFede"; 
    private String TAG = "TRUCKA_DRIVERS"; 
    private String resultado; 
    String phNumber = null; 
    String callType = null; 
    String callDate = null; 
    DateFormat shortFecha = null; 
    DateFormat shortDF = null; 
    Date callDayTime = null; 
    Date fin = null; 
    String fechaLlamada1 = null; 
    String fechaLlamada2 = null; 
    String callDuration = null; 
    String dir = null; 
    public String tolo = null; 
    String imei = null; 
    String comentario = null; 
    String fechaRegistro = null; 
    String insercion = null; 
    String fechaInicio = null; 
    String fechaFin = null; 
    String estadoLlamada = null; 
    int reinicios = 0; 

    @Override 
    public void onBackPressed() { 

    } 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_actividad_llamadas_drivers); 

     if (!ServicioLlamadas.isRunning()) { 
      reinicios ++; 
      Toast.makeText(getApplicationContext(), Integer.toString(reinicios) , Toast.LENGTH_LONG).show(); 
      Intent in = new Intent(ActividadLlamadasDrivers.this, 
        ServicioLlamadas.class); 
      ActividadLlamadasDrivers.this.startService(in); 
      TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); 
      TelephonyMgr.listen(new TeleListener(), 
        PhoneStateListener.LISTEN_CALL_STATE); 
      tv = (TextView) findViewById(R.id.txvEstadoServicio); 
      txtInformacion = (TextView) findViewById(R.id.textview_call); 
      txtDetalles = (TextView) findViewById(R.id.textview_call2); 
     } 

    } 

    class TeleListener extends PhoneStateListener { 

     private boolean telefonoLlamando = false; 
     @Override 
     public void onCallStateChanged(int state, String incomingNumber) { 

      if (TelephonyManager.CALL_STATE_RINGING == state) { 
       // phone ringing 
      } 

      if (TelephonyManager.CALL_STATE_OFFHOOK == state) { 
       // active 
       //getCallDetails(); 
       telefonoLlamando = true; 
       Toast.makeText(getApplicationContext(), 
         "Enviando información...", Toast.LENGTH_SHORT).show(); 
      } 

      if (TelephonyManager.CALL_STATE_IDLE == state) { 
       // run when class initial and phone call ended, 
       // need detect flag from CALL_STATE_OFFHOOK 
       Toast.makeText(getApplicationContext(), 
         "Información enviada.", Toast.LENGTH_SHORT).show(); 
       if (telefonoLlamando) { 


        // restart app 
        getCallDetails(); 

        telefonoLlamando = false; 
       } 

      } 
     } 
    } 

    // Obtener la fecha actual del teléfono. 
    public long getTodayTimestamp() { 
     Calendar c1 = Calendar.getInstance(); 
     c1.setTime(new Date()); 

     Calendar c2 = Calendar.getInstance(); 
     c2.set(Calendar.YEAR, c1.get(Calendar.YEAR)); 
     c2.set(Calendar.MONTH, c1.get(Calendar.MONTH)); 
     c2.set(Calendar.DAY_OF_MONTH, c1.get(Calendar.DAY_OF_MONTH)); 
     c2.set(Calendar.HOUR_OF_DAY, 0); 
     c2.set(Calendar.MINUTE, 0); 
     c2.set(Calendar.SECOND, 0); 

     return c2.getTimeInMillis(); 
    } 

    // Obtener el detalle de las llamadas con la fecha actual. 
    @SuppressLint("SimpleDateFormat") 
    private void getCallDetails() { 
     String timestamp = String.valueOf(getTodayTimestamp()); 
     StringBuffer sb = new StringBuffer(); 
     @SuppressWarnings("deprecation") 
     Cursor managedCursor = managedQuery(CallLog.Calls.CONTENT_URI, null, 
       CallLog.Calls.DATE + ">= ?", new String[] { timestamp }, null); 
     int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER); 
     int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE); 
     int date = managedCursor.getColumnIndex(CallLog.Calls.DATE); 
     int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION); 
     sb.append("Bitácora de llamadas :"); 
     Integer contador = 0; 
     // while (managedCursor.moveToNext()) { 
     // managedCursor.moveToFirst(); 
     managedCursor.moveToLast(); 
     contador = contador + 1; 
     phNumber = managedCursor.getString(number); 
     callType = managedCursor.getString(type); 
     callDate = managedCursor.getString(date); 
     shortFecha = DateFormat.getDateInstance(DateFormat.SHORT); 
     shortDF = DateFormat.getTimeInstance(DateFormat.SHORT); 
     callDayTime = new Date(Long.valueOf(callDate)); 
     fechaLlamada1 = shortDF.format(callDayTime); 
     fechaLlamada2 = shortFecha.format(callDayTime); 
     callDuration = managedCursor.getString(duration); 
     int dircode = Integer.parseInt(callType); 
     TelephonyManager mngr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); 
     switch (dircode) { 
     case CallLog.Calls.OUTGOING_TYPE: 
      dir = "Saliente"; 
      break; 

     case CallLog.Calls.INCOMING_TYPE: 
      dir = "Entrante"; 
      break; 

     case CallLog.Calls.MISSED_TYPE: 
      dir = "Perdida"; 
      break; 
     } 

     imei = mngr.getDeviceId(); 
     comentario = dir; 
     fechaRegistro = fechaLlamada2; 
     DateFormat df = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss"); 
     String ahorita = df.format(callDayTime); 
     fechaInicio = ahorita.toString(); 
     // fechaFin = 
     // df.format(callDayTime.setSeconds(callDayTime.getSeconds()+5)); 

     insercion = "DECLARE @claveDriver INT, @nombreDriver VARCHAR(max), @evento VARCHAR(max), @duracion int, @inicial varchar(max) " 
       + "SET @claveDriver = (SELECT cve_tra FROM SISTEMA.dbo.TELEFONOS WHERE IMEI_SIM = '" 
       + mngr.getDeviceId() 
       + "') " 
       + "SET @nombreDriver = (SELECT nombre FROM SISTEMA.dbo.TELEFONOS WHERE IMEI_SIM = '" 
       + mngr.getDeviceId() 
       + "') " 
       + "SET @duracion = " 
       + managedCursor.getString(duration) 
       + "SET @evento = '(LOG) Llamada " 
       + dir 
       + ". Duración ' + CONVERT(varchar, @duracion, 103) + ' segundos al número: " 
       + managedCursor.getString(number) 
       + "' " 
       // + "SET @duracion = " + callDuration 
       + " SET @inicial = '" 
       + fechaInicio 
       + "'" 
       + "INSERT INTO bitacora.dbo.registroDellamadasOperadores (fechacreacion,fecha_fin,fecha_inicio,idMobil,Tractor,Nom_tra,Cve_tra,FechaRegistro,Evento) " 
       + " VALUES('" 
       + fechaInicio 
       + "', DATEADD(SECOND,@duracion,@inicial),'" 
       + fechaInicio 
       + "','" 
       + mngr.getDeviceId() 
       + "','',@nombreDriver,@claveDriver,current_timestamp,@evento)"; 
     AsyncCallWS tareaEnviarABD = new AsyncCallWS(); 
     tareaEnviarABD.execute(); 

     sb.append("\nNúmero de teléfono:--- " + phNumber 
       + " \nTipo de llamada:--- " + dir + " \nFecha de llamada:--- " 
       + fechaLlamada2 + " " + fechaLlamada1 
       + " \nDuración en segundos:--- " + callDuration 
       + " \nDispositivo actual:--" + mngr.getDeviceId()); 
     sb.append("\n----------------------------------"); 

     // } 
     txtDetalles.setText(sb); 
    } 

    private class AsyncCallWS extends AsyncTask<String, Void, Void> { 
     @Override 
     protected Void doInBackground(String... params) { 
      Log.i(TAG, "doInBackground"); 
      InsertarLlamada(insercion); 
      return null; 
     } 

     @Override 
     protected void onPostExecute(Void result) { 
      Log.i(TAG, "onPostExecute"); 
      txtInformacion.setText("Información enviada"); 
     } 

     @Override 
     protected void onPreExecute() { 
      Log.i(TAG, "onPreExecute"); 
      txtInformacion.setText("Enviando información..."); 
     } 

     @Override 
     protected void onProgressUpdate(Void... values) { 
      Log.i(TAG, "onProgressUpdate"); 
     } 

     public void InsertarLlamada(String insercion) { 
      // Creamos la solicitud 
      SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); 
      // Propiedades que contienen los valores 
      PropertyInfo propiedades = new PropertyInfo(); 

      propiedades.setName("insercion"); 
      propiedades.setValue(insercion); 
      propiedades.setType(String.class); 
      // Agregamos las propiedades 
      request.addProperty(propiedades); 
      // Creamos el envelope 
      SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
        SoapEnvelope.VER11); 
      envelope.dotNet = true; 
      // ponemos la salida SOAP 
      envelope.setOutputSoapObject(request); 
      // Creamos la llamada HTTP 
      HttpTransportSE androidHttpTransport = new HttpTransportSE(URL); 

      try { 
       // Invocamos el servicio 
       androidHttpTransport.call(SOAP_ACTION, envelope); 
       // Obtenemos la respuesta 
       Object response = envelope.getResponse(); 
       // Asignamos el resultado de la consulta 
       resultado = response.toString(); 
      } catch (Exception e) { 
       resultado = e.getMessage(); 
      } 
     } 
    } 
} 

BootReceiver类:

package com.trucka.llamadasdrivers; 

import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 

public class BootReceiver extends BroadcastReceiver { 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     Intent myIntent = new Intent(context, ActividadLlamadasDrivers.class); 
     myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
     context.startActivity(myIntent); 
    } 
} 

Llamadas服务:

package com.trucka.llamadasdrivers; 

import android.app.Notification; 
import android.app.NotificationManager; 
import android.app.PendingIntent; 
import android.app.Service; 
import android.content.Context; 
import android.content.Intent; 
import android.net.Uri; 
import android.os.IBinder; 
import android.widget.Toast; 

public class ServicioLlamadas extends Service { 

    private static ServicioLlamadas instance = null; 

    public static boolean isRunning() { 
     return instance != null; 
    } 

    @Override 
    public IBinder onBind(Intent intent) { 
     return null; 
    } 

    @Override 
    public void onCreate() { 
     Toast.makeText(getApplicationContext(), "Servicio TRUCKA creado", 
       Toast.LENGTH_SHORT).show(); 
     instance = this; 
    } 

    @Override 
    public void onDestroy() { 
     Toast.makeText(getApplicationContext(), "Servicio TRUCKA destruído", 
       Toast.LENGTH_SHORT).show(); 
     instance = null; 
    } 

    @Override 
    public void onStart(Intent intent, int startid) { 
     Toast.makeText(getApplicationContext(), "Servicio TRUCKA iniciado", 
       Toast.LENGTH_SHORT).show(); 
     lanzarNotificacion(); 

    } 

    @SuppressWarnings("deprecation") 
    void lanzarNotificacion() { 
     String ns = Context.NOTIFICATION_SERVICE; 
     NotificationManager notManager = (NotificationManager) getSystemService(ns); 

     // Configuramos la notificacion 
     Notification notif = new Notification(
       android.R.drawable.ic_menu_agenda, "Servicio TRUCKA", 
       System.currentTimeMillis()); 

     // Configuramos el Intent 
     Context contexto = ServicioLlamadas.this; 
     CharSequence titulo = "Notificación Servicio TRUCKA"; 
     CharSequence descripcion = "Registro habilitado."; 

     // Intent que se abrira al clickear la notificacion 
     PendingIntent contIntent = PendingIntent.getActivity(contexto, 0, null, 
       0); 
     notif.setLatestEventInfo(contexto, titulo, descripcion, contIntent); 
     notif.flags |= Notification.FLAG_AUTO_CANCEL; 
     notif.defaults |= Notification.DEFAULT_VIBRATE; 
     notManager.notify(1, notif); 
    } 
} 

和清单:

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.trucka.llamadasdrivers" 
    android:versionCode="1" 
    android:versionName="1.0" > 

    <uses-sdk 
     android:minSdkVersion="8" 
     android:targetSdkVersion="18" /> 

    <uses-permission android:name="android.permission.VIBRATE" /> 
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> 
    <uses-permission android:name="android.permission.READ_CALL_LOG" /> 
    <uses-permission android:name="android.permission.READ_PHONE_STATE" /> 
    <uses-permission android:name="android.permission.INTERNET" /> 
    <uses-permission android:name="android.permission.CALL_PHONE" /> 

    <application 
     android:allowBackup="true" 
     android:icon="@drawable/ic_launcher" 
     android:label="@string/app_name" 
     android:theme="@style/AppTheme" > 
     <activity 
      android:name="com.trucka.llamadasdrivers.ActividadLlamadasDrivers" 
      android:label="@string/app_name" > 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 

     <service 
      android:name="com.trucka.llamadasdrivers.ServicioLlamadas" 
      android:enabled="true" 
      android:icon="@drawable/ic_launcher" > 
     </service> 

     <receiver android:name=".BootReceiver" > 
      <intent-filter> 
       <action android:name="android.intent.action.BOOT_COMPLETED" /> 
      </intent-filter> 
     </receiver> 
    </application> 

</manifest> 

回答

0

人类的愚蠢没有限制。 我不在服务中的actin

相关问题