Android编程权威指南:第21章挑战练习:有一个隐式intent

先添加一个新的用于打电话的Button,布局添加好后给这个Button添加一个时间监听器。

mCallButton = (Button)v.findViewById(R.id.crime_callButton);
        mCallButton.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Uri number = Uri.parse("tel:"+ mCrime.getPhoneNumber());
                Intent i = new Intent(Intent.ACTION_DIAL, number);
                startActivity(i);
            }
});

由于要获得对应的电话号码,给Crime类添加号码信息。

    private String mPhoneNumber;

    public String getPhoneNumber() {
        return mPhoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        mPhoneNumber = phoneNumber;
    }
package com.onevol.app;

import java.util.Date;
import java.util.UUID;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.drawable.BitmapDrawable;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;

public class CrimeFragment extends Fragment {
    public static final String EXTRA_CRIME_ID = "crime_id";
    //用于getSerializable()方法中UUID的键。
    private static final String DIALOG_DATE = "date";//DatePickerFragment的tag常量,卵用
    private static final int REQUEST_DATE = 0;
    private static final int REQUEST_TIME = 1;
    private static final int REQUEST_PHOTO = 2;
    private static final int REQUEST_CONTACT = 3;
    private static final String TAG = "CrimeFragment";
    //用于DatePickerFragment设置目标fragment的setTargetFragment()方法
    //CrimeFragment用其确定是哪一个fragment返回的数据。
    protected static final String DIALOG_IMAGE = "image";

    private Crime mCrime;
    private EditText mTitleField;
    private Button mDateButton;
    private CheckBox mSolvedCheckBox;
    private Button mTimeButton;
    private ImageButton mPhotoButton;
    private ImageView mPhotoView;
    private Button mSuspectButton;
    private Button mCallButton;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);//标题栏上添加的按钮
//      UUID crimeId = (UUID) getActivity().getIntent().getSerializableExtra(EXTRA_CRIME_ID);
        UUID crimeId = (UUID)getArguments().getSerializable(EXTRA_CRIME_ID);
        mCrime = CrimeLab.get(getActivity()).getCrime(crimeId);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup parent,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View v = inflater.inflate(R.layout.fragment_crime, parent, false);

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
            if(NavUtils.getParentActivityName(getActivity()) != null){
                getActivity().getActionBar().setDisplayHomeAsUpEnabled(true);
            }
        }

        mTitleField = (EditText)v.findViewById(R.id.crime_title);
        mTitleField.setText(mCrime.getTitle());
        mTitleField.addTextChangedListener(new TextWatcher(){
            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {
                // TODO Auto-generated method stub
                mCrime.setTitle(s.toString());
            }
            @Override
            public void afterTextChanged(Editable arg0) {
                // TODO Auto-generated method stub
            }
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
                // TODO Auto-generated method stub
            }
        });

        mDateButton = (Button) v.findViewById(R.id.crime_date);
//      SimpleDateFormat format=new SimpleDateFormat("dd-MM-yyyy");
//      String time=format.format(new Date());
        mDateButton.setText(mCrime.getDate().toString());
//      mDateButton.setEnabled(false);
        mDateButton.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                FragmentManager fm = getActivity().getSupportFragmentManager();
//              DatePickerFragment dialog = new DatePickerFragment();
                DatePickerFragment dialog = DatePickerFragment.newInstance(mCrime.getDate());//新建DatePickerFragment并传递时间信息
                dialog.setTargetFragment(CrimeFragment.this, REQUEST_DATE);//设置DatePickerFragment传递数据的目标。
                dialog.show(fm, DIALOG_DATE);//显示该fragment(DialogFragment)。
            }
        });

        mSolvedCheckBox = (CheckBox) v.findViewById(R.id.crime_solved);
        mSolvedCheckBox.setChecked(mCrime.isSolved());
        mSolvedCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener(){
            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {
                // TODO Auto-generated method stub
                mCrime.setSolved(isChecked);
            }
        });

        mTimeButton = (Button)v.findViewById(R.id.crime_time);
        mTimeButton.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                FragmentManager fm = getActivity().getSupportFragmentManager();
