├── .gitignore
├── README.md
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── neu
│ │ └── androidbestpractices
│ │ └── ApplicationTest.java
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── neu
│ │ │ └── androidbestpractices
│ │ │ ├── MyApplication.java
│ │ │ ├── activity
│ │ │ ├── ContactActivity.java
│ │ │ ├── MainActivity.java
│ │ │ ├── QrcodeActivity.java
│ │ │ └── base
│ │ │ │ └── BaseActivity.java
│ │ │ ├── adapter
│ │ │ └── CardViewAdapter.java
│ │ │ ├── fragment
│ │ │ ├── ContactFragment.java
│ │ │ ├── QrcodeFragment.java
│ │ │ └── base
│ │ │ │ └── BaseFragment.java
│ │ │ ├── pojo
│ │ │ └── ItemTest.java
│ │ │ └── widget
│ │ │ └── FixedHeightScrollingViewBehavior.java
│ └── res
│ │ ├── layout
│ │ ├── activity_main.xml
│ │ ├── adapter_item.xml
│ │ ├── common_activity.xml
│ │ ├── fragment_contact.xml
│ │ └── fragment_qrcode.xml
│ │ ├── mipmap-hdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-mdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xhdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xxhdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xxxhdpi
│ │ └── ic_launcher.png
│ │ ├── values-v21
│ │ └── styles.xml
│ │ ├── values-w820dp
│ │ └── dimens.xml
│ │ └── values
│ │ ├── colors.xml
│ │ ├── dimens.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test
│ └── java
│ └── com
│ └── neu
│ └── androidbestpractices
│ └── ExampleUnitTest.java
├── build.gradle
├── contact
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── neu
│ │ └── contact
│ │ └── ApplicationTest.java
│ └── main
│ ├── AndroidManifest.xml
│ ├── java
│ └── com
│ │ └── neu
│ │ └── contact
│ │ ├── ContactFactory.java
│ │ ├── constants
│ │ └── Constants.java
│ │ ├── contact
│ │ ├── Contact.java
│ │ ├── ContactCallback.java
│ │ ├── ContactImpl.java
│ │ └── PermissionResultCallback.java
│ │ ├── contactui
│ │ ├── ContactDetailsFragment.java
│ │ ├── ContactsListFragment.java
│ │ ├── ContactsPickerActivity.java
│ │ └── OnContactSelectedListener.java
│ │ └── util
│ │ ├── PermissionUtil.java
│ │ └── Utils.java
│ └── res
│ ├── drawable-hdpi
│ ├── library_ic_action_search.png
│ └── library_ic_person_add_white_48dp.png
│ ├── drawable-xhdpi
│ ├── library_ic_action_search.png
│ └── library_ic_person_add_white_48dp.png
│ ├── layout
│ ├── library_activity_contacts.xml
│ ├── library_fragment_contact_detail.xml
│ ├── library_fragment_contacts_list.xml
│ ├── library_list_item_contacts.xml
│ └── library_list_item_phone_number.xml
│ ├── menu
│ └── library_main.xml
│ └── values
│ ├── library_strings.xml
│ ├── library_styles.xml
│ └── strings.xml
├── gradle.properties
├── gradle
├── maven_push.gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── httpclient
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── neu
│ │ └── httpclient
│ │ └── ApplicationTest.java
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── neu
│ │ │ └── httpclient
│ │ │ ├── HttpCallback.java
│ │ │ ├── HttpRequest.java
│ │ │ ├── HttpRequestFactory.java
│ │ │ ├── OkHttpRequestImpl.java
│ │ │ ├── ProgressListener.java
│ │ │ └── TType.java
│ └── res
│ │ └── values
│ │ └── strings.xml
│ └── test
│ └── java
│ └── com
│ └── neu
│ └── httpclient
│ └── ExampleUnitTest.java
├── qrcode
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── neu
│ │ └── qrcode
│ │ └── ApplicationTest.java
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── neu
│ │ │ └── qrcode
│ │ │ ├── Qrcode.java
│ │ │ ├── QrcodeFactory.java
│ │ │ ├── callback
│ │ │ ├── PermissionResultCallback.java
│ │ │ └── QrcodeCallback.java
│ │ │ ├── impl
│ │ │ └── QrcodeImpl.java
│ │ │ ├── qrcode
│ │ │ └── QrcodeInfo.java
│ │ │ ├── skill
│ │ │ ├── activity
│ │ │ │ └── CaptureActivity.java
│ │ │ ├── camera
│ │ │ │ ├── AutoFocusManager.java
│ │ │ │ ├── CameraConfigurationManager.java
│ │ │ │ ├── CameraManager.java
│ │ │ │ ├── PreviewCallback.java
│ │ │ │ └── open
│ │ │ │ │ └── OpenCameraInterface.java
│ │ │ ├── constants
│ │ │ │ └── Constants.java
│ │ │ ├── decode
│ │ │ │ ├── DecodeFormatManager.java
│ │ │ │ ├── DecodeHandler.java
│ │ │ │ └── DecodeThread.java
│ │ │ ├── utils
│ │ │ │ ├── BeepManager.java
│ │ │ │ ├── CaptureActivityHandler.java
│ │ │ │ └── InactivityTimer.java
│ │ │ └── view
│ │ │ │ └── ViewfinderView.java
│ │ │ └── util
│ │ │ └── Utils.java
│ └── res
│ │ ├── layout
│ │ ├── library_activity_capture.xml
│ │ └── library_view_find_view.xml
│ │ ├── raw
│ │ └── beep.ogg
│ │ └── values
│ │ └── strings.xml
│ └── test
│ └── java
│ └── com
│ └── neu
│ └── qrcode
│ └── ExampleUnitTest.java
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/workspace.xml
5 | /.idea/libraries
6 | .DS_Store
7 | /build
8 | /captures
9 | /.idea
10 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # android-best-practices
2 |
3 | android最佳实践学习
4 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 23
5 | buildToolsVersion "23.0.2"
6 |
7 | defaultConfig {
8 | applicationId "com.neu.androidbestpractices"
9 | minSdkVersion 16
10 | targetSdkVersion 23
11 | versionCode 1
12 | versionName "1.0"
13 | }
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 | }
21 |
22 | dependencies {
23 | compile fileTree(include: ['*.jar'], dir: 'libs')
24 | testCompile 'junit:junit:4.12'
25 | compile 'com.android.support:appcompat-v7:23.1.1'
26 | compile 'com.android.support:recyclerview-v7:23.1.1'
27 | compile 'com.android.support:cardview-v7:23.1.1'
28 | compile 'com.jakewharton:butterknife:7.0.1'
29 | compile 'com.android.support:design:23.1.1'
30 |
31 | compile project(':contact')
32 | compile project(':qrcode')
33 | compile project(':httpclient')
34 | }
35 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/neu/Library/Android/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/neu/androidbestpractices/ApplicationTest.java:
--------------------------------------------------------------------------------
1 | package com.neu.androidbestpractices;
2 |
3 | import android.app.Application;
4 | import android.test.ApplicationTestCase;
5 |
6 | /**
7 | * Testing Fundamentals
8 | */
9 | public class ApplicationTest extends ApplicationTestCase {
10 | public ApplicationTest() {
11 | super(Application.class);
12 | }
13 | }
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/app/src/main/java/com/neu/androidbestpractices/MyApplication.java:
--------------------------------------------------------------------------------
1 | package com.neu.androidbestpractices;
2 |
3 | import android.app.Application;
4 |
5 | /**
6 | * Created by neu on 16/2/2.
7 | */
8 | public class MyApplication extends Application{
9 | /**
10 | * 全局实例
11 | */
12 | private static MyApplication sApp;
13 |
14 | /**
15 | * 获取实例
16 | * @return
17 | */
18 | public static MyApplication getInstance(){
19 | return sApp;
20 | }
21 | @Override
22 | public void onCreate() {
23 | super.onCreate();
24 | //初始化
25 | sApp = this;
26 |
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/app/src/main/java/com/neu/androidbestpractices/activity/ContactActivity.java:
--------------------------------------------------------------------------------
1 | package com.neu.androidbestpractices.activity;
2 |
3 |
4 | import android.app.Activity;
5 | import android.app.Fragment;
6 |
7 | import com.neu.androidbestpractices.activity.base.BaseActivity;
8 | import com.neu.androidbestpractices.fragment.ContactFragment;
9 |
10 | /**
11 | * 联系人界面
12 | * Created by neu on 16/2/3.
13 | */
14 | public class ContactActivity extends BaseActivity {
15 | @Override
16 | protected Activity getActivity() {
17 | return this;
18 | }
19 |
20 | @Override
21 | protected Fragment getFragment() {
22 | return new ContactFragment();
23 | }
24 |
25 | @Override
26 | protected CharSequence getToolbarTitle() {
27 | return "联系人测试";
28 | }
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/app/src/main/java/com/neu/androidbestpractices/activity/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.neu.androidbestpractices.activity;
2 |
3 | import android.app.Activity;
4 | import android.os.Bundle;
5 | import android.support.v7.app.AppCompatActivity;
6 | import android.support.v7.widget.LinearLayoutManager;
7 | import android.support.v7.widget.RecyclerView;
8 |
9 | import com.neu.androidbestpractices.R;
10 | import com.neu.androidbestpractices.adapter.CardViewAdapter;
11 | import com.neu.androidbestpractices.pojo.ItemTest;
12 |
13 | import java.util.ArrayList;
14 | import java.util.List;
15 |
16 | /**
17 | * 首页
18 | */
19 | public class MainActivity extends AppCompatActivity {
20 |
21 | @Override
22 | protected void onCreate(Bundle savedInstanceState) {
23 | super.onCreate(savedInstanceState);
24 | setContentView(R.layout.activity_main);
25 |
26 | RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
27 |
28 | //设置layoutmanager
29 | LinearLayoutManager llm = new LinearLayoutManager(this);
30 | recyclerView.setLayoutManager(llm);
31 |
32 | //设置adapter
33 | CardViewAdapter adapter = new CardViewAdapter(getList(), this);
34 | recyclerView.setAdapter(adapter);
35 |
36 |
37 | Activity activity = this;
38 | activity.findViewById(R.id.collapsing_toolbar);
39 | }
40 |
41 | /**
42 | * 数据
43 | * @return
44 | */
45 | private List getList() {
46 | List list = new ArrayList<>();
47 | list.add(new ItemTest("联系人模块",ContactActivity.class.getCanonicalName()));
48 | list.add(new ItemTest("二维码模块",QrcodeActivity.class.getCanonicalName()));
49 |
50 | return list;
51 |
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/app/src/main/java/com/neu/androidbestpractices/activity/QrcodeActivity.java:
--------------------------------------------------------------------------------
1 | package com.neu.androidbestpractices.activity;
2 |
3 | import android.app.Activity;
4 | import android.app.Fragment;
5 |
6 | import com.neu.androidbestpractices.activity.base.BaseActivity;
7 | import com.neu.androidbestpractices.fragment.QrcodeFragment;
8 |
9 | /**
10 | * Created by neu on 16/2/23.
11 | */
12 | public class QrcodeActivity extends BaseActivity{
13 | @Override
14 | protected Activity getActivity() {
15 | return this;
16 | }
17 |
18 | @Override
19 | protected Fragment getFragment() {
20 | return new QrcodeFragment();
21 | }
22 |
23 | @Override
24 | protected CharSequence getToolbarTitle() {
25 | return "扫描二维码测试";
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/app/src/main/java/com/neu/androidbestpractices/activity/base/BaseActivity.java:
--------------------------------------------------------------------------------
1 | package com.neu.androidbestpractices.activity.base;
2 |
3 | import android.app.Activity;
4 | import android.app.Fragment;
5 | import android.os.Bundle;
6 | import android.support.design.widget.CollapsingToolbarLayout;
7 | import android.support.v7.app.ActionBar;
8 | import android.support.v7.app.AppCompatActivity;
9 | import android.support.v7.widget.Toolbar;
10 | import android.view.View;
11 |
12 | import com.neu.androidbestpractices.R;
13 |
14 | import butterknife.Bind;
15 | import butterknife.ButterKnife;
16 |
17 | /**
18 | * activity的基类
19 | * Created by neu on 16/2/3.
20 | */
21 | public abstract class BaseActivity extends AppCompatActivity {
22 |
23 | @Bind(R.id.toolBar)
24 | Toolbar mToolBar;
25 | @Bind(R.id.collapsing_toolbar)
26 | CollapsingToolbarLayout mCollapsingToolbar;
27 |
28 | @Override
29 | public void onCreate(Bundle savedInstanceState) {
30 | super.onCreate(savedInstanceState);
31 |
32 | View view = View.inflate(this, R.layout.common_activity, null);
33 | setContentView(view);
34 | ButterKnife.bind(this);
35 |
36 | //设置工具栏
37 | setSupportActionBar(mToolBar);
38 |
39 | ActionBar actionBar = getSupportActionBar();
40 | if (actionBar != null){
41 | actionBar.setDisplayHomeAsUpEnabled(true);
42 | }
43 |
44 | mCollapsingToolbar.setTitle(getToolbarTitle());
45 | getFragmentManager().beginTransaction().replace(R.id.content_frame,getFragment()).commit();
46 |
47 | mToolBar.setNavigationOnClickListener(new View.OnClickListener() {
48 | @Override
49 | public void onClick(View v) {
50 | getActivity().finish();
51 | }
52 | });
53 |
54 | }
55 |
56 | protected abstract Activity getActivity();
57 |
58 | protected abstract Fragment getFragment();
59 |
60 | protected abstract CharSequence getToolbarTitle();
61 | }
62 |
--------------------------------------------------------------------------------
/app/src/main/java/com/neu/androidbestpractices/adapter/CardViewAdapter.java:
--------------------------------------------------------------------------------
1 | package com.neu.androidbestpractices.adapter;
2 |
3 | import android.content.Context;
4 | import android.content.Intent;
5 | import android.support.v7.widget.CardView;
6 | import android.support.v7.widget.RecyclerView;
7 | import android.view.LayoutInflater;
8 | import android.view.View;
9 | import android.view.ViewGroup;
10 | import android.widget.TextView;
11 |
12 | import com.neu.androidbestpractices.R;
13 | import com.neu.androidbestpractices.pojo.ItemTest;
14 |
15 | import java.util.List;
16 |
17 | /**
18 | * adapter
19 | * Created by neu on 16/2/2.
20 | */
21 | public class CardViewAdapter extends RecyclerView.Adapter{
22 | private Context mContext;
23 | private List mList;
24 |
25 | /**
26 | * 跳转
27 | * @param position 用户点击的位置
28 | */
29 | private void redirectToDetail(int position) {
30 | Intent intent=new Intent();
31 | intent.setClassName(mContext,mList.get(position).className);
32 | mContext.startActivity(intent);
33 | }
34 | public CardViewAdapter(List list, Context context){
35 | mList=list;
36 | mContext=context;
37 | }
38 |
39 |
40 | @Override
41 | public CardViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
42 | View item= LayoutInflater.from(mContext).inflate(R.layout.adapter_item,parent,false);
43 |
44 | return new CardViewHolder(item, new CardViewHolder.ClickListener() {
45 | @Override
46 | public void onWholeClick(int position) {
47 | redirectToDetail(position);
48 | }
49 | });
50 | }
51 |
52 |
53 | @Override
54 | public void onBindViewHolder(CardViewHolder holder, int position) {
55 | final ItemTest title=mList.get(position);
56 | holder.mTextView.setText(title.itemName);
57 | }
58 |
59 | @Override
60 | public int getItemCount() {
61 | return mList.size();
62 | }
63 |
64 | public static class CardViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
65 | private TextView mTextView;
66 | private ClickListener mClickListener;
67 | private CardView list_card_view;
68 | public CardViewHolder(View itemView,ClickListener clickListener) {
69 | super(itemView);
70 | this.mClickListener=clickListener;
71 | mTextView=(TextView)itemView.findViewById(R.id.itemText);
72 | list_card_view=(CardView)itemView.findViewById(R.id.list_card_view);
73 | list_card_view.setOnClickListener(this);
74 | }
75 |
76 | @Override
77 | public void onClick(View v) {
78 | switch (v.getId()){
79 | case R.id.list_card_view:
80 | mClickListener.onWholeClick(getAdapterPosition());
81 | break;
82 | default:
83 | break;
84 | }
85 | }
86 |
87 | public interface ClickListener{
88 | void onWholeClick(int position);
89 | }
90 | }
91 | }
92 |
--------------------------------------------------------------------------------
/app/src/main/java/com/neu/androidbestpractices/fragment/ContactFragment.java:
--------------------------------------------------------------------------------
1 | package com.neu.androidbestpractices.fragment;
2 |
3 | import android.content.Intent;
4 | import android.os.Bundle;
5 | import android.support.annotation.NonNull;
6 | import android.view.View;
7 | import android.widget.Button;
8 | import android.widget.TextView;
9 |
10 | import com.neu.androidbestpractices.R;
11 | import com.neu.androidbestpractices.fragment.base.BaseFragment;
12 | import com.neu.contact.ContactFactory;
13 | import com.neu.contact.contact.Contact;
14 | import com.neu.contact.contact.ContactCallback;
15 | import com.neu.contact.contact.PermissionResultCallback;
16 |
17 | import butterknife.Bind;
18 | import butterknife.OnClick;
19 |
20 | /**
21 | * Created by neu on 16/2/3.
22 | */
23 | public class ContactFragment extends BaseFragment{
24 | @Bind(R.id.contact)
25 | Button mContactButton;
26 | @Bind(R.id.text)
27 | TextView mText;
28 | @Bind(R.id.contactUI)
29 | Button mContactUI;
30 | @OnClick({R.id.contact,R.id.contactUI})
31 | void testContactModule(Button button){
32 | switch (button.getId()){
33 | case R.id.contact:
34 |
35 | mContact.getContacts();
36 | break;
37 | case R.id.contactUI:
38 |
39 | mContact.getContactsUI();
40 | break;
41 | }
42 | }
43 |
44 | private Contact mContact;
45 |
46 | @Override
47 | protected int getFragmentLayout() {
48 | return R.layout.fragment_contact;
49 | }
50 |
51 | @Override
52 | public void onViewCreated(View view, Bundle savedInstanceState) {
53 | mContact = ContactFactory.newContact(this);
54 | }
55 |
56 | @Override
57 | public void onActivityResult(int requestCode, int resultCode, Intent data) {
58 | mContact.onActivityResult(requestCode, resultCode, data, new ContactCallback() {
59 | @Override
60 | public void onSuccess(@NonNull String contactNumber, @NonNull String contactName) {
61 | mText.setText(contactName + contactNumber);
62 | }
63 |
64 | @Override
65 | public void onFailed(@NonNull int errCode, @NonNull String message) {
66 | mText.setText(errCode + message);
67 | }
68 | });
69 |
70 | }
71 |
72 | @Override
73 | public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
74 | mContact.onRequestPermissionsResult(requestCode, permissions, grantResults, new PermissionResultCallback() {
75 |
76 | @Override
77 | public void denyPermission() {
78 | mText.setText("用户已经拒绝");
79 | }
80 | });
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/app/src/main/java/com/neu/androidbestpractices/fragment/QrcodeFragment.java:
--------------------------------------------------------------------------------
1 | package com.neu.androidbestpractices.fragment;
2 |
3 | import android.content.Intent;
4 | import android.support.annotation.NonNull;
5 | import android.widget.Button;
6 | import android.widget.ImageView;
7 | import android.widget.TextView;
8 |
9 | import com.neu.androidbestpractices.R;
10 | import com.neu.androidbestpractices.fragment.base.BaseFragment;
11 | import com.neu.qrcode.Qrcode;
12 | import com.neu.qrcode.QrcodeFactory;
13 | import com.neu.qrcode.callback.QrcodeCallback;
14 | import com.neu.qrcode.qrcode.QrcodeInfo;
15 |
16 | import butterknife.Bind;
17 | import butterknife.OnClick;
18 |
19 | /**
20 | * Created by neu on 16/2/23.
21 | */
22 | public class QrcodeFragment extends BaseFragment {
23 |
24 | @Bind(R.id.qrCode)
25 | Button mQrCodeButton;
26 | @Bind(R.id.text)
27 | TextView mText;
28 | @Bind(R.id.image)
29 | ImageView mImageView;
30 | @OnClick(R.id.qrCode)
31 | void onClick(){
32 | mQrcode = QrcodeFactory.newQrcode(this);
33 | mQrcode.start();
34 | }
35 | private Qrcode mQrcode;
36 |
37 | @Override
38 | protected int getFragmentLayout() {
39 | return R.layout.fragment_qrcode;
40 | }
41 |
42 |
43 | @Override
44 | public void onActivityResult(int requestCode, int resultCode, final Intent data) {
45 | mQrcode.onActivityResult(requestCode, resultCode, data, new QrcodeCallback() {
46 | @Override
47 | public void onSuccess(@NonNull QrcodeInfo info) {
48 | String textInfo = "二维码信息" + info.getResult() + "图片高度" + info.getHeight() + "图片宽度" + info.getWidth();
49 | mText.setText(textInfo);
50 | mImageView.setImageBitmap(info.getQrCodeImage());
51 | }
52 |
53 | @Override
54 | public void onFailed(@NonNull String errMsg) {
55 | mText.setText(errMsg);
56 | }
57 | });
58 | }
59 |
60 | @Override
61 | public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
62 | mQrcode.onRequestPermissionsResult(requestCode, permissions, grantResults, new com.neu.qrcode.callback.PermissionResultCallback() {
63 | @Override
64 | public void denyPermission() {
65 | mText.setText("App无权限");
66 | }
67 | });
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/app/src/main/java/com/neu/androidbestpractices/fragment/base/BaseFragment.java:
--------------------------------------------------------------------------------
1 | package com.neu.androidbestpractices.fragment.base;
2 |
3 | import android.app.Fragment;
4 | import android.os.Bundle;
5 | import android.support.annotation.Nullable;
6 | import android.view.LayoutInflater;
7 | import android.view.View;
8 | import android.view.ViewGroup;
9 |
10 | import butterknife.ButterKnife;
11 |
12 | /**
13 | * Created by neu on 16/2/3.
14 | */
15 | public abstract class BaseFragment extends Fragment{
16 | @Nullable
17 | @Override
18 | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
19 | View view = inflater.inflate(getFragmentLayout(),container,false);
20 | ButterKnife.bind(this,view);
21 | return view;
22 | }
23 |
24 | @Override
25 | public void onDestroyView() {
26 | super.onDestroyView();
27 | ButterKnife.unbind(this);
28 | }
29 |
30 | protected abstract int getFragmentLayout();
31 | }
32 |
--------------------------------------------------------------------------------
/app/src/main/java/com/neu/androidbestpractices/pojo/ItemTest.java:
--------------------------------------------------------------------------------
1 | package com.neu.androidbestpractices.pojo;
2 |
3 | /**
4 | * 每个item对应的pojo
5 | * Created by neu on 16/2/2.
6 | */
7 | public class ItemTest {
8 | //模块名称
9 | public String itemName;
10 | //模块测试入口
11 | public String className;
12 |
13 | public ItemTest(String itemName, String className) {
14 | this.itemName = itemName;
15 | this.className = className;
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/app/src/main/java/com/neu/androidbestpractices/widget/FixedHeightScrollingViewBehavior.java:
--------------------------------------------------------------------------------
1 | package com.neu.androidbestpractices.widget;
2 |
3 | import android.content.Context;
4 | import android.support.design.widget.AppBarLayout;
5 | import android.support.design.widget.CoordinatorLayout;
6 | import android.support.v4.view.ViewCompat;
7 | import android.util.AttributeSet;
8 | import android.view.View;
9 |
10 | import java.util.List;
11 |
12 | /**
13 | * 处理滑动问题
14 | * Created by neu on 16/2/3.
15 | */
16 | public class FixedHeightScrollingViewBehavior extends AppBarLayout.ScrollingViewBehavior {
17 | public FixedHeightScrollingViewBehavior() {
18 | }
19 |
20 | public FixedHeightScrollingViewBehavior(Context context, AttributeSet attrs) {
21 | super(context, attrs);
22 | }
23 |
24 | public boolean onMeasureChild(CoordinatorLayout parent, View child, int parentWidthMeasureSpec, int widthUsed, int parentHeightMeasureSpec, int heightUsed) {
25 | if (child.getLayoutParams().height == -1) {
26 | List dependencies = parent.getDependencies(child);
27 | if (dependencies.isEmpty()) {
28 | return false;
29 | }
30 |
31 | AppBarLayout appBar = findFirstAppBarLayout(dependencies);
32 | if (appBar != null && ViewCompat.isLaidOut(appBar)) {
33 | if (ViewCompat.getFitsSystemWindows(appBar)) {
34 | ViewCompat.setFitsSystemWindows(child, true);
35 | }
36 |
37 | int scrollRange = appBar.getTotalScrollRange();
38 | int height = parent.getHeight() - appBar.getMeasuredHeight() + Math.min(scrollRange, parent.getHeight() - heightUsed);
39 | int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY);
40 | parent.onMeasureChild(child, parentWidthMeasureSpec, widthUsed, heightMeasureSpec, heightUsed);
41 | return true;
42 | }
43 | }
44 |
45 | return false;
46 | }
47 |
48 | private static AppBarLayout findFirstAppBarLayout(List views) {
49 | int i = 0;
50 |
51 | for (int z = views.size(); i < z; ++i) {
52 | View view = (View) views.get(i);
53 | if (view instanceof AppBarLayout) {
54 | return (AppBarLayout) view;
55 | }
56 | }
57 |
58 | return null;
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
10 |
11 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/adapter_item.xml:
--------------------------------------------------------------------------------
1 |
2 |
11 |
12 |
15 |
16 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/common_activity.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
11 |
12 |
17 |
18 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
33 |
34 |
38 |
39 |
40 |
41 |
42 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/fragment_contact.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
15 |
16 |
23 |
24 |
32 |
33 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/fragment_qrcode.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
15 |
16 |
23 |
24 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/neuyu/android-best-practices/27a5fc648f04455558c98995996cc44b0b9794c2/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/neuyu/android-best-practices/27a5fc648f04455558c98995996cc44b0b9794c2/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/neuyu/android-best-practices/27a5fc648f04455558c98995996cc44b0b9794c2/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/neuyu/android-best-practices/27a5fc648f04455558c98995996cc44b0b9794c2/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/neuyu/android-best-practices/27a5fc648f04455558c98995996cc44b0b9794c2/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/values-v21/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/app/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | AndroidBestPractices
3 | 手机号:
4 | 验证码:
5 | 发送验证码
6 |
7 |
8 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
15 |
16 |
18 |
19 |
22 |
23 |
27 |
28 |
38 |
39 |
40 |
--------------------------------------------------------------------------------
/app/src/test/java/com/neu/androidbestpractices/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.neu.androidbestpractices;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * To work on unit tests, switch the Test Artifact in the Build Variants view.
9 | */
10 | public class ExampleUnitTest {
11 | @Test
12 | public void addition_isCorrect() throws Exception {
13 | assertEquals(4, 2 + 2);
14 | }
15 | }
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | jcenter()
6 | }
7 | dependencies {
8 | classpath 'com.android.tools.build:gradle:2.0.0-beta5'
9 | classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
10 | // NOTE: Do not place your application dependencies here; they belong
11 | // in the individual module build.gradle files
12 | }
13 | }
14 |
15 | allprojects {
16 | repositories {
17 | jcenter()
18 | }
19 | }
20 |
21 | task clean(type: Delete) {
22 | delete rootProject.buildDir
23 | }
24 |
25 | subprojects{
26 | configure(allprojects - project(':app')) {
27 | apply plugin: 'com.android.library'
28 | android {
29 | compileSdkVersion 23
30 | buildToolsVersion '23.0.2'
31 |
32 | defaultConfig {
33 | minSdkVersion 16
34 | targetSdkVersion 23
35 | versionCode 1
36 | versionName "1.0"
37 | }
38 | lintOptions {
39 | abortOnError false
40 | }
41 | }
42 | dependencies {
43 | testCompile 'junit:junit:4.12'
44 | compile 'com.android.support:appcompat-v7:23.1.1'
45 |
46 | }
47 | apply from: '../gradle/maven_push.gradle'
48 | }
49 | }
--------------------------------------------------------------------------------
/contact/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/contact/build.gradle:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/neuyu/android-best-practices/27a5fc648f04455558c98995996cc44b0b9794c2/contact/build.gradle
--------------------------------------------------------------------------------
/contact/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/neu/Library/Android/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/contact/src/androidTest/java/com/neu/contact/ApplicationTest.java:
--------------------------------------------------------------------------------
1 | package com.neu.contact;
2 |
3 | import android.app.Application;
4 | import android.test.ApplicationTestCase;
5 |
6 | /**
7 | * Testing Fundamentals
8 | */
9 | public class ApplicationTest extends ApplicationTestCase {
10 | public ApplicationTest() {
11 | super(Application.class);
12 | }
13 | }
--------------------------------------------------------------------------------
/contact/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/contact/src/main/java/com/neu/contact/ContactFactory.java:
--------------------------------------------------------------------------------
1 | package com.neu.contact;
2 |
3 | import android.app.Activity;
4 | import android.support.v4.app.Fragment;
5 |
6 | import com.neu.contact.contact.Contact;
7 | import com.neu.contact.contact.ContactImpl;
8 | import com.neu.contact.util.Utils;
9 |
10 |
11 | /**
12 | * Created by neuyuandaima on 2015/12/31.
13 | * 联系人构建工厂
14 | */
15 | public class ContactFactory {
16 | /**
17 | * 传入activity的Contact
18 | * @param activity 传入参数
19 | * @return 返回Contact接口对象
20 | */
21 | public static Contact newContact(Activity activity) {
22 | Utils.checkNotNull(activity, "Activity could not null or other object");
23 | return new ContactImpl(activity);
24 | }
25 |
26 | /**
27 | * 传入fragment的Contact
28 | * @param fragment 传入参数
29 | * @return 返回Contact接口对象
30 | */
31 | public static Contact newContact(Fragment fragment) {
32 | Utils.checkNotNull(fragment,"Fragment could not null or other object");
33 | return new ContactImpl(fragment);
34 | }
35 |
36 | /**
37 | * 传入fragment的Contact
38 | *
39 | * @param fragment 传入参数
40 | * @return 返回Contact接口对象
41 | */
42 | public static Contact newContact(android.app.Fragment fragment) {
43 | Utils.checkNotNull(fragment, "Fragment could not null or other object");
44 | return new ContactImpl(fragment);
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/contact/src/main/java/com/neu/contact/constants/Constants.java:
--------------------------------------------------------------------------------
1 | package com.neu.contact.constants;
2 |
3 | /**
4 | * Created by neuyuandaima on 2016/1/8.
5 | * 常量类
6 | */
7 | public class Constants {
8 | /**
9 | * 用户手机无号码或者用户权限拒绝
10 | */
11 | public static final int PERMISSION_DENY = 1;
12 | /**
13 | * 用户选择的联系人无手机号码
14 | */
15 | public static final int SELECTED_NO_MOBILE_PHONE = 2;
16 | /**
17 | * 用户选择的联系人无任何联系方式
18 | */
19 | public static final int SELECTED_NO_PHONE = 3;
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/contact/src/main/java/com/neu/contact/contact/Contact.java:
--------------------------------------------------------------------------------
1 | package com.neu.contact.contact;
2 |
3 | import android.content.Intent;
4 |
5 | /**
6 | * Created by neuyuandaima on 2015/12/31.
7 | */
8 | public interface Contact {
9 | //通过自有页面展示联系人
10 | void getContacts();
11 | //通过手机app页面展示
12 | void getContactsUI();
13 | //展示结果
14 | void onActivityResult(int requestCode, int resultCode, Intent data, ContactCallback callback);
15 | //android 6.0的动态权限
16 | void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults,PermissionResultCallback callback);
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/contact/src/main/java/com/neu/contact/contact/ContactCallback.java:
--------------------------------------------------------------------------------
1 | package com.neu.contact.contact;
2 |
3 | import android.support.annotation.NonNull;
4 |
5 | /**
6 | * Created by neuyuandaima on 2015/12/31.
7 | */
8 | public interface ContactCallback {
9 | //成功回调 contactNumber为选择的手机号码,contactName为选择的姓名
10 | void onSuccess(@NonNull String contactNumber, @NonNull String contactName);
11 |
12 | //失败回调 message为失败的原因
13 | void onFailed(@NonNull int errCode, @NonNull String message);
14 | }
15 |
--------------------------------------------------------------------------------
/contact/src/main/java/com/neu/contact/contact/ContactImpl.java:
--------------------------------------------------------------------------------
1 | package com.neu.contact.contact;
2 |
3 | import android.Manifest;
4 | import android.app.Activity;
5 | import android.app.AlertDialog;
6 | import android.app.Dialog;
7 | import android.content.Intent;
8 | import android.content.pm.PackageManager;
9 | import android.database.Cursor;
10 | import android.net.Uri;
11 | import android.os.Build;
12 | import android.provider.ContactsContract;
13 | import android.provider.ContactsContract.Contacts;
14 | import android.support.v4.app.ActivityCompat;
15 | import android.support.v4.app.Fragment;
16 | import android.view.View;
17 | import android.widget.AdapterView;
18 | import android.widget.ArrayAdapter;
19 | import android.widget.ListView;
20 |
21 | import com.neu.contact.constants.Constants;
22 | import com.neu.contact.contactui.ContactsPickerActivity;
23 | import com.neu.contact.util.PermissionUtil;
24 |
25 | import java.util.ArrayList;
26 | import java.util.List;
27 |
28 | /**
29 | * Created by neuyuandaima on 2015/12/31.
30 | * Contact接口的实现类
31 | */
32 | public final class ContactImpl implements Contact {
33 | /**
34 | * Id to identify a contacts permission request.
35 | */
36 | private static final int REQUEST_CONTACTS = 1;
37 |
38 | /**
39 | * Permissions required to read and write contacts. Used by the {@link ContactImpl}.
40 | */
41 | private static String[] PERMISSIONS_CONTACT = {Manifest.permission.READ_CONTACTS,
42 | Manifest.permission.WRITE_CONTACTS};
43 |
44 |
45 | //持有activity
46 | private Activity mActivity;
47 | //持有fragment
48 | private Fragment mSupportFragment;
49 | //持有fragment
50 | private android.app.Fragment mFragment;
51 | //回调
52 | private ContactCallback mContactCallback;
53 | //选中的姓名
54 | private String mPhoneName;
55 | //选中的手机号码
56 | private String mPhoneNum;
57 | //选中的姓名的多手机号码
58 | private List mPhoneNumList = new ArrayList<>();
59 |
60 | //构造器
61 | public ContactImpl(Activity activity) {
62 | mActivity = activity;
63 | }
64 |
65 | public ContactImpl(Fragment fragment) {
66 | mActivity = fragment.getActivity();
67 | mSupportFragment = fragment;
68 | }
69 |
70 | public ContactImpl(android.app.Fragment fragment) {
71 | mActivity = fragment.getActivity();
72 | mFragment = fragment;
73 | }
74 |
75 | @Override
76 | public void getContacts() {
77 | //检查是否具有该权限
78 | checkPremission();
79 | }
80 |
81 | /**
82 | * 跳转到app 内置应用
83 | */
84 | private void startContact() {
85 | if (mFragment != null) {
86 | Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
87 | mFragment.startActivityForResult(intent, 2);
88 | } else if (mSupportFragment != null) {
89 | Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
90 | mSupportFragment.startActivityForResult(intent, 2);
91 | } else {
92 | Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
93 | mActivity.startActivityForResult(intent, 2);
94 | }
95 | }
96 |
97 | /**
98 | * 检查是否具有该权限
99 | */
100 | private void checkPremission() {
101 | //当Android6.0以下,申明了权限,直接startIntent()
102 | if (ActivityCompat.checkSelfPermission(mActivity, Manifest.permission.READ_CONTACTS)
103 | != PackageManager.PERMISSION_GRANTED
104 | || ActivityCompat.checkSelfPermission(mActivity, Manifest.permission.WRITE_CONTACTS)
105 | != PackageManager.PERMISSION_GRANTED) {
106 | // Contacts permissions have not been granted.
107 | requestContactsPermissions();
108 |
109 | } else {
110 | // Contact permissions have been granted. Show the contacts fragment.
111 | startContact();
112 | }
113 | }
114 |
115 | /**
116 | * 6.0以上的,弹出权限选择框
117 | */
118 | private void requestContactsPermissions() {
119 | //判断该权限是否需要
120 | if (mFragment != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
121 | mFragment.requestPermissions(PERMISSIONS_CONTACT, REQUEST_CONTACTS);
122 | } else if (mSupportFragment != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
123 | mSupportFragment.requestPermissions(PERMISSIONS_CONTACT, REQUEST_CONTACTS);
124 | } else {
125 | //Android6.0以上的手机启动contact,且是activity启动的
126 | //Android6.0以下的手机,具有权限管理,且关闭了app的联系人权限
127 | // TODO: 16/2/17 当Android6.0以下手机调用方必须是在其activity中实现OnRequestPermissionsResultCallback,且调用contact的onRequestPermissionsResult
128 | //不实现OnRequestPermissionsResultCallback的话,无法接收消息,fragmentactivity实现了该接口
129 | //所以当你的activity是fragmentactivity的子类或者appcompatActivity的子类,可以不实现其接口
130 | ActivityCompat.requestPermissions(mActivity, PERMISSIONS_CONTACT, REQUEST_CONTACTS);
131 | }
132 | }
133 |
134 | @Override
135 | public void getContactsUI() {
136 | //判断传入的是activity还是fragment还是v4 fragment
137 | if (mSupportFragment != null) {
138 | Intent intent = new Intent(mActivity, ContactsPickerActivity.class);
139 | mSupportFragment.startActivityForResult(intent, 1);
140 | } else if (mFragment != null) {
141 | Intent intent = new Intent(mActivity, ContactsPickerActivity.class);
142 | mFragment.startActivityForResult(intent, 1);
143 | } else {
144 | Intent intent = new Intent(mActivity, ContactsPickerActivity.class);
145 | mActivity.startActivityForResult(intent, 1);
146 | }
147 |
148 | }
149 |
150 | @Override
151 | public void onActivityResult(int requestCode, int resultCode, Intent data, ContactCallback callback) {
152 | //判断用户选择是的哪一种打开方式
153 | if (requestCode == 1 && resultCode == Activity.RESULT_OK) {//自定义UI
154 | mContactCallback = callback;
155 | String number = data.getStringExtra(ContactsPickerActivity.KEY_PHONE_NUMBER);
156 | String name = data.getStringExtra(ContactsPickerActivity.KEY_CONTACT_NAME);
157 | mContactCallback.onSuccess(number, name);
158 | } else if (resultCode == Activity.RESULT_OK) {//默认ui
159 | mContactCallback = callback;
160 | getContactPhone(data);
161 | }
162 | }
163 |
164 | /**
165 | * 处理权限结果
166 | * @param requestCode 发送号码
167 | * @param permissions 权限数组
168 | * @param grantResults 返回结果
169 | * @param callback 否决回调
170 | */
171 | @Override
172 | public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults, PermissionResultCallback callback) {
173 | if (requestCode == REQUEST_CONTACTS) {
174 | // We have requested multiple permissions for contacts, so all of them need to be
175 | // checked.
176 | if (PermissionUtil.verifyPermissions(grantResults)) {
177 | // All required permissions have been granted, display contacts fragment.
178 | startContact();
179 | } else {
180 | callback.denyPermission();
181 | }
182 |
183 | }
184 | }
185 |
186 | /**
187 | * 获取联系人信息
188 | *
189 | * @param data 点击联系人返回的结果
190 | */
191 | private void getContactPhone(Intent data) {
192 | Uri contactData = data.getData();
193 | Cursor cursor = mActivity
194 | .getContentResolver()
195 | .query(contactData, null, null, null, null);
196 | if (cursor == null || cursor.getCount() < 1) {
197 | sendBackResult(false, Constants.PERMISSION_DENY, "获取联系人失败");
198 | } else {
199 | handleCursor(cursor);
200 | }
201 | }
202 |
203 | /**
204 | * 返回结果
205 | * @param result 获取联系人是否成功
206 | * @param errCode 错误码
207 | * @param errMsg 错误信息
208 | */
209 | private void sendBackResult(boolean result, int errCode, String errMsg) {
210 | if (!result) {
211 | mContactCallback.onFailed(errCode, errMsg);
212 | } else if (mPhoneNumList.size() < 2) {
213 | mContactCallback.onSuccess(mPhoneNum, mPhoneName);
214 | } else {
215 | showDialog();
216 | }
217 | }
218 |
219 | /**
220 | * 处理cursor
221 | * @param cursor 查询游标
222 | */
223 | private void handleCursor(Cursor cursor) {
224 | cursor.moveToFirst();
225 | int phoneCount = cursor.getInt(cursor.getColumnIndex(Contacts.HAS_PHONE_NUMBER));
226 | if (phoneCount > 0) {
227 | // 获得联系人的ID号
228 | String contactId = cursor.getString(cursor.getColumnIndex(Contacts._ID));
229 | Cursor phone = mActivity.getContentResolver()
230 | .query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
231 | null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactId, null, null);
232 | try {
233 | while (null != phone && phone.moveToNext()) {
234 | mPhoneName = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
235 | mPhoneNum = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
236 | mPhoneNumList.add(mPhoneNum);
237 | }
238 | } finally {
239 | //当用户点击的该联系人无手机号码,但有其他联系方式
240 | if (mPhoneName == null || mPhoneNum == null || mPhoneNumList.size() == 0) {
241 | sendBackResult(false, Constants.SELECTED_NO_MOBILE_PHONE, "该联系人无手机号码");
242 | } else {//成功
243 | sendBackResult(true, 0, null);
244 | }
245 | //关闭cursor
246 | if (phone != null) {
247 | phone.close();
248 | }
249 | }
250 | } else {
251 | //用户点击的联系人无联系方式
252 | sendBackResult(false, Constants.SELECTED_NO_PHONE, "该联系人无联系方式");
253 | }
254 | cursor.close();
255 | }
256 |
257 | /**
258 | * 当联系人有多个联系方式
259 | */
260 | private void showDialog() {
261 | ListView listView = new ListView(mActivity);
262 | final Dialog mDialog = new AlertDialog.Builder(mActivity, AlertDialog.THEME_DEVICE_DEFAULT_DARK).setView(listView)
263 | .create();
264 | mDialog.setTitle("请选择手机号码");
265 | listView.setAdapter(new ArrayAdapter(mActivity, android.R.layout.simple_expandable_list_item_1, mPhoneNumList));
266 | listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
267 | @Override
268 | public void onItemClick(AdapterView> parent, View v, int position, long id) {
269 | if (mDialog.isShowing()) {
270 | mDialog.dismiss();
271 | }
272 | mPhoneNum = mPhoneNumList.get(position);
273 | mContactCallback.onSuccess(mPhoneNum, mPhoneName);
274 | }
275 | });
276 |
277 | mDialog.show();
278 | }
279 |
280 | }
281 |
--------------------------------------------------------------------------------
/contact/src/main/java/com/neu/contact/contact/PermissionResultCallback.java:
--------------------------------------------------------------------------------
1 | package com.neu.contact.contact;
2 |
3 | /**
4 | * Created by neu on 16/2/16.
5 | * 权限结果
6 | */
7 | public interface PermissionResultCallback {
8 | //用户点击否定
9 | void denyPermission();
10 |
11 | }
12 |
--------------------------------------------------------------------------------
/contact/src/main/java/com/neu/contact/contactui/ContactDetailsFragment.java:
--------------------------------------------------------------------------------
1 | package com.neu.contact.contactui;
2 |
3 | import android.app.Activity;
4 | import android.content.Context;
5 | import android.database.Cursor;
6 | import android.net.Uri;
7 | import android.os.Bundle;
8 | import android.provider.ContactsContract.CommonDataKinds.Phone;
9 | import android.support.v4.app.ListFragment;
10 | import android.support.v4.widget.SimpleCursorAdapter;
11 | import android.view.LayoutInflater;
12 | import android.view.View;
13 | import android.view.ViewGroup;
14 | import android.widget.ListAdapter;
15 | import android.widget.ListView;
16 | import android.widget.TextView;
17 |
18 | import com.neu.contact.R;
19 |
20 |
21 | /**
22 | * Created by yuxiaole on 2015/12/31.
23 | *
24 | */
25 | public final class ContactDetailsFragment extends ListFragment {
26 | private TextView mDisplayName;
27 | private OnContactSelectedListener mContactsListener;
28 | private Cursor mCursor;
29 |
30 | @Override
31 | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
32 | return inflater.inflate(R.layout.library_fragment_contact_detail, container, false);
33 | }
34 |
35 | @Override
36 | public void onListItemClick(ListView l, View v, int position, long id) {
37 | super.onListItemClick(l, v, position, id);
38 |
39 | TextView tv = (TextView) v.findViewById(R.id.phone_number);
40 | String number = tv.getText().toString();
41 | String name = mDisplayName.getText().toString();
42 |
43 | mContactsListener.onContactNumberSelected(number, name);
44 | }
45 |
46 | @Override
47 | public void onAttach(Activity activity) {
48 | super.onAttach(activity);
49 |
50 | try {
51 | mContactsListener = (OnContactSelectedListener) activity;
52 | } catch (ClassCastException e) {
53 | throw new ClassCastException(activity.toString() + " must implement OnContactSelectedListener");
54 | }
55 | }
56 |
57 | @Override
58 | public void onActivityCreated(Bundle savedInstanceState) {
59 | super.onActivityCreated(savedInstanceState);
60 |
61 | long personId = getArguments().getLong(ContactsPickerActivity.SELECTED_CONTACT_ID);// getIntent().getLongExtra("id", 0);
62 | Activity activity = getActivity();
63 |
64 | Uri phonesUri = Phone.CONTENT_URI;
65 | String[] projection = new String[]{
66 | Phone._ID, Phone.DISPLAY_NAME,
67 | Phone.TYPE, Phone.NUMBER, Phone.LABEL};
68 | String selection = Phone.CONTACT_ID + " = ?";
69 | String[] selectionArgs = new String[]{Long.toString(personId)};
70 |
71 | mCursor = activity.getContentResolver().query(phonesUri,
72 | projection, selection, selectionArgs, null);
73 |
74 | mDisplayName = (TextView) activity.findViewById(R.id.display_name);
75 | if (mCursor.moveToFirst()) {
76 | mDisplayName.setText(mCursor.getString(mCursor.getColumnIndex(Phone.DISPLAY_NAME)));
77 | }
78 |
79 | ListAdapter adapter = new PhoneNumbersAdapter(this.getActivity(),
80 | R.layout.library_list_item_phone_number, mCursor,
81 | new String[]{Phone.TYPE, Phone.NUMBER},
82 | new int[]{R.id.label, R.id.phone_number});
83 | setListAdapter(adapter);
84 | }
85 |
86 | class PhoneNumbersAdapter extends SimpleCursorAdapter {
87 |
88 | public PhoneNumbersAdapter(Context context, int layout, Cursor c,
89 | String[] from, int[] to) {
90 | super(context, layout, c, from, to, 0);
91 | }
92 |
93 | @Override
94 | public void bindView(View view, Context context, Cursor cursor) {
95 | super.bindView(view, context, cursor);
96 |
97 | TextView tx = (TextView) view.findViewById(R.id.label);
98 | int type = cursor.getInt(cursor.getColumnIndex(Phone.TYPE));
99 | String label = cursor.getString(cursor.getColumnIndex(Phone.LABEL));
100 | label = Phone.getTypeLabel(getResources(), type, label).toString();
101 |
102 | tx.setText(label);
103 | }
104 | }
105 | }
106 |
--------------------------------------------------------------------------------
/contact/src/main/java/com/neu/contact/contactui/ContactsListFragment.java:
--------------------------------------------------------------------------------
1 | package com.neu.contact.contactui;
2 |
3 | import android.annotation.SuppressLint;
4 | import android.app.Activity;
5 | import android.content.Context;
6 | import android.content.Intent;
7 | import android.database.Cursor;
8 | import android.net.Uri;
9 | import android.os.AsyncTask;
10 | import android.os.Build;
11 | import android.os.Bundle;
12 | import android.provider.ContactsContract.CommonDataKinds.Phone;
13 | import android.provider.ContactsContract.Contacts;
14 | import android.provider.ContactsContract.Data;
15 | import android.support.v4.app.ListFragment;
16 | import android.support.v4.app.LoaderManager;
17 | import android.support.v4.content.CursorLoader;
18 | import android.support.v4.content.Loader;
19 | import android.support.v4.view.MenuItemCompat;
20 | import android.support.v4.widget.SimpleCursorAdapter;
21 | import android.support.v7.widget.SearchView;
22 | import android.text.TextUtils;
23 | import android.view.LayoutInflater;
24 | import android.view.Menu;
25 | import android.view.MenuInflater;
26 | import android.view.MenuItem;
27 | import android.view.View;
28 | import android.view.ViewGroup;
29 | import android.widget.AlphabetIndexer;
30 | import android.widget.ListView;
31 | import android.widget.SectionIndexer;
32 | import android.widget.TextView;
33 |
34 | import com.neu.contact.R;
35 |
36 | import java.lang.ref.WeakReference;
37 |
38 | /**
39 | * Created by neuyuandaima on 2015/12/31.
40 | */
41 | public final class ContactsListFragment extends ListFragment implements
42 | LoaderManager.LoaderCallbacks, SearchView.OnQueryTextListener, SearchView.OnCloseListener {
43 | @SuppressLint("InlinedApi")
44 | private static String DISPLAY_NAME_COMPAT = Build.VERSION.SDK_INT
45 | >= Build.VERSION_CODES.HONEYCOMB ?
46 | Contacts.DISPLAY_NAME_PRIMARY :
47 | Contacts.DISPLAY_NAME;
48 | private static final String[] CONTACTS_SUMMARY_PROJECTION = new String[]{
49 | Contacts._ID,
50 | DISPLAY_NAME_COMPAT,
51 | Contacts.HAS_PHONE_NUMBER,
52 | Contacts.LOOKUP_KEY
53 | };
54 | private OnContactSelectedListener mContactsListener;
55 | private SimpleCursorAdapter mAdapter;
56 | private String mSearchString = null;
57 | private SearchView mSearchView;
58 |
59 | @Override
60 | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
61 | return inflater.inflate(R.layout.library_fragment_contacts_list, container, false);
62 | }
63 |
64 | @Override
65 | public void onListItemClick(ListView l, View v, int position, long id) {
66 | ViewHolder viewHolder = (ViewHolder) v.getTag();
67 | String phoneNumber = viewHolder.phoneNumber.getText().toString();
68 | String name = viewHolder.contactName.getText().toString();
69 |
70 | if (phoneNumber.equals(getString(R.string.label_multiple_numbers))) {
71 | mContactsListener.onContactNameSelected(id);
72 | } else {
73 | mContactsListener.onContactNumberSelected(phoneNumber, name);
74 | }
75 | }
76 |
77 | @Override
78 | public void onAttach(Activity activity) {
79 | super.onAttach(activity);
80 | try {
81 | mContactsListener = (OnContactSelectedListener) activity;
82 | } catch (ClassCastException e) {
83 | throw new ClassCastException(activity.toString() + " must implement OnContactSelectedListener");
84 | }
85 | }
86 |
87 | @Override
88 | public void onActivityCreated(Bundle savedInstanceState) {
89 | super.onActivityCreated(savedInstanceState);
90 | setHasOptionsMenu(true);
91 | getLoaderManager().initLoader(0, null, this);
92 |
93 | mAdapter = new IndexedListAdapter(
94 | this.getActivity(),
95 | R.layout.library_list_item_contacts,
96 | null,
97 | new String[]{Contacts.DISPLAY_NAME},
98 | new int[]{R.id.display_name});
99 |
100 | setListAdapter(mAdapter);
101 | getListView().setFastScrollEnabled(true);
102 |
103 | }
104 |
105 | @Override
106 | public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
107 | inflater.inflate(R.menu.library_main, menu);
108 | mSearchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
109 | mSearchView.setOnQueryTextListener(this);
110 | mSearchView.setOnCloseListener(this);
111 | }
112 |
113 | @Override
114 | public boolean onOptionsItemSelected(MenuItem item) {
115 | int actionId = item.getItemId();
116 | if (actionId == R.id.action_add_contact) {
117 | Intent intent = new Intent(Intent.ACTION_INSERT,
118 | Contacts.CONTENT_URI);
119 | startActivity(intent);
120 | return true;
121 | }
122 |
123 | if (actionId == android.R.id.home) {
124 | getActivity().finish();
125 | }
126 |
127 | return super.onOptionsItemSelected(item);
128 | }
129 |
130 | @Override
131 | public Loader onCreateLoader(int arg0, Bundle arg1) {
132 | Uri baseUri;
133 |
134 | if (mSearchString != null) {
135 | baseUri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI,
136 | Uri.encode(mSearchString));
137 | } else {
138 | baseUri = Contacts.CONTENT_URI;
139 | }
140 |
141 | String selection = "((" + DISPLAY_NAME_COMPAT + " NOTNULL) AND ("
142 | + Contacts.HAS_PHONE_NUMBER + "=1) AND ("
143 | + DISPLAY_NAME_COMPAT + " != '' ))";
144 |
145 | String sortOrder = Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
146 |
147 | return new CursorLoader(getActivity(), baseUri, CONTACTS_SUMMARY_PROJECTION, selection, null, sortOrder);
148 | }
149 |
150 | @Override
151 | public void onLoadFinished(Loader loader, Cursor data) {
152 | mAdapter.swapCursor(data);
153 | }
154 |
155 | @Override
156 | public void onLoaderReset(Loader loader) {
157 | mAdapter.swapCursor(null);
158 | }
159 |
160 | @Override
161 | public boolean onClose() {
162 | if (!TextUtils.isEmpty(mSearchView.getQuery())) {
163 | mSearchView.setQuery(null, true);
164 | }
165 | return true;
166 | }
167 |
168 | @Override
169 | public boolean onQueryTextSubmit(String s) {
170 | return true;
171 | }
172 |
173 | @Override
174 | public boolean onQueryTextChange(String newText) {
175 | String newFilter = !TextUtils.isEmpty(newText) ? newText : null;
176 |
177 | if (mSearchString == null && newFilter == null) {
178 | return true;
179 | }
180 | if (mSearchString != null && mSearchString.equals(newFilter)) {
181 | return true;
182 | }
183 | mSearchString = newFilter;
184 | getLoaderManager().restartLoader(0, null, this);
185 | return true;
186 | }
187 |
188 | static class ViewHolder {
189 | TextView contactName;
190 | TextView phoneLabel;
191 | TextView phoneNumber;
192 | View separator;
193 | PhoneNumberLookupTask phoneNumberLookupTask;
194 | }
195 |
196 | class IndexedListAdapter extends SimpleCursorAdapter implements SectionIndexer {
197 |
198 | AlphabetIndexer alphaIndexer;
199 |
200 | public IndexedListAdapter(Context context, int layout, Cursor c,
201 | String[] from, int[] to) {
202 | super(context, layout, c, from, to, 0);
203 | }
204 |
205 | @Override
206 | public View getView(int position, View convertView, ViewGroup parent) {
207 | ViewHolder viewHolder;
208 | if (convertView == null) {
209 | LayoutInflater inflater = getLayoutInflater(null);
210 | convertView = inflater.inflate(R.layout.library_list_item_contacts, parent, false);
211 | viewHolder = new ViewHolder();
212 | viewHolder.contactName = (TextView) convertView.findViewById(R.id.display_name);
213 | viewHolder.phoneLabel = (TextView) convertView.findViewById(R.id.phone_label);
214 | viewHolder.phoneNumber = (TextView) convertView.findViewById(R.id.phone_number);
215 | viewHolder.separator = convertView.findViewById(R.id.label_separator);
216 | convertView.setTag(viewHolder);
217 | } else {
218 | viewHolder = (ViewHolder) convertView.getTag();
219 | viewHolder.phoneNumberLookupTask.cancel(true);
220 | }
221 |
222 | return super.getView(position, convertView, parent);
223 | }
224 |
225 | @Override
226 | public void bindView(View view, Context context, Cursor cursor) {
227 | super.bindView(view, context, cursor);
228 |
229 | long contactId = cursor.getLong(cursor.getColumnIndexOrThrow(Contacts._ID));
230 | ViewHolder viewHolder = (ViewHolder) view.getTag();
231 | viewHolder.phoneNumberLookupTask = new PhoneNumberLookupTask(view);
232 | viewHolder.phoneNumberLookupTask.execute(contactId);
233 | }
234 |
235 | @Override
236 | public Cursor swapCursor(Cursor c) {
237 | if (c != null&&c.getCount()>0) {
238 | alphaIndexer = new AlphabetIndexer(c,
239 | c.getColumnIndex(Contacts.DISPLAY_NAME),
240 | " ABCDEFGHIJKLMNOPQRSTUVWXYZ");
241 | }
242 | return super.swapCursor(c);
243 | }
244 |
245 | @Override
246 | public Object[] getSections() {
247 | return alphaIndexer == null ? null : alphaIndexer.getSections();
248 | }
249 |
250 | @Override
251 | public int getPositionForSection(int section) {
252 | return alphaIndexer.getPositionForSection(section);
253 | }
254 |
255 | @Override
256 | public int getSectionForPosition(int position) {
257 | return alphaIndexer.getSectionForPosition(position);
258 | }
259 | }
260 |
261 | /**
262 | * Task for looking up the phone number and displaying it next to the contact.
263 | * This task holds a weak reference to the view so that if it is recycled while task is running,
264 | * then the task does nothing.
265 | */
266 | private class PhoneNumberLookupTask extends AsyncTask {
267 | final WeakReference mViewReference;
268 |
269 | String mPhoneNumber;
270 | String mPhoneLabel;
271 |
272 | public PhoneNumberLookupTask(View view) {
273 | mViewReference = new WeakReference<>(view);
274 | }
275 |
276 | @Override
277 | protected Void doInBackground(Long... ids) {
278 | String[] projection = new String[]{Phone.DISPLAY_NAME, Phone.TYPE, Phone.NUMBER, Phone.LABEL};
279 | long contactId = ids[0];
280 |
281 | final Cursor phoneCursor = getActivity().getContentResolver().query(
282 | Phone.CONTENT_URI,
283 | projection,
284 | Data.CONTACT_ID + "=?",
285 | new String[]{String.valueOf(contactId)},
286 | null);
287 |
288 | if (phoneCursor != null && phoneCursor.moveToFirst() && phoneCursor.getCount() == 1) {
289 | final int contactNumberColumnIndex = phoneCursor.getColumnIndex(Phone.NUMBER);
290 | mPhoneNumber = phoneCursor.getString(contactNumberColumnIndex);
291 | int type = phoneCursor.getInt(phoneCursor.getColumnIndexOrThrow(Phone.TYPE));
292 | mPhoneLabel = phoneCursor.getString(phoneCursor.getColumnIndex(Phone.LABEL));
293 | mPhoneLabel = Phone.getTypeLabel(getResources(), type, mPhoneLabel).toString();
294 | phoneCursor.close();
295 | }
296 |
297 | return null;
298 | }
299 |
300 | @Override
301 | protected void onPostExecute(Void param) {
302 | View view = mViewReference.get();
303 | if (view != null) {
304 | ViewHolder viewHolder = (ViewHolder) view.getTag();
305 | if (mPhoneNumber != null) {
306 | viewHolder.phoneNumber.setText(mPhoneNumber);
307 | viewHolder.phoneLabel.setText(mPhoneLabel);
308 | viewHolder.phoneLabel.setVisibility(View.VISIBLE);
309 | viewHolder.separator.setVisibility(View.VISIBLE);
310 | } else {
311 | viewHolder.phoneNumber.setText(getString(R.string.label_multiple_numbers));
312 | viewHolder.phoneLabel.setVisibility(View.GONE);
313 | viewHolder.separator.setVisibility(View.GONE);
314 | }
315 |
316 | }
317 | }
318 | }
319 | }
320 |
--------------------------------------------------------------------------------
/contact/src/main/java/com/neu/contact/contactui/ContactsPickerActivity.java:
--------------------------------------------------------------------------------
1 | package com.neu.contact.contactui;
2 |
3 | import android.content.Intent;
4 | import android.os.Bundle;
5 | import android.support.v4.app.Fragment;
6 | import android.support.v4.app.FragmentTransaction;
7 | import android.support.v7.app.ActionBar;
8 | import android.support.v7.app.AppCompatActivity;
9 |
10 | import com.neu.contact.R;
11 |
12 |
13 | /**
14 | * Created by neuyuandaima on 2015/12/31.
15 | */
16 | public final class ContactsPickerActivity extends AppCompatActivity implements OnContactSelectedListener {
17 | public static final String SELECTED_CONTACT_ID = "contact_id";
18 | public static final String KEY_PHONE_NUMBER = "phone_number";
19 | public static final String KEY_CONTACT_NAME = "contact_name";
20 |
21 | /**
22 | * Starting point
23 | * Loads the {@link ContactsListFragment}
24 | */
25 | @Override
26 | protected void onCreate(Bundle savedInstanceState) {
27 | super.onCreate(savedInstanceState);
28 | setContentView(R.layout.library_activity_contacts);
29 |
30 | if (savedInstanceState == null) {
31 | FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
32 | ContactsListFragment fragment = new ContactsListFragment();
33 | transaction.replace(R.id.fragment_container, fragment);
34 | transaction.commit();
35 | }
36 |
37 | ActionBar actionBar = getSupportActionBar();
38 | if (actionBar != null) {
39 | actionBar.setDisplayHomeAsUpEnabled(true);
40 | actionBar.setTitle("Select contact");
41 | }
42 | }
43 |
44 |
45 |
46 | /**
47 | * Callback when the contact is selected from the list of contacts.
48 | * Loads the {@link ContactDetailsFragment}
49 | */
50 | @Override
51 | public void onContactNameSelected(long contactId) {
52 | /* Now that we know which Contact was selected we can go to the details fragment */
53 |
54 | Fragment detailsFragment = new ContactDetailsFragment();
55 | Bundle args = new Bundle();
56 | args.putLong(ContactsPickerActivity.SELECTED_CONTACT_ID, contactId);
57 | detailsFragment.setArguments(args);
58 | FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
59 |
60 | transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
61 | // Replace whatever is in the fragment_container view with this fragment,
62 | // and add the transaction to the back stack
63 | transaction.replace(R.id.fragment_container, detailsFragment);
64 |
65 | transaction.addToBackStack(null);
66 | // Commit the transaction
67 | transaction.commit();
68 | }
69 |
70 | /**
71 | * Callback when the contact number is selected from the contact details view
72 | * Sets the activity result with the contact information and finishes
73 | */
74 | @Override
75 | public void onContactNumberSelected(String contactNumber, String contactName) {
76 | Intent intent = new Intent();
77 | intent.putExtra(KEY_PHONE_NUMBER, contactNumber);
78 | intent.putExtra(KEY_CONTACT_NAME, contactName);
79 | setResult(RESULT_OK, intent);
80 | finish();
81 | }
82 |
83 |
84 | }
85 |
--------------------------------------------------------------------------------
/contact/src/main/java/com/neu/contact/contactui/OnContactSelectedListener.java:
--------------------------------------------------------------------------------
1 | package com.neu.contact.contactui;
2 |
3 | /**
4 | * Created by neuyuandaima on 2015/12/31.
5 | */
6 | interface OnContactSelectedListener {
7 | /**
8 | * Callback when the contact is selected from the list of contacts
9 | * @param contactId Long ID of the contact which was selected.
10 | */
11 | void onContactNameSelected(long contactId);
12 |
13 | /**
14 | * Callback when the contact number is selected from the contact details view
15 | * @param contactNumber String with the number which was selected
16 | * @param contactName Name of the contact which was selected as String
17 | */
18 | void onContactNumberSelected(String contactNumber, String contactName);
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/contact/src/main/java/com/neu/contact/util/PermissionUtil.java:
--------------------------------------------------------------------------------
1 | package com.neu.contact.util;
2 |
3 | import android.app.Activity;
4 | import android.content.pm.PackageManager;
5 |
6 | /**
7 | * 验证permission是否全部通过
8 | */
9 | public abstract class PermissionUtil {
10 | /**
11 | * Check that all given permissions have been granted by verifying that each entry in the
12 | * given array is of the value {@link PackageManager#PERMISSION_GRANTED}.
13 | *
14 | * @see Activity#onRequestPermissionsResult(int, String[], int[])
15 | */
16 | public static boolean verifyPermissions(int[] grantResults) {
17 | // At least one result must be checked.
18 | if(grantResults.length < 1){
19 | return false;
20 | }
21 |
22 | // Verify that each required permission has been granted, otherwise return false.
23 | for (int result : grantResults) {
24 | if (result != PackageManager.PERMISSION_GRANTED) {
25 | return false;
26 | }
27 | }
28 | return true;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/contact/src/main/java/com/neu/contact/util/Utils.java:
--------------------------------------------------------------------------------
1 | package com.neu.contact.util;
2 |
3 | /**
4 | * Created by neuyuandaima on 2015/12/28.
5 | * 工具类
6 | */
7 | public class Utils {
8 | /**
9 | * 校验给定对象是否为空及其属性是否为空
10 | * @param object 给定对象
11 | * @param message 抛出错误信息
12 | * @param 返回类型
13 | * @return 返回对象
14 | */
15 | public static T checkNotNull(T object, String message) {
16 | if (object == null) {
17 | throw new NullPointerException(message);
18 | }
19 | /* for (Field f : object.getClass().getDeclaredFields()) {
20 | f.setAccessible(true);
21 | try {
22 | if (f.get(object) == null) { //判断字段是否为空,并且对象属性中的基本都会转为对象类型来判断
23 | throw new NullPointerException(message);
24 | }
25 | } catch (IllegalAccessException e) {
26 | e.printStackTrace();
27 | }
28 | }*/
29 | return object;
30 | }
31 |
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/contact/src/main/res/drawable-hdpi/library_ic_action_search.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/neuyu/android-best-practices/27a5fc648f04455558c98995996cc44b0b9794c2/contact/src/main/res/drawable-hdpi/library_ic_action_search.png
--------------------------------------------------------------------------------
/contact/src/main/res/drawable-hdpi/library_ic_person_add_white_48dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/neuyu/android-best-practices/27a5fc648f04455558c98995996cc44b0b9794c2/contact/src/main/res/drawable-hdpi/library_ic_person_add_white_48dp.png
--------------------------------------------------------------------------------
/contact/src/main/res/drawable-xhdpi/library_ic_action_search.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/neuyu/android-best-practices/27a5fc648f04455558c98995996cc44b0b9794c2/contact/src/main/res/drawable-xhdpi/library_ic_action_search.png
--------------------------------------------------------------------------------
/contact/src/main/res/drawable-xhdpi/library_ic_person_add_white_48dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/neuyu/android-best-practices/27a5fc648f04455558c98995996cc44b0b9794c2/contact/src/main/res/drawable-xhdpi/library_ic_person_add_white_48dp.png
--------------------------------------------------------------------------------
/contact/src/main/res/layout/library_activity_contacts.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
8 |
--------------------------------------------------------------------------------
/contact/src/main/res/layout/library_fragment_contact_detail.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
8 |
9 |
20 |
21 |
26 |
27 |
--------------------------------------------------------------------------------
/contact/src/main/res/layout/library_fragment_contacts_list.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
11 |
12 |
19 |
20 |
--------------------------------------------------------------------------------
/contact/src/main/res/layout/library_list_item_contacts.xml:
--------------------------------------------------------------------------------
1 |
2 |
10 |
11 |
22 |
23 |
26 |
32 |
33 |
39 |
47 |
48 |
--------------------------------------------------------------------------------
/contact/src/main/res/layout/library_list_item_phone_number.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
17 |
18 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/contact/src/main/res/menu/library_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/contact/src/main/res/values/library_strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Contact
3 | Search
4 | 多个号码
5 |
6 |
--------------------------------------------------------------------------------
/contact/src/main/res/values/library_styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
11 |
--------------------------------------------------------------------------------
/contact/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m
13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
14 |
15 | # When configured, Gradle will run in incubating parallel mode.
16 | # This option should only be used with decoupled projects. More details, visit
17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
18 | # org.gradle.parallel=true
--------------------------------------------------------------------------------
/gradle/maven_push.gradle:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/neuyu/android-best-practices/27a5fc648f04455558c98995996cc44b0b9794c2/gradle/maven_push.gradle
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/neuyu/android-best-practices/27a5fc648f04455558c98995996cc44b0b9794c2/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Tue Feb 16 10:52:42 HKT 2016
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.11-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/httpclient/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/httpclient/build.gradle:
--------------------------------------------------------------------------------
1 | dependencies {
2 | compile 'com.squareup.okhttp3:okhttp:3.1.1'
3 | }
--------------------------------------------------------------------------------
/httpclient/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/neu/Library/Android/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/httpclient/src/androidTest/java/com/neu/httpclient/ApplicationTest.java:
--------------------------------------------------------------------------------
1 | package com.neu.httpclient;
2 |
3 | import android.app.Application;
4 | import android.test.ApplicationTestCase;
5 |
6 | /**
7 | * Testing Fundamentals
8 | */
9 | public class ApplicationTest extends ApplicationTestCase {
10 | public ApplicationTest() {
11 | super(Application.class);
12 | }
13 | }
--------------------------------------------------------------------------------
/httpclient/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/httpclient/src/main/java/com/neu/httpclient/HttpCallback.java:
--------------------------------------------------------------------------------
1 | package com.neu.httpclient;
2 |
3 | /**
4 | *Created by neu on 16/2/9.
5 | */
6 | public abstract class HttpCallback extends TType implements ProgressListener {
7 |
8 | /**
9 | * 请求失败回调的函数,请求失败包括服务器未返回,或服务器返回的HTTP STATUS CODE标示失败
10 | *
11 | * @param httpStatusCode
12 | * @param message
13 | * @param throwable 如果httpStatusCode为-1的话,由该参数标识发生的异常
14 | */
15 | public abstract void onFailure(int httpStatusCode, String message, Throwable throwable);
16 |
17 | /**
18 | * 请求成功回调的函数,请求成功仅表示服务器正常处理请求了,不代表业务处理成功
19 | *
20 | * @param httpStatusCode
21 | * @param responseObject
22 | */
23 | public abstract void onSuccess(int httpStatusCode, T responseObject);
24 |
25 | @Override
26 | public void onProgress(long bytesCount, long contentLength, boolean done) {
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/httpclient/src/main/java/com/neu/httpclient/HttpRequest.java:
--------------------------------------------------------------------------------
1 | package com.neu.httpclient;
2 |
3 | import java.util.Map;
4 |
5 | /**
6 | *
7 | * Created by neu on 16/2/9.
8 | */
9 | public interface HttpRequest {
10 |
11 | /**
12 | * 发起HTTP GET同步请求
13 | *
14 | * @param ttype
15 | * @param url
16 | * @param parameters 请求的参数,参数将拼接到url中,允许为null
17 | * @param 支持返回实体对像,当指定为String.class时,返回的是字符串
18 | * @return
19 | */
20 | T get(TType ttype, String url, Map parameters);
21 |
22 | /**
23 | * 发起HTTP GET同步请求
24 | *
25 | * @param url
26 | * @param parameters
27 | * @return
28 | */
29 | String get(String url, Map parameters);
30 |
31 | /**
32 | * 发起HTTP异步请求
33 | *
34 | * @param url
35 | * @param parameters 请求的参数,如果是GET请求,则会将参数拼接到url中,允许为null
36 | * @param httpCallback
37 | * @param 支持返回实体对像,当指定为String.class时,返回的是字符串
38 | */
39 | void get(String url, Map parameters, HttpCallback httpCallback);
40 |
41 | /**
42 | * 发起HTTP POST 同步请求
43 | *
44 | * @param ttType
45 | * @param url
46 | * @param parameters
47 | * @param 支持返回实体对像,当指定为String.class时,返回的是字符串
48 | * @return
49 | */
50 | T post(TType ttType, String url, Map parameters);
51 |
52 | /**
53 | * 发起HTTP POST 同步请求
54 | *
55 | * @param url
56 | * @param parameters
57 | * @return
58 | */
59 | String post(String url, Map parameters);
60 |
61 | /**
62 | * 发起HTTP POST 异步请求
63 | *
64 | * @param url
65 | * @param parameters
66 | * @param httpCallback
67 | * @param 支持返回实体对像,当指定为String.class时,返回的是字符串
68 | */
69 | void post(String url, Map parameters, HttpCallback httpCallback);
70 |
71 |
72 | }
73 |
--------------------------------------------------------------------------------
/httpclient/src/main/java/com/neu/httpclient/HttpRequestFactory.java:
--------------------------------------------------------------------------------
1 | package com.neu.httpclient;
2 |
3 | /**
4 | * Created by siva on 15/12/23.
5 | */
6 | public class HttpRequestFactory {
7 |
8 | private String TAG = HttpRequestFactory.class.getSimpleName();
9 |
10 | /**
11 | * 创建一个HttpRequest实例
12 | *
13 | * @return
14 | */
15 | public static HttpRequest newInstance() {
16 |
17 | return new OkHttpRequestImpl();
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/httpclient/src/main/java/com/neu/httpclient/OkHttpRequestImpl.java:
--------------------------------------------------------------------------------
1 | package com.neu.httpclient;
2 |
3 | import java.util.Map;
4 |
5 | /**
6 | * Created by neu on 16/2/9.
7 | */
8 | public class OkHttpRequestImpl implements HttpRequest{
9 | @Override
10 | public T get(TType ttype, String url, Map parameters) {
11 | return null;
12 | }
13 |
14 | @Override
15 | public String get(String url, Map parameters) {
16 | return null;
17 | }
18 |
19 | @Override
20 | public void get(String url, Map parameters, HttpCallback httpCallback) {
21 |
22 | }
23 |
24 | @Override
25 | public T post(TType ttType, String url, Map parameters) {
26 | return null;
27 | }
28 |
29 | @Override
30 | public String post(String url, Map parameters) {
31 | return null;
32 | }
33 |
34 | @Override
35 | public void post(String url, Map parameters, HttpCallback httpCallback) {
36 |
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/httpclient/src/main/java/com/neu/httpclient/ProgressListener.java:
--------------------------------------------------------------------------------
1 | package com.neu.httpclient;
2 |
3 | /**
4 | * Created by neu on 16/2/09.
5 | */
6 | public interface ProgressListener {
7 |
8 | /**
9 | * 上传或下载的进度反馈
10 | *
11 | * @param bytesCount 已上传或下载的字节数
12 | * @param contentLength 需要上传或下载的总字节数,下载的长度获取不到时可能返回-1
13 | * @param done 是否已经成功完成,注意异常情况下,该值不会返回true
14 | */
15 | void onProgress(long bytesCount, long contentLength, boolean done);
16 | }
17 |
--------------------------------------------------------------------------------
/httpclient/src/main/java/com/neu/httpclient/TType.java:
--------------------------------------------------------------------------------
1 | package com.neu.httpclient;
2 |
3 | import java.lang.reflect.ParameterizedType;
4 | import java.lang.reflect.Type;
5 |
6 | /**
7 | *Created by neu on 16/2/9.
8 | */
9 | public abstract class TType {
10 |
11 | /**
12 | * //由于泛型的擦试原因,无法在子类中获取T.class,因此需要通过反射机制获取
13 | *
14 | * @return
15 | */
16 | public final Type getTType() {
17 | return ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/httpclient/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | HttpClient
3 |
4 |
--------------------------------------------------------------------------------
/httpclient/src/test/java/com/neu/httpclient/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.neu.httpclient;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * To work on unit tests, switch the Test Artifact in the Build Variants view.
9 | */
10 | public class ExampleUnitTest {
11 | @Test
12 | public void addition_isCorrect() throws Exception {
13 | assertEquals(4, 2 + 2);
14 | }
15 | }
--------------------------------------------------------------------------------
/qrcode/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/qrcode/build.gradle:
--------------------------------------------------------------------------------
1 | dependencies{
2 | compile 'com.google.zxing:core:3.2.0'
3 |
4 | }
--------------------------------------------------------------------------------
/qrcode/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/neu/Library/Android/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/qrcode/src/androidTest/java/com/neu/qrcode/ApplicationTest.java:
--------------------------------------------------------------------------------
1 | package com.neu.qrcode;
2 |
3 | import android.app.Application;
4 | import android.test.ApplicationTestCase;
5 |
6 | /**
7 | * Testing Fundamentals
8 | */
9 | public class ApplicationTest extends ApplicationTestCase {
10 | public ApplicationTest() {
11 | super(Application.class);
12 | }
13 | }
--------------------------------------------------------------------------------
/qrcode/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/qrcode/src/main/java/com/neu/qrcode/Qrcode.java:
--------------------------------------------------------------------------------
1 | package com.neu.qrcode;
2 |
3 | import android.content.Intent;
4 |
5 | import com.neu.qrcode.callback.PermissionResultCallback;
6 | import com.neu.qrcode.callback.QrcodeCallback;
7 |
8 | /**
9 | * Created by neu on 16/2/23.
10 | */
11 | public interface Qrcode {
12 | /**
13 | * 开启扫描界面
14 | */
15 | void start();
16 |
17 | /**
18 | * 重写onActivityResult
19 | *
20 | * @param callback 扫描回调
21 | */
22 | void onActivityResult(int requestCode, int resultCode, Intent data, QrcodeCallback callback);
23 |
24 | //android 6.0的动态权限
25 | void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults,PermissionResultCallback callback);
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/qrcode/src/main/java/com/neu/qrcode/QrcodeFactory.java:
--------------------------------------------------------------------------------
1 | package com.neu.qrcode;
2 |
3 | import android.app.Activity;
4 | import android.app.Fragment;
5 |
6 | import com.neu.qrcode.impl.QrcodeImpl;
7 | import com.neu.qrcode.util.Utils;
8 |
9 | /**
10 | * Created by neu on 16/2/23.
11 | * 二维码生产工厂类
12 | */
13 | public class QrcodeFactory {
14 | /**
15 | * 利用activity生产二维码对象
16 | *
17 | * @param activity activity对象
18 | * @return
19 | */
20 | public static Qrcode newQrcode(Activity activity) {
21 | Utils.checkNotNull(activity, "Activity could not null or other object");
22 | return new QrcodeImpl(activity);
23 | }
24 |
25 | /**
26 | * 利用v4.fragement生成二维码对象
27 | *
28 | * @param fragment fragment对象
29 | * @return
30 | */
31 | public static Qrcode newQrcode(Fragment fragment) {
32 | Utils.checkNotNull(fragment, "Fragment could not null or other object");
33 | return new QrcodeImpl(fragment);
34 | }
35 |
36 |
37 | /**
38 | * 利用v4.fragement生成二维码对象
39 | *
40 | * @param fragment fragment对象
41 | * @return
42 | */
43 | public static Qrcode newQrcode(android.support.v4.app.Fragment fragment) {
44 | Utils.checkNotNull(fragment, "Fragment could not null or other object");
45 | return new QrcodeImpl(fragment);
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/qrcode/src/main/java/com/neu/qrcode/callback/PermissionResultCallback.java:
--------------------------------------------------------------------------------
1 | package com.neu.qrcode.callback;
2 |
3 | /**
4 | * Created by neu on 16/2/16.
5 | * 权限结果
6 | */
7 | public interface PermissionResultCallback {
8 | //用户点击否定
9 | void denyPermission();
10 |
11 | }
12 |
--------------------------------------------------------------------------------
/qrcode/src/main/java/com/neu/qrcode/callback/QrcodeCallback.java:
--------------------------------------------------------------------------------
1 | package com.neu.qrcode.callback;
2 |
3 | import android.support.annotation.NonNull;
4 |
5 | import com.neu.qrcode.qrcode.QrcodeInfo;
6 |
7 | /**
8 | * Created by neu on 16/2/23.
9 | */
10 | public interface QrcodeCallback {
11 | /**
12 | * 扫描二维码成功
13 | *
14 | * @param info 二维码信息
15 | */
16 | void onSuccess(@NonNull QrcodeInfo info);
17 |
18 | /**
19 | * 扫描二维码失败
20 | * @param errMsg 错误信息
21 | */
22 | void onFailed(@NonNull String errMsg);
23 | }
24 |
--------------------------------------------------------------------------------
/qrcode/src/main/java/com/neu/qrcode/impl/QrcodeImpl.java:
--------------------------------------------------------------------------------
1 | package com.neu.qrcode.impl;
2 |
3 | import android.Manifest;
4 | import android.app.Activity;
5 | import android.app.Fragment;
6 | import android.content.Intent;
7 | import android.content.pm.PackageManager;
8 | import android.graphics.Bitmap;
9 | import android.graphics.BitmapFactory;
10 | import android.os.Build;
11 | import android.os.Bundle;
12 | import android.support.v4.app.ActivityCompat;
13 |
14 | import com.neu.qrcode.Qrcode;
15 | import com.neu.qrcode.callback.PermissionResultCallback;
16 | import com.neu.qrcode.callback.QrcodeCallback;
17 | import com.neu.qrcode.qrcode.QrcodeInfo;
18 | import com.neu.qrcode.skill.activity.CaptureActivity;
19 | import com.neu.qrcode.skill.constants.Constants;
20 | import com.neu.qrcode.skill.decode.DecodeThread;
21 | import com.neu.qrcode.util.Utils;
22 |
23 | /**
24 | * Created by neu on 16/2/23.
25 | */
26 | public class QrcodeImpl implements Qrcode {
27 | /**
28 | * Id to identify a activity startActivityForResult
29 | */
30 | private static final int REQUEST_CODE = 101;
31 | /**
32 | * Id to identify a CAMERA permission request.
33 | */
34 | private static final int REQUEST_CAMERA = 201;
35 | /**
36 | * Permissions required to read and write contacts. Used by the {@link QrcodeImpl}.
37 | */
38 | private static String[] PERMISSIONS_CAMERA = {Manifest.permission.CAMERA};
39 |
40 |
41 | //持有activity
42 | private Activity mActivity;
43 | //持有fragment
44 | private android.support.v4.app.Fragment mSupportFragment;
45 | //持有fragment
46 | private Fragment mFragment;
47 | //扫描后回调
48 | private QrcodeCallback mCallback;
49 |
50 |
51 | public QrcodeImpl(Activity activity) {
52 | mActivity = activity;
53 | }
54 |
55 | public QrcodeImpl(Fragment fragment) {
56 | mFragment = fragment;
57 | mActivity = mFragment.getActivity();
58 | }
59 |
60 | public QrcodeImpl(android.support.v4.app.Fragment supportFragment) {
61 | mSupportFragment = supportFragment;
62 | mActivity = mSupportFragment.getActivity();
63 | }
64 |
65 | @Override
66 | public void start() {
67 | //检查是否具有该权限
68 | checkPremission();
69 | }
70 |
71 | /**
72 | * 检查是否具有权限
73 | */
74 | private void checkPremission() {
75 | //当Android6.0以下,申明了权限,直接startIntent()
76 | if (ActivityCompat.checkSelfPermission(mActivity, Manifest.permission.CAMERA)
77 | != PackageManager.PERMISSION_GRANTED){
78 | // Contacts permissions have not been granted.
79 | requesQrCodePermissions();
80 |
81 | } else {
82 | // Contact permissions have been granted. Show the contacts fragment.
83 | startQrCode();
84 | }
85 | }
86 |
87 | /**
88 | * 开启扫码
89 | */
90 | private void startQrCode() {
91 | if (mFragment != null) {
92 | Intent intent = new Intent(mActivity, CaptureActivity.class);
93 | mFragment.startActivityForResult(intent, REQUEST_CODE);
94 | } else if (mSupportFragment != null) {
95 | Intent intent = new Intent(mActivity, CaptureActivity.class);
96 | mSupportFragment.startActivityForResult(intent, REQUEST_CODE);
97 | } else {
98 | Intent intent = new Intent(mActivity, CaptureActivity.class);
99 | mActivity.startActivityForResult(intent, REQUEST_CODE);
100 | }
101 | }
102 |
103 | /**
104 | * Android6.0需要权限
105 | */
106 | private void requesQrCodePermissions() {
107 | //判断该权限是否需要
108 | if (mFragment != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
109 | mFragment.requestPermissions(PERMISSIONS_CAMERA, REQUEST_CAMERA);
110 | } else if (mSupportFragment != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
111 | mSupportFragment.requestPermissions(PERMISSIONS_CAMERA, REQUEST_CAMERA);
112 | } else {
113 | //Android6.0以上的手机启动contact,且是activity启动的
114 | //Android6.0以下的手机,具有权限管理,且关闭了app的联系人权限
115 | // TODO: 16/2/17 当Android6.0以下手机调用方必须是在其activity中实现OnRequestPermissionsResultCallback,且调用contact的onRequestPermissionsResult
116 | //不实现OnRequestPermissionsResultCallback的话,无法接收消息,fragmentactivity实现了该接口
117 | //所以当你的activity是fragmentactivity的子类或者appcompatActivity的子类,可以不实现其接口
118 | ActivityCompat.requestPermissions(mActivity, PERMISSIONS_CAMERA, REQUEST_CAMERA);
119 | }
120 | }
121 |
122 | @Override
123 | public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults, PermissionResultCallback callback) {
124 | if (requestCode == REQUEST_CAMERA) {
125 | // We have requested multiple permissions for contacts, so all of them need to be
126 | // checked.
127 | if (Utils.verifyPermissions(grantResults)) {
128 | // All required permissions have been granted, display contacts fragment.
129 | startQrCode();
130 | } else {
131 | callback.denyPermission();
132 | }
133 |
134 | }
135 | }
136 |
137 | @Override
138 | public void onActivityResult(int requestCode, int resultCode, Intent data, QrcodeCallback callback) {
139 | this.mCallback = callback;
140 | if (requestCode == REQUEST_CODE) {
141 | handleActivityResult(resultCode, data, callback);
142 | }
143 | }
144 |
145 | /**
146 | * 处理扫描结果
147 | *
148 | * @param resultCode 结果码
149 | * @param data 数据
150 | * @param callback 回调
151 | */
152 | private void handleActivityResult(int resultCode, Intent data, QrcodeCallback callback) {
153 | switch (resultCode) {
154 | case Activity.RESULT_OK:
155 | handleSuccess(data);
156 | break;
157 | case Activity.RESULT_CANCELED:
158 | sendBackResult(false, "用户已取消", null);
159 | break;
160 | case Constants.PERMISSION_DENY:
161 | sendBackResult(false, "打开摄像头无权限", null);
162 | break;
163 | }
164 | }
165 |
166 | /**
167 | * 返回用户数据
168 | *
169 | * @param isSuccess 是否成功
170 | * @param message 信息
171 | * @param info 二维码信息
172 | */
173 | private void sendBackResult(boolean isSuccess, String message, QrcodeInfo info) {
174 | if (!isSuccess) {
175 | mCallback.onFailed(message);
176 | } else {
177 | mCallback.onSuccess(info);
178 | }
179 | }
180 |
181 | /**
182 | * 成功扫描
183 | *
184 | * @param data 数据
185 | */
186 | private void handleSuccess(Intent data) {
187 | Bundle bundle = data.getExtras();
188 | if (bundle != null) {
189 | String result = bundle.getString("result");
190 | byte[] compressedBitmap = bundle.getByteArray(DecodeThread.BARCODE_BITMAP);
191 | int width = bundle.getInt("width");
192 | int height = bundle.getInt("height");
193 | Bitmap bitmap = getBitmap(compressedBitmap);
194 | sendBackResult(true, null, new QrcodeInfo(result, bitmap, width, height));
195 | } else {
196 | sendBackResult(false, "扫码失败", null);
197 | }
198 | }
199 |
200 | /**
201 | * 将byte数组decode为bitmap
202 | *
203 | * @param compressedBitmap byte数组
204 | * @return bitmap对象
205 | */
206 | private Bitmap getBitmap(byte[] compressedBitmap) {
207 | Bitmap barcode = null;
208 | if (compressedBitmap != null) {
209 | barcode = BitmapFactory.decodeByteArray(compressedBitmap, 0, compressedBitmap.length, null);
210 | // Mutable copy:
211 | barcode = barcode.copy(Bitmap.Config.RGB_565, true);
212 | }
213 | return barcode;
214 | }
215 |
216 |
217 | }
218 |
--------------------------------------------------------------------------------
/qrcode/src/main/java/com/neu/qrcode/qrcode/QrcodeInfo.java:
--------------------------------------------------------------------------------
1 | package com.neu.qrcode.qrcode;
2 |
3 | import android.graphics.Bitmap;
4 |
5 | /**
6 | * Created by neu on 16/2/23.
7 | * 二维码信息类
8 | */
9 | public final class QrcodeInfo {
10 | /**
11 | * 二维码信息
12 | */
13 | private final String result;
14 | /**
15 | * 二维码图像
16 | */
17 | private final Bitmap qrCodeImage;
18 | /**
19 | * 二维码图像宽度
20 | */
21 | private final int width;
22 | /**
23 | * 二维码高度
24 | */
25 | private final int height;
26 |
27 | public QrcodeInfo(String result, Bitmap qiCodeImage, int width, int height) {
28 | this.result = result;
29 | this.qrCodeImage = qiCodeImage;
30 | this.width = width;
31 | this.height = height;
32 | }
33 |
34 | public Bitmap getQrCodeImage() {
35 | return qrCodeImage;
36 | }
37 |
38 | public int getHeight() {
39 | return height;
40 | }
41 |
42 | public int getWidth() {
43 | return width;
44 | }
45 |
46 | public String getResult() {
47 | return result;
48 | }
49 |
50 | @Override
51 | public String toString() {
52 | return result;
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/qrcode/src/main/java/com/neu/qrcode/skill/activity/CaptureActivity.java:
--------------------------------------------------------------------------------
1 | package com.neu.qrcode.skill.activity;
2 |
3 | import android.app.Activity;
4 | import android.app.AlertDialog;
5 | import android.content.DialogInterface;
6 | import android.content.Intent;
7 | import android.graphics.Rect;
8 | import android.os.Bundle;
9 | import android.os.Handler;
10 | import android.util.Log;
11 | import android.view.SurfaceHolder;
12 | import android.view.SurfaceView;
13 | import android.view.ViewStub;
14 | import android.view.Window;
15 | import android.view.WindowManager;
16 | import android.widget.FrameLayout;
17 |
18 | import com.google.zxing.Result;
19 | import com.neu.qrcode.R;
20 | import com.neu.qrcode.skill.camera.CameraManager;
21 | import com.neu.qrcode.skill.constants.Constants;
22 | import com.neu.qrcode.skill.decode.DecodeThread;
23 | import com.neu.qrcode.skill.utils.BeepManager;
24 | import com.neu.qrcode.skill.utils.CaptureActivityHandler;
25 | import com.neu.qrcode.skill.utils.InactivityTimer;
26 | import com.neu.qrcode.skill.view.ViewfinderView;
27 |
28 | import java.io.IOException;
29 |
30 | /**
31 | * 扫描二维码实现类
32 | */
33 | public final class CaptureActivity extends Activity implements SurfaceHolder.Callback {
34 |
35 | private static final String TAG = CaptureActivity.class.getSimpleName();
36 | //摄像头管理类
37 | private CameraManager cameraManager;
38 | //handler
39 | private CaptureActivityHandler handler;
40 | //activity计时类
41 | private InactivityTimer inactivityTimer;
42 | //震动类
43 | private BeepManager beepManager;
44 | //layout中的组件
45 | private SurfaceView scanPreview = null;
46 |
47 | private ViewfinderView mViewfinderView;
48 | //截取正方形
49 | private Rect mCropRect = null;
50 |
51 | private Rect mScanRect = null;
52 | //是否有surface
53 | private boolean isHasSurface = false;
54 | //view延迟加载
55 | private ViewStub mViewStub;
56 | //是否被inflate
57 | private boolean isInflate = false;
58 |
59 | public Handler getHandler() {
60 | return handler;
61 | }
62 |
63 | public CameraManager getCameraManager() {
64 | return cameraManager;
65 | }
66 |
67 | @Override
68 | public void onCreate(Bundle savedInstanceState) {
69 | super.onCreate(savedInstanceState);
70 | //设置屏幕常亮
71 | Window window = getWindow();
72 | window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
73 | setContentView(R.layout.library_activity_capture);
74 |
75 | scanPreview = (SurfaceView) findViewById(R.id.capture_preview);
76 | //在初始化相机的时候截取正方形
77 | mViewStub = (ViewStub) findViewById(R.id.viewStub);
78 | //给activity生命周期计时 当手机不处于充电状态,5分钟关闭该activity
79 | inactivityTimer = new InactivityTimer(this);
80 | //扫码成功后震动
81 | beepManager = new BeepManager(this);
82 | }
83 |
84 | @Override
85 | protected void onResume() {
86 | super.onResume();
87 | //处理相机事务
88 | cameraManager = new CameraManager(getApplication());
89 | //将handler设置为空
90 | handler = null;
91 | //判断是否添加了callback
92 | if (isHasSurface) {
93 | initCamera(scanPreview.getHolder());
94 | } else {
95 |
96 | scanPreview.getHolder()
97 | .addCallback(this);
98 | }
99 | //注册是否充电监听
100 | inactivityTimer.onResume();
101 | }
102 |
103 | @Override
104 | protected void onPause() {
105 | if (handler != null) {
106 | handler.quitSynchronously();
107 | handler = null;
108 | }
109 | inactivityTimer.onPause();
110 | beepManager.close();
111 | cameraManager.closeDriver();
112 | if (!isHasSurface) {
113 | scanPreview.getHolder()
114 | .removeCallback(this);
115 | }
116 | super.onPause();
117 | }
118 |
119 | @Override
120 | protected void onDestroy() {
121 | inactivityTimer.shutdown();
122 | super.onDestroy();
123 | }
124 |
125 | /**
126 | * 初始化相机
127 | *
128 | * @param surfaceHolder surfaceholder
129 | */
130 | private void initCamera(SurfaceHolder surfaceHolder) {
131 | if (surfaceHolder == null) {
132 | throw new IllegalStateException("No SurfaceHolder provided");
133 | }
134 | if (cameraManager.isOpen()) {
135 | Log.w(TAG, "initCamera() while already open -- late SurfaceView callback?");
136 | return;
137 | }
138 | try {
139 | cameraManager.openDriver(surfaceHolder);
140 | // Creating the handler starts the preview, which can also throw a
141 | // RuntimeException.
142 | if (handler == null) {
143 | handler = new CaptureActivityHandler(this, cameraManager, DecodeThread.ALL_MODE);
144 | }
145 |
146 | if (!isInflate) {
147 | FrameLayout layout = (FrameLayout) mViewStub.inflate();
148 | mViewfinderView = (ViewfinderView) layout.findViewById(R.id.viewfinder_view);
149 | initCrop();
150 | mViewfinderView.setGuideFrame(getScanRect());
151 | isInflate = true;
152 | }
153 |
154 | } catch (IOException ioe) {
155 | Log.w(TAG, ioe);
156 | displayFrameworkBugMessageAndExit();
157 | } catch (RuntimeException e) {
158 | // Barcode Scanner has seen crashes in the wild of this variety:
159 | // java.?lang.?RuntimeException: Fail to connect to camera service
160 | Log.w(TAG, "Unexpected error initializing camera", e);
161 | displayFrameworkBugMessageAndExit();
162 | }
163 | }
164 |
165 | /**
166 | * 初始化截取的矩形区域
167 | */
168 | private void initCrop() {
169 | int cameraWidth = cameraManager.getCameraResolution().y;
170 | int cameraHeight = cameraManager.getCameraResolution().x;
171 |
172 | // 扫描框的为正方形,边长为相机最短边长的1/2
173 | int cropLength = Math.min(cameraWidth, cameraHeight) / 2;
174 |
175 | /** 获取布局中扫描框的位置信息 */
176 | int[] location = new int[2];
177 | mViewfinderView.getLocationInWindow(location);
178 |
179 | int cropLeft = (cameraWidth - cropLength) / 2;
180 | int cropTop = (cameraHeight - cropLength) / 3;
181 |
182 | /** 生成最终的截取的矩形 */
183 | mCropRect = new Rect(cropLeft, cropTop, cropLeft + cropLength, cropTop + cropLength);
184 |
185 | /** 获取布局容器的宽高 */
186 | int containerWidth = scanPreview.getWidth();
187 | int containerHeight = scanPreview.getHeight();
188 |
189 | /** 计算屏幕显示最终截取的矩形的左上角顶点x坐标 */
190 | int x = cropLeft * containerWidth / cameraWidth;
191 | /** 计算屏幕显示最终截取的矩形的左上角顶点y坐标 */
192 | int y = cropTop * containerHeight / cameraHeight;
193 |
194 | /** 计算屏幕显示最终截取的矩形的宽度 */
195 | int width = cropLength * containerWidth / cameraWidth;
196 | /** 计算屏幕显示最终截取的矩形的高度 */
197 | int height = cropLength * containerHeight / cameraHeight;
198 |
199 | mScanRect = new Rect(x, y, width + x, height + y);
200 | }
201 |
202 | public Rect getScanRect() {
203 | return mScanRect;
204 | }
205 |
206 | public Rect getCropRect() {
207 | return mCropRect;
208 | }
209 |
210 | private void displayFrameworkBugMessageAndExit() {
211 | // camera error
212 | AlertDialog.Builder builder = new AlertDialog.Builder(this);
213 | builder.setTitle(getString(R.string.app_name));
214 | builder.setMessage("相机打开出错,请稍后重试");
215 | builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
216 |
217 | @Override
218 | public void onClick(DialogInterface dialog, int which) {
219 | setResult(Constants.PERMISSION_DENY);
220 | finish();
221 | }
222 |
223 | });
224 | builder.show();
225 | }
226 |
227 | @Override
228 | public void surfaceCreated(SurfaceHolder holder) {
229 | if (holder == null) {
230 | Log.e(TAG, "*** WARNING *** surfaceCreated() gave us a null surface!");
231 | }
232 | //初始化相机
233 | if (!isHasSurface) {
234 | isHasSurface = true;
235 | initCamera(holder);
236 | }
237 | }
238 |
239 | @Override
240 | public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
241 |
242 | }
243 |
244 | @Override
245 | public void surfaceDestroyed(SurfaceHolder holder) {
246 | isHasSurface = false;
247 | }
248 |
249 | /**
250 | * A valid barcode has been found, so give an indication of success and show
251 | * the results.
252 | *
253 | * @param rawResult The contents of the barcode.
254 | * @param bundle The extras
255 | */
256 | public void handleDecode(Result rawResult, Bundle bundle) {
257 | inactivityTimer.onActivity();
258 | beepManager.playBeepSoundAndVibrate();
259 |
260 | bundle.putInt("width", mCropRect.width());
261 | bundle.putInt("height", mCropRect.height());
262 | bundle.putString("result", rawResult.getText());
263 |
264 | Intent intent = new Intent();
265 | intent.putExtras(bundle);
266 | setResult(RESULT_OK, intent);
267 | finish();
268 | }
269 | }
--------------------------------------------------------------------------------
/qrcode/src/main/java/com/neu/qrcode/skill/camera/AutoFocusManager.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2012 ZXing authors
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.neu.qrcode.skill.camera;
18 |
19 | import android.annotation.SuppressLint;
20 | import android.content.Context;
21 | import android.hardware.Camera;
22 | import android.os.AsyncTask;
23 | import android.os.Build;
24 | import android.util.Log;
25 |
26 | import java.util.ArrayList;
27 | import java.util.Collection;
28 | import java.util.concurrent.RejectedExecutionException;
29 |
30 | public class AutoFocusManager implements Camera.AutoFocusCallback {
31 |
32 | private static final String TAG = AutoFocusManager.class.getSimpleName();
33 |
34 | private static final long AUTO_FOCUS_INTERVAL_MS = 2000L;
35 | private static final Collection FOCUS_MODES_CALLING_AF;
36 |
37 | static {
38 | FOCUS_MODES_CALLING_AF = new ArrayList(2);
39 | FOCUS_MODES_CALLING_AF.add(Camera.Parameters.FOCUS_MODE_AUTO);
40 | FOCUS_MODES_CALLING_AF.add(Camera.Parameters.FOCUS_MODE_MACRO);
41 | }
42 |
43 | private final boolean useAutoFocus;
44 | private final Camera camera;
45 | private boolean stopped;
46 | private boolean focusing;
47 | private AsyncTask, ?, ?> outstandingTask;
48 |
49 | public AutoFocusManager(Context context, Camera camera) {
50 | this.camera = camera;
51 | String currentFocusMode = camera.getParameters()
52 | .getFocusMode();
53 | useAutoFocus = FOCUS_MODES_CALLING_AF.contains(currentFocusMode);
54 | Log.i(TAG, "Current focus mode '" + currentFocusMode + "'; use auto focus? " + useAutoFocus);
55 | start();
56 | }
57 |
58 | public synchronized void start() {
59 | if (useAutoFocus) {
60 | outstandingTask = null;
61 | if (!stopped && !focusing) {
62 | try {
63 | camera.autoFocus(this);
64 | focusing = true;
65 | } catch (RuntimeException re) {
66 | // Have heard RuntimeException reported in Android 4.0.x+;
67 | // continue?
68 | Log.w(TAG, "Unexpected exception while focusing", re);
69 | // Try again later to keep cycle going
70 | autoFocusAgainLater();
71 | }
72 | }
73 | }
74 | }
75 |
76 | @SuppressLint("NewApi")
77 | private synchronized void autoFocusAgainLater() {
78 | if (!stopped && outstandingTask == null) {
79 | AutoFocusTask newTask = new AutoFocusTask();
80 | try {
81 | if (Build.VERSION.SDK_INT >= 11) {
82 | newTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
83 | } else {
84 | newTask.execute();
85 | }
86 | outstandingTask = newTask;
87 | } catch (RejectedExecutionException ree) {
88 | Log.w(TAG, "Could not request auto focus", ree);
89 | }
90 | }
91 | }
92 |
93 | @Override
94 | public synchronized void onAutoFocus(boolean success, Camera theCamera) {
95 | focusing = false;
96 | autoFocusAgainLater();
97 | }
98 |
99 | public synchronized void stop() {
100 | stopped = true;
101 | if (useAutoFocus) {
102 | cancelOutstandingTask();
103 | // Doesn't hurt to call this even if not focusing
104 | try {
105 | camera.cancelAutoFocus();
106 | } catch (RuntimeException re) {
107 | // Have heard RuntimeException reported in Android 4.0.x+;
108 | // continue?
109 | Log.w(TAG, "Unexpected exception while cancelling focusing", re);
110 | }
111 | }
112 | }
113 |
114 | private synchronized void cancelOutstandingTask() {
115 | if (outstandingTask != null) {
116 | if (outstandingTask.getStatus() != AsyncTask.Status.FINISHED) {
117 | outstandingTask.cancel(true);
118 | }
119 | outstandingTask = null;
120 | }
121 | }
122 |
123 | private final class AutoFocusTask extends AsyncTask