如何使用游标在android中使用Service检索调用?

时间:2018-04-05 14:42:30

标签: android android-service android-cursor

我使用Activity检索了调用,但相同的代码似乎不适用于Service。光标无效。服务中的游标或任何其他选项是否有替代方法可以在后台检索调用?

    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.selection_call, container, false);

    ContentResolver resolver = getActivity().getContentResolver();
    Context context = getActivity();
    call_logs = (TextView) v.findViewById(R.id.tv_call_logs);
    upload = (FloatingActionButton) v.findViewById(R.id.upload_floatingActionButton);
    StringBuffer sb = new StringBuffer();
    if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_CALL_LOG) !=
            PackageManager.PERMISSION_GRANTED)
    {

        final int REQUEST_CODE_ASK_PERMISSIONS = 123;
        ActivityCompat.requestPermissions(getActivity(), new String[]{"android.permission.READ_CALL_LOG"},  REQUEST_CODE_ASK_PERMISSIONS);
        ActivityCompat.requestPermissions(getActivity(), new String[]{"android.permission.WRITE_CALL_LOG"}, REQUEST_CODE_ASK_PERMISSIONS);
    }

    Cursor cur = context.getContentResolver().query(CallLog.Calls.CONTENT_URI, null, null, null, android.provider.CallLog.Calls.DATE + " DESC");

    int number = cur.getColumnIndex( CallLog.Calls.NUMBER );
    int type = cur.getColumnIndex(CallLog.Calls.TYPE);
    int date = cur.getColumnIndex(CallLog.Calls.DATE);
    int duration = cur.getColumnIndex( CallLog.Calls.DURATION);
    sb.append( "Call Details : \n");
    while ( cur.moveToNext() ) {
        String phNumber = cur.getString( number );
        String callType = cur.getString(type);
        String callDate = cur.getString(date);
        Date callDayTime = new Date(Long.valueOf(callDate));
        String callDuration = cur.getString( duration );
        String dir = null;
        int dircode = Integer.parseInt(callType);
        switch (dircode) {
            case CallLog.Calls.OUTGOING_TYPE:
                dir = "OUTGOING";
                break;

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

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

        sb.append( "\nPhone Number:--- "+phNumber +"\nCall Type:--- " + dir +" \nCall Date:--- " + callDayTime+" \nCall duration in sec :--- "+callDuration );
        sb.append("\n----------------------------------");
    }
    cur.close();
    call_logs.setText(sb);

    return v;
}

0 个答案:

没有答案