2012-07-28 68 views
-2

我目前正在尝试创建一个应用程序,可以跟踪我花了多少时间打个电话,然后在点击一个按钮后在敬酒信息上显示。不知道为什么代码不工作.. Android/Java

代码在这里找到:http://paste.ideaslabs.com/show/6INd0afyi

我似乎无法弄清楚为什么应用程序无法正常工作......

的想法是创建一个,只要我打个电话启动的服务呼叫(并且从此开始无限期地继续运行)。该服务有两个while循环,它们通过TelephonyManager类使用getCallState()方法来跟踪对话的开始时间和结束时间。然后,结束时间和开始时间变量的值将被存储并用于活动类中。

活动类只是使用一个按钮来显示吐司消息,说明我花了多少时间。

当我尝试运行我的手机上的应用程序,我可以看到该服务运行,但有时还是仅仅是应用程序崩溃表明,花了通话时间为0分钟(这是不正确的。)

希望你们可以指出任何错误?!

谢谢!

+2

发布你的'CallService'代码。 – iTurki 2012-07-28 18:07:17

+1

...和logcat错误。也请直接编辑它们到这个问题中;突出显示您的代码并按下Ctrl + K以正确格式化代码块。 – Sam 2012-07-28 18:07:45

回答

1

只要看到你发布的代码,我会说你没有正确阅读有关服务的文档。你不通过做一个MyService s = new MyService()

阅读Android developer guideAndroid SDK documentation。您会看到如何启动本地服务或使用意图启动服务。

如:

Intent intent = new Intent(this, HelloService.class); 
startService(intent); 
+0

嗨, “最终CallService cs = new CallService();”位仅用于访问变量“EndTime”和“StartTime”。我并没有试图用我的活动开始这项服务。新呼叫发起时,它使用“CallReceiver”类开始。按照我的方式访问变量是否错误? – fouadalnoor 2012-07-28 19:23:51

0

看你以前的问题,我建议你阅读本:How to make a phone call in android and come back to my activity when the call is done?

它描述了如何建立一个PhoneStateListener这样,当呼叫本地启动就可以收到一个意图,从别人收到,并结束。

的服务有两个while循环跟踪的开始时间和结束时间

这些while循环,也没有必要用PhoneStateListener,你可以简单地得到两个时间戳和减去差,不具有两个while循环每毫秒运行。

1

操作系统发生时会发生一些事件。例如。接收短信,电话状态(发送,接收)。通过阅读您的文章,我认为您应该使用广播接收器注册您的应用程序。这是一个示例代码。

public class PhoneCallState extends BroadcastReceiver 
{ 

static long start_time, end_time; 

@Override 
public void onReceive(Context context, Intent intent) 
{ 
    final Bundle extras = intent.getExtras(); 

    if(intent.getAction().equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED)) 
    {    
     final String state = extras.getString(TelephonyManager.EXTRA_STATE); 

     if ("RINGING".equals(state)) 
     { 
     Toast.makeText(context, "Ringing", Toast.LENGTH_LONG).show(); 
     }  

     if ("OFFHOOK".equals(state)) 
     { 

     start_time = System.currentTimeMillis(); 
     Toast.makeText(context, "Off", Toast.LENGTH_LONG).show(); 
     } 


     if ("IDLE".equals(state)) 
     { 

     end_time = System.currentTimeMillis(); 

     long duration = (end_time - start_time) /1000; 
     Toast.makeText(context, "Duration : " + duration, Toast.LENGTH_LONG).show(); 

     } 


    } 
} 

并注册您的接收器在清单文件。

<receiver android:name=".PhoneCallState"> 
    <intent-filter> 
     <action android:name="android.intent.action.PHONE_STATE" /> 
    </intent-filter> 
</receiver> 

}

终于不用forgate添加PHONE_STATE权限。

<uses-permission android:name="android.permission.READ_PHONE_STATE" /> 
相关问题