PhoneNumber Android Library

repository·legacy·Indexed 42 days ago

https://github.com/xdtianyu/phonenumber

An open-source Android library for retrieving phone number information, including location attribution, spam detection, and harassment identification. It supports offline local databases and online API queries via Baidu, Juhe (360), or custom APIs. Features include custom NumberHandlers for extensibility and a WebNumberHandler for HTML scraping via Jsoup. Version 0.6.11.

Tokens
3.2K
Snippets
7
Records
15
Agent score
52%

What's inside PhoneNumber

  1. Control query priority and API types

    legacy

    The default query order is: Local Special Numbers $\rightarrow$ Local Common Numbers $\rightarrow$ Local Marked Numbers $\rightarrow$ Local Offline Location $\rightarrow$ Google Offline Location $\rightarrow$ Online Custom API $\rightarrow$ Online Baidu API $\rightarrow$ Online Juhe (360) API.

    You can control which online interface is prioritized by setting the api_type key in SharedPreferences. The value should correspond to the getApiId() return value of the specific module.

  2. Configure API Keys in AndroidManifest

    legacy

    To enable online querying via Baidu or Juhe (360) APIs, you must add the corresponding API keys as meta-data in your AndroidManifest.xml.

    <meta-data
        android:name="org.xdty.phone.number.API_KEY"
        android:value="API_KEY"/>
    <meta-data
        android:name="org.xdty.phone.JUHE_API_KEY"
        android:value="JUHE_API_KEY"/>
  3. Disable online querying

    legacy

    If you want to prevent the library from making network requests, you can disable online querying in two ways:

    1. Globally: Set the only_offline_key key in SharedPreferences.
    2. Temporarily: Use the PhoneNumber constructor that accepts a boolean flag: PhoneNumber(context, true, callback).
  4. Install PhoneNumber via Gradle or Maven

    legacy

    You can integrate the PhoneNumber library into your Android project using Gradle or Maven. Note that the version specified in the examples is 0.6.11.

    ### Gradle
    ```groovy
    dependencies {
        compile 'org.xdty.phone.number:phone-number:0.6.11'
    }

    Maven

    <dependency>
      <groupId>org.xdty.phone.number</groupId>
      <artifactId>phone-number</artifactId>
      <version>0.6.11</version>
      <type>aar</type>
    </dependency>
  5. Understand the JuHeNumber data model

    legacy

    The JuHeNumber class implements the INumber interface and serves as the data model for responses received from the Juhe (聚合数据) API. It maps the raw JSON/API response fields into a standardized format used by the library.

    Key behaviors:

    • Validation: A JuHeNumber instance is considered valid via isValid() if the error_code is 0, the result object is not null, and a name is present.
    • Type Mapping: The getType() method determines if a number is Type.NORMAL or Type.REPORT based on the iszhapian field (where 0 indicates NORMAL).
    • Data Cleaning: The getProvince() and getCity() methods automatically clean the data by converting the string "暂无机构信息" (No institution information) into an empty string.
    • Geo-location: hasGeo() returns true if either the province or city is not empty.
    • API Identification: getApiId() returns INumber.API_ID_JH to identify this provider.
  6. Fetch phone number information with PhoneNumber

    legacy

    To retrieve geolocation and other information for a phone number, instantiate PhoneNumber with a context and a PhoneNumber.Callback. Use the .fetch() method to initiate the request.

    Inside the onResponse(INumber number) callback, you can access information from the INumber object, such as number.getName().

    new PhoneNumber(this, new PhoneNumber.Callback() {
        @Override
        public void onResponse(INumber number) {
            // Do your jobs here
            textView.setText(number.getName());
        }
    
        @Override
        public void onResponseFailed(INumber number) {
        }
    }).fetch("10086", "10000", "10001", "OTHER_PHONE_NUMBER");
  7. Extend PhoneNumber with custom NumberHandlers

    legacy
    You can implement custom number processing by implementing the INumber and NumberHandler interfaces. To use your custom handler, call addNumberHandler(new YourCustomNumberHandler()) before calling .fetch().
  8. Use the PhoneNumber API to fetch number information

    legacy

    Initialize PhoneNumber with a Callback to handle results. The library distinguishes between offline and online results:

    • onResponseOffline(INumber number): Triggered when information is retrieved from local offline databases.
    • onResponse(INumber number): Triggered when information is retrieved via online network queries.
    • onResponseFailed(INumber number): Triggered when the query fails.

    Use the .fetch(...) method to query specific numbers. You can pass multiple phone numbers as arguments.

    new PhoneNumber(this, new PhoneNumber.Callback() {
        @Override
        public void onResponseOffline(INumber number) {
            // Handle offline result
        }
        
        @Override
        public void onResponse(INumber number) {
            // Handle online result
            textView.setText(number.getName());
        }
    
        @Override
        public void onResponseFailed(INumber number) {
            // Handle failure
        }
    }).fetch("10086", "10000", "10001", "OTHER_PHONE_NUMBER");
  9. Configure WebNumberHandler via WebConfig

    legacy

    To use WebNumberHandler, you must provide a WebConfig instance. The handler relies on this configuration to perform web scraping via Jsoup. The following configuration keys are used by the handler:

    • url: The base URL used for requests (e.g., https://example.com/search/).
    • ua: The User-Agent string for the HTTP request.
    • index: An integer used to calculate the API ID via INumber.API_ID_WEB + index.
    • root: CSS selector for the main content container.
    • number: CSS selector to extract the phone number.
    • mark: CSS selector to extract the mark/name.
    • count: CSS selector to extract the numeric count.
    • name: CSS selector to extract the name.
    • address: CSS selector to extract the province/address.

    Note: If multiple selectors (like mark and name) are provided, the last one successfully matched will determine the WebNumber.setName() value.

  10. JuHeNumber API implementation details

    legacy

    The following methods are part of the INumber interface implementation for JuHeNumber:

    MethodDescription
    getName()Returns the carrier name from result.hy.name. If hy is null, it falls back to result.rpt_type.
    getProvince()Returns the province string (cleaned of "暂无机构信息").
    getCity()Returns the city string (cleaned of "暂无机构信息").
    getType()Returns Type.NORMAL if iszhapian == 0, otherwise Type.REPORT.
    getNumber()Returns the phone number string (result.phone).
    getProvider()Returns the service provider (result.sp).
    getCount()Returns the report count (result.rpt_cnt).
    isValid()Returns true if error_code == 0 and essential data is present.
    isOnline()Always returns true.
    hasGeo()Returns true if province or city is non-empty.
    getApiId()Returns INumber.API_ID_JH.
    patch(INumber i)Updates the internal result object's province, city, and sp fields using data from the provided INumber instance.
  11. Use WebNumberHandler to scrape phone number data

    legacy

    The WebNumberHandler is a NumberHandler implementation used to fetch phone number information from a web source by scraping HTML content. It requires a WebConfig object to define how to connect to the URL and which CSS selectors to use for extracting data.

    When find(n: String) is called, the handler performs the following steps:

    1. Connects to ${WebConfig.url}${n} using the configured User-Agent.
    2. Uses CSS selectors defined in WebConfig to extract:
      • number: The phone number text.
      • mark: The name/mark of the number.
      • count: A numeric count (cleaned of non-digit characters).
      • name: The name associated with the number.
      • address: The province/address information.
    3. Returns a WebNumber object populated with the extracted data.