2014-05-03 41 views
1

我想在android中使用broadcastreceiver服務保存傳出的電話號碼和持續時間。我使用下面的代碼來實現功能,但它會引發錯誤。想要保存傳出的電話號碼,使用broadcastreceiver的持續時間

public class OutgoingReceiver extends BroadcastReceiver { 
    public OutgoingReceiver() { 
    } 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     try 
     { 
      Bundle bundle = intent.getExtras(); 
      number = bundle.getString(Intent.EXTRA_PHONE_NUMBER); 
      dbOutgoing = new DBOutgoing(ctx);    
      dbOutgoing.InsertOutGoingCallDB(number, "0", "0"); 
      Toast.makeText(ctx, 
       "Outgoing: "+number, 
       Toast.LENGTH_LONG).show(); 
     } 
     catch(FileNotFoundException e) 
     { 
      e.printStackTrace(); 
      Toast.makeText(ctx, String.valueOf(e),Toast.LENGTH_LONG).show(); 
     } 
    } 
} 

上面的代碼給出了撥出的電話號碼,但我也需要在通話結束後持續時間。

+0

請添加錯誤的詳細信息。 –

+0

@AlexeyMalev。我現在沒有得到任何錯誤,但我希望在撥出電話結束後獲得通話時間 – user3490327

回答

0

來源:Get Last Call Duration in androidIntent to be fired when a call ends?

<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
     package="com.gopi" 
     android:versionCode="1" 
     android:versionName="1.0"> 
    <uses-permission android:name="android.permission.INTERNET" /> 
    <uses-permission android:name="android.permission.WRITE_CONTACTS" /> 
    <uses-permission android:name="android.permission.READ_PHONE_STATE" /> 

    <application android:icon="@drawable/icon" android:label="@string/app_name"> 

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

    </application> 
</manifest> 



public class IncomingCallTracker extends BroadcastReceiver { 

    @Override 
    public void onReceive(Context context, Intent intent) { 

     Bundle bundle = intent.getExtras(); 

      Set<String> keys = bundle.keySet(); 
     for (String key : keys) { 
       Log.i("MYAPP##", key + "="+ bundle.getString(key)); 
     }  
    } 

} 

你可以看看在包的密鑰 '國家'。當其值爲'IDLE'時,表示呼叫已結束,您可以根據此操作執行任何您想要的操作。

如果狀態是 '空閒'

Uri contacts = CallLog.Calls.CONTENT_URI; 
     Cursor managedCursor = mContext.getContentResolver().query(
       contacts, null, null, null, null); 
     int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER); 
     int duration1 = managedCursor.getColumnIndex(CallLog.Calls.DURATION); 
     // movetoFirst() gives last ended call 
     if(managedCursor.moveToFirst() == true) { 
      String phNumber = managedCursor.getString(number); 
      String callDuration = managedCursor.getString(duration1); 
     } 
     managedCursor.close(); 
+0

感謝您的代碼,但我如何才能找到該包的狀態。我試過bundle.getString(TelephonyManager.EXTRA_STATE),但我不知道它的正確性? – user3490327

+0

而我需要它撥出電話。任何人都會分享你的想法。 – user3490327

+0

傳出呼叫的廣播接收器:http://stackoverflow.com/questions/9569118/how-do-you-receive-outgoing-call-in-broadcastreceiver –