2012-07-28 118 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" />