//              DatePickerFragment dialog = new DatePickerFragment();
                TimePickerFragment tdialog = TimePickerFragment.newInstance(mCrime.getDate());//新建TimePickerFragment并传递时间信息
                tdialog.setTargetFragment(CrimeFragment.this, REQUEST_TIME);//设置TimePickerFragment传递数据的目标。
                tdialog.show(fm, DIALOG_DATE);////显示该fragment(DialogFragment)。忽略DIALOG_DATE不是DIALOG_TIME
            }
        });

        mPhotoButton = (ImageButton)v.findViewById(R.id.crime_imageButton);
        mPhotoButton.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent i = new Intent(getActivity(), CrimeCameraActivity.class);
//              startActivity(i);
                startActivityForResult(i, REQUEST_PHOTO);
            }
        });

        mPhotoView = (ImageView)v.findViewById(R.id.crime_imageView);
        registerForContextMenu(mPhotoView);
        mPhotoView.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Photo p = mCrime.getPhoto();
                if(p == null){
                    return;
                }
                FragmentManager fm = getActivity().getSupportFragmentManager();
                String path = getActivity().getFileStreamPath(p.getFilename()).getAbsolutePath();
                ImageFragment.newInstance(path, mCrime.getPhoto().getOrientation())
                    .show(fm, DIALOG_IMAGE);
            }
        });

        Button reportButton = (Button)v.findViewById(R.id.crime_reportButton);
        reportButton.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent i = new Intent(Intent.ACTION_SEND);
                i.setType("text/plain");
                i.putExtra(Intent.EXTRA_TEXT, getCrimeReport());
                i.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.crime_report_subject));
                i = Intent.createChooser(i, getString(R.string.send_report));
                startActivity(i);
            }
        });

        mSuspectButton = (Button)v.findViewById(R.id.crime_suspectButton);
        mSuspectButton.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent i = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);//修改联系人电话号码的URI
                startActivityForResult(i, REQUEST_CONTACT);
            }
        });
        if(mCrime.getSuspect() != null){
            mSuspectButton.setText(mCrime.getSuspect());
        }

        mCallButton = (Button)v.findViewById(R.id.crime_callButton);
        mCallButton.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Uri number = Uri.parse("tel:"+ mCrime.getPhoneNumber());
                Intent i = new Intent(Intent.ACTION_DIAL, number);//拨好号码,等待用户发起通话
                startActivity(i);
            }
        });

        PackageManager pm = getActivity().getPackageManager();//判断设备是否有相机
        boolean hasACamera = pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)||
                pm.hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT)||
                Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD||
                Camera.getNumberOfCameras() > 0;
        if(!hasACamera){
            mPhotoButton.setEnabled(false);//没有将不能按相机按钮
        }
        return v;
    }

    public static CrimeFragment newInstance(UUID crimeId){//托管activity需要fragment实例是,调用newInstance方法
        Bundle args = new Bundle();
        args.putSerializable(EXTRA_CRIME_ID, crimeId);
        //取出crimeId的值,添加到bundle中
        CrimeFragment fragment = new CrimeFragment();
        fragment.setArguments(args);//设给fragment
        return fragment;
    }

    public void returnResult(){
        getActivity().setResult(Activity.RESULT_OK, null);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {//CrimeFragment与其它fragment的数据传递。
        //该方法是接受其它fragment传来的时间数据,改变按钮上显示的时间。
        // TODO Auto-generated method stub
        if(resultCode != Activity.RESULT_OK) return;
        if(requestCode == REQUEST_DATE){//如果是DatePickerFragment传的数据
            Date date = (Date)data.getSerializableExtra(DatePickerFragment.EXTRA_DATE);
            mCrime.setDate(date);
            mDateButton.setText(mCrime.getDate().toString());
        }
        if(requestCode == REQUEST_TIME){//如果是TimePickerFragment传的数据
        Date date = (Date)data.getSerializableExtra(TimePickerFragment.EXTRA_TIME);
        mCrime.setDate(date);
        mDateButton.setText(mCrime.getDate().toString());
        }
        if(requestCode == REQUEST_PHOTO){
            if(mCrime.getPhoto() != null) {
                mCrime.deletePhoto(getActivity().getFileStreamPath(mCrime.getPhoto().getFilename()).getAbsolutePath());
            }
            String filename = data.getStringExtra(CrimeCameraFragment.EXTRA_PHOTO_FILENAME);
            int orientation = data.getIntExtra(CrimeCameraFragment.EXTRA_PHOTO_ORIENTATION, 0);
            if(filename != null){
//              Log.i(TAG, "filename: " + filename);
                Photo p = new Photo(filename, orientation);
                mCrime.setPhoto(p);
//              Log.i(TAG, "Crime: " + mCrime.getTitle() + " has a photo");
                showPhoto();
            }
        }
        if(requestCode == REQUEST_CONTACT){
            Uri contactUri = data.getData();

            String[] queryFields = new String[]{ContactsContract.Contacts.DISPLAY_NAME,
                    ContactsContract.CommonDataKinds.Phone.NUMBER};//获得联系人姓名及电话号码

            Cursor c = getActivity().getContentResolver().query(contactUri, queryFields, null, null, null);
            if(c.getCount() == 0){
                c.close();
                return;
            }
            c.moveToFirst();
            String suspect = c.getString(0);
            String number = c.getString(1);
            mCrime.setSuspect(suspect);
            mCrime.setPhoneNumber(number);
            mSuspectButton.setText(suspect);
            mCallButton.setText("CALL:" + suspect);
            c.close();
        }
    }

    @Override
    public void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        CrimeLab.get(getActivity()).saveCrimes();
    }


    @Override
    public void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        showPhoto();
    }

    @Override
    public void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        PictureUtils.cleanImageView(mPhotoView);
    }

    private void showPhoto(){
        Photo p = mCrime.getPhoto();
        BitmapDrawable b = null;
        if(p != null){
            String path = getActivity().getFileStreamPath(p.getFilename()).getAbsolutePath();
            b = PictureUtils.getScaledDrawable(getActivity(), path);

            if(p.getOrientation() == Configuration.ORIENTATION_PORTRAIT){//如果是竖屏就旋转90度
            b = PictureUtils.getPortraitDrawable(mPhotoView, b);
            }
        }
        mPhotoView.setImageDrawable(b);
    }

    private String getCrimeReport(){
        String solvedString = null;
        if(mCrime.isSolved()){
            solvedString = getString(R.string.crime_report_solved);
        } else {
            solvedString = getString(R.string.crime_report_unsolved);
        }

        String dateFormat = "EEE, MMM dd";
        String dateString = DateFormat.format(dateFormat, mCrime.getDate()).toString();

        String suspect = mCrime.getSuspect();
        if(suspect == null){
            suspect = getString(R.string.crime_report_no_suspect);
        } else {
            suspect = getString(R.string.crime_report_suspect,suspect);
        }

        String report = getString(R.string.crime_report, mCrime.getTitle(), dateString, solvedString, suspect);

        return report;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // TODO Auto-generated method stub
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.delete_crime, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        switch(item.getItemId()){
        case R.id.menu_delete_crime://标题栏删除按钮
            Crime crime = mCrime;
            CrimeLab.get(getActivity()).deleteCrime(crime);
            Intent i = new Intent(getActivity(), CrimeListActivity.class);
            startActivity(i);
            return true;
        case android.R.id.home://标题栏后退按钮
            if(NavUtils.getParentActivityName(getActivity()) != null){
                NavUtils.navigateUpFromSameTask(getActivity());
            }
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
        //添加上下文菜单
        getActivity().getMenuInflater().inflate(R.menu.crime_list_item_context,menu);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        if(mCrime.getPhoto() != null && 
                mCrime.deletePhoto(getActivity().getFileStreamPath(mCrime.getPhoto().getFilename()).getAbsolutePath())) {
            showPhoto();
            return true;
        }
        return super.onContextItemSelected(item);
    }
}

补充
android系统管理联系人的URI如下:
ContactsContract.Contacts.CONTENT_URI 管理联系人的Uri
ContactsContract.CommonDataKinds.Phone.CONTENT_URI 管理联系人的电话的Uri
ContactsContract.CommonDataKinds.Email.CONTENT_URI 管理联系人的Email的Uri
注:Contacts有两个表,分别是rawContact和Data,rawContact记录了用户的id和name,
其中id栏名称为:ContactsContract.Contacts._ID,
name名称栏为ContactContract.Contracts.DISPLAY_NAME,
电话信息表的外键id为ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
电话号码栏名称为:ContactsContract.CommonDataKinds.Phone.NUMBER.
Email外键id为:ContactsContract.CommonDataKinds.Email.CONTACT_ID
Email地址栏名称为:ContactsContract.CommonDataKinds.Email.DATA

你可能感兴趣的:(练习)