#TargetAPI
Explore tagged Tumblr posts
iwebdatascrape · 1 year ago
Text
Target product data scraper | Target scraping tool
Leverage the benefit of our Target product data scraping services to efficiently scrape Target product data, encompassing essential details such as product titles, pricing information, and more.
Know More: https://www.iwebdatascraping.com/scrape-target-product-data.php
0 notes
iwebscrapingblogs · 4 years ago
Text
How To Collect Data From The Target API?
Tumblr media
With nearly 2000 stores, Target is the top most popular retailers around the globe. Their website has its whole catalog, including information on the product, local inventory, customer comments, and more. As a result, the Target API provides a variety of information which can be gathered and evaluated. The easiest approach to gain information is by web scraping, which means the automated extraction of data from a web site. You can then monitor the data through analytic software after you have it. Your company can use this data to come up with price policies, product growth, and other ideas.
Target API
An API or Application Programming Interface allows two programs to communicate with one another. For instance, Target, has real-time inventory and delivery options at local stores. To accomplish the task, the Target API should exchange data with the inventory interface used by Target. Customer ratings and recent offers are also available on the website.
Methods to Execute the Target API
As of the Target's characteristics, there is a wealth of information ready to be acquired and processed. Web harvesting is the most effective method for gathering this information. A web extracting tool, allows you to scrape data from online sites continuously so that they may be examined. The data can be readily saved and stored in an excel sheet once it has been extracted.
While manually extracting data is possible, it takes longer time and requires more work than utilizing an extracting program. Team can use the additional time to undertake comprehensive statistical analysis, which will aid your organization to make excellent decisions, based on data in future.
Advantages of Extracting Target Data
Extracting Target data has numerous advantages. Here are a few examples of how you can utilize Target API information to benefit your company.
When you browse an item on Target's website, you'll see the pricing as well as details on the discounted price similar to the older. This will allow you to easily check how much money you're spending. Scraping Target's price data allows you to compare your products with the market price, allowing you to determine the ideal price. Finding the effective price while developing your item is critical. Scraping Target's price data and combining it with information from other big retailers will provide you the most accurate view of the market's price range.
Target product Data
Target product data can be used for product growth and corporate research in addition to pricing information. The Target website lists all of a product's attributes, including its size, color variations, and material. It's crucial to explain how competing items differ while price comparison. For example, a clothing business that employs high-end fabrics would be able to pay more than a brand that uses low-cost materials. Product information is crucial because it allows price data to be contextualized. The cause for a price in the market could be found in the product specifications.
The cause for an outlier price in the market could be found in the product specifications. Scraping a product line provides insight into which product characteristics and features are most appreciated by consumers, which is useful for companies creating innovative brands or upgrading current ones.
Web Scraping Services the reviews with the product details might help you spot trends, such as which coat fabrics people would prefer or which appliance functions, they utilize the most. Because you can avoid your competitors' mistakes while being inspired by what works in their favor, having this data helps you make better product decisions during the development process.
Target Inventory API Data
The target inventory tool will allow to view which Target locations have items in store. If you want, you can opt for delivery or pick up. You can use this information for your benefit. You can find out which goods are in high demand by scraping inventory data and promoting your products as a result.
If company and Target both have a competing product and their edition is out of the sale, for example, you can start strongly promoting yours in the hopes of converting individuals that could not Target enough into prospective investors.
Analyzing market patterns by scraping Target's shares is a wonderful approach to do it. One chooses which products to stock and how to extend your product line in the future. Scraping inventory information to determine market dynamics is a simple approach to remain on top of consumer demand.
Web scraping and analysis with the Target API
Scraping the Target API and incorporating it into your data routine is an excellent method to gain access to price analysis, inventory analysis, and product data. Only scraping Target's website, on the other hand, limits your data analysis. Here are some ideas for combining your Target data with data from other sources.
Online Retailers
In the United States, Target is one of the largest retailer shops. The same information can be found on the websites of Walmart, Wayfair, Amazon, Home Depot, and other large merchants. When you compare Target to other stores, you can discover whether the data patterns they have are exclusive to them or are common across the market. Having the most up-to-date information allows you to make better judgments in the future, and these ideas come from a variety of sources.
Social Media
Consumer sentiment data can also be found on social media platforms like Twitter and Instagram. While Amazon and other retail sites have comment sections, people on the internet discuss things they dislike and love. You can discover out how other accounts, including brands, a user follows by scraping their profiles. Trending topics can also be seen on social media sites such as Twitter.
Scraping a popular topic relating to your business or product can provide you with a wealth of information at once, much like a review section. You can gather the most precise statistics on how people feel about a product by combining social media with reviews on a retailer's website.
Scraping social media is an excellent method for designing an advertisement poster or gathering consumer feedback on certain social subjects. Scraping a popular subject associated with climate change in your sector can help you acquire useful information as to how your business or consumers think about sustainability in their goods if your product is eco-friendly.
This allows you to tailor your marketing campaign to their climate change without having to perform formal research such as focus groups.
iWeb Scraping
Data accuracy is improved by combining data obtained from the Target API as well as a variety of additional sources. However, combining all of this information into a single, comprehensive study might be difficult. This is a lot easier with iWeb Scraping API. Our API makes it simple to combine data sources by allowing you to input data from multiple sources directly into your preferred analysis program.
Contact iWeb Scraping for any queries or ask for a free quote!
https://www.iwebscraping.com/how-to-collect-data-from-the-target-api.php
1 note · View note
joeyrob1 · 5 years ago
Text
Tutorial How To Create Custom Android Code Templates
Mobile App Development: Tutorial How To Create Custom Android Code Templates
(No Ratings Yet) Loading...
Introduction
This tutorial will show you how to create custom Android code templates of your own. Most Android developers would have used Android code templates at least once to start projects. But have you tried creating your own Android code templates? In this tutorial, we will show you how to create a template that can be used to generate a Android project from Android Studio IDE that contains Google Analytics configuration. (Google Analytics v4 for Android)
Tung Dao Xuan, [email protected], is the author of this article and he contributes to RobustTechHouse Blog
  Video & Source Code
Source Code
You can download the source code at GoogleAnalyticApplication-2015-05-31.
Step by Step Video
[vc_video title=”Video Tutorial How To Create Custom Android Code Template” link=”https://www.youtube.com/watch?v=rhsBrBcgMkQ”]
  High Level View of Code Generation Process
If you are not familiar with the code generation process, please also check out the documentation of the full process here.
  Steps To Create Custom Android Code Templates For Google Analytics
To build your own template, please ensure that:
You understand the code generation process described above at a high level.
You have some knowledge about FreeMarker
You have some knowledge about Android IDE Template Format and you can see the documentation here.
    Step 1: Create Google Analytic Application Folder
This is for the template directory you need. On Windows, place it in: path-to-your-installation-android-studio-folder\plugins\android\lib\templates\activities. Please change your path appropriately on Linux, Mac OS etc.
Then, create the root folder and other files inside your GoogleAnalyticApplication folder.
  Step 2: Create template.xml file
Each template directory must contain a template.xml file. This XML file contains the metadata about the template, including the name, description, category and user-visible parameters that the IDE will present as options to the user. The XML file also indicates the name of the recipe XML file which gets processed by FreeMarker, and the global variables XML file  if there are global variables besides the template parameter values that should be visible to all FreeMarker-processed files (.ftl files).
<?xml version="1.0"?> <template format="3" revision="4" name="Google Analytics Application" minApi="7" minBuildApi="14" description="Creates a new application that has already Google Analytics configuration."> <category value="Activity" /> <formfactor value="Mobile" /> <parameter id="activityClass" name="Activity Name" type="string" constraints="class|unique|nonempty" suggest="${layoutToActivity(layoutName)}" default="MainActivity" help="The name of the activity class to create" /> <parameter id="layoutName" name="Layout Name" type="string" constraints="layout|unique|nonempty" suggest="${activityToLayout(activityClass)}" default="activity_main" help="The name of the layout to create for the activity" /> <parameter id="classApplication" name="Class extends Application" type="string" constraints="nonempty|class" help="The name of class that extends from Application" /> <parameter constraints="nonempty|string" id="googleAnalyticID" name="Google Analytic ID" type="string" help="Id of Google Analytic" /> <parameter id="dispatchPeriod" name="Dispatch Period" help="Frequency of automatic dispatch in seconds. Defaults to 30 minutes (1800 seconds)." type="string" default="1800"/> <parameter id="autoActivityTracking" name="Auto Activity Tracking" help="If true, views (Activities) will be tracked automatically. false by default." type="boolean" default="false"/> <!-- 128x128 thumbnails relative to template.xml --> <thumbs> <!-- default thumbnail is required --> <thumb>template_google_analytics.png</thumb> </thumbs> <globals file="globals.xml.ftl" /> <execute file="recipe.xml.ftl" /> </template>
There are parameters: activityClass, layoutName, classApplication, googleAnalyticID, dispatchPeriod, autoActivityTracking which will be shown in popups when you create a project.
   Step 3: Create globals.xml.ftl file
The optional globals XML file contains global variable definitions, for use in all FreeMarker processing jobs for this template.
<?xml version="1.0"?> <globals> <global id="manifestOut" value="${manifestDir}" /> <global id="srcOut" value="${srcDir}/${slashedPackageName(packageName)}" /> <global id="resOut" value="${resDir}" /> </globals>
  Step 4: Create folder & files inside root folder
The root folder contains template source code & template resource to generate.
4a. Create AndroidManifest.xml.ftl
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="${packageName}"> <application android:name="${packageName}.${classApplication}" android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme"> <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> <meta-data android:name="com.google.android.gms.analytics.globalConfigResource" android:resource="@xml/analytics_global_config" /> <activity android:name=".activities.MainActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
  There are parameters: packageName & classApplication that are declared in template.xml file above.
  4b. Create Application.java.ftl
package ${packageName}; import android.app.Application; import com.google.android.gms.analytics.GoogleAnalytics; import com.google.android.gms.analytics.Tracker; /** * Created by TungDX on 5/29/2015. */ public class ${classApplication} extends Application { private static GoogleAnalytics analytics; private static Tracker tracker; @Override public void onCreate() { analytics = GoogleAnalytics.getInstance(this); tracker = analytics.newTracker("${googleAnalyticID}"); } public static GoogleAnalytics getGoogleAnalytics() { return analytics; } public static Tracker getTracker() { return tracker; } }
There are parameters: packageName & googleAnalyticID which are parameters declared in template.xml file above.
  4c. Create MainActivity.java.ftl
package ${packageName}.activities; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import ${packageName}.${classApplication}; import ${packageName}.R; public class MainActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override protected void onStart() { super.onStart(); ${classApplication}.getGoogleAnalytics().reportActivityStart(this); } @Override protected void onStop() { super.onStop(); ${classApplication}.getGoogleAnalytics().reportActivityStop(this); } }
There are parameters: packageName & classApplication which are parameters declared in template.xml file above.
  4d. Create activity_main.xml.ftl
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin"> <TextView android:text="@string/ready" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RelativeLayout>
  4e. Create strings.xml.ftl
<resources> <#if !isNewProject> <string name="title_${activityToLayout(activityClass)}">${escapeXmlString(activityTitle)}</string> </#if> <string name="ready">Google Analytic is ready!</string> </resources>
  4f. Create dimens.xml
<resources> <!-- Default screen margins, per the Android Design guidelines. --> <dimen name="activity_horizontal_margin">16dp</dimen> <dimen name="activity_vertical_margin">16dp</dimen> </resources>
  4g. Create recipe.xml.ftl file
The recipe XML file contains the individual instructions that should be executed when generating code from this template. For example, you can copy certain files or directories (the copy instruction), optionally run the source files through FreeMarker (the instantiate instruction), and ask the IDE to open a file after the code has been generated (the open instruction).
  <?xml version="1.0"?> <recipe> <dependency mavenUrl="com.android.support:support-v4:${targetApi}.+" /> <dependency mavenUrl="com.android.support:appcompat-v7:${targetApi}.+"/> <dependency mavenUrl="com.google.android.gms:play-services:6+" /> <instantiate from="AndroidManifest.xml.ftl" to="${escapeXmlAttribute(manifestOut)}/AndroidManifest.xml" /> <instantiate from="src/app_package/Application.java.ftl" to="${escapeXmlAttribute(srcOut)}/${classApplication}.java"/> <instantiate from="src/app_package/activities/MainActivity.java.ftl" to="${escapeXmlAttribute(srcOut)}/activities/${activityClass}.java"/> <instantiate from="res/xml/analytics_global_config.xml.ftl" to="${escapeXmlAttribute(resOut)}/xml/analytics_global_config.xml"/> <instantiate from="res/layout/activity_main.xml.ftl" to="${escapeXmlAttribute(resOut)}/layout/${layoutName}.xml"/> <copy from="res/values/dimens.xml" to="${escapeXmlAttribute(resOut)}/values/dimens.xml"/> <merge from="res/values/strings.xml.ftl" to="${escapeXmlAttribute(resOut)}/values/strings.xml" /> <open file="${escapeXmlAttribute(srcOut)}/activities/${activityClass}.java" /> <open file="${escapeXmlAttribute(resOut)}/layout/${layoutName}.xml" /> </recipe>
    4h. Check Dependencies
   4i. Check AndroidManifest.xml.ftl
<instantiate from="AndroidManifest.xml.ftl" to="${escapeXmlAttribute(manifestOut)}/AndroidManifest.xml" />
  4j. Check Application.java.ftl
<instantiate from="src/app_package/Application.java.ftl" to="${escapeXmlAttribute(srcOut)}/${classApplication}.java"/>https://robusttechhouse.com/wp-admin/post.php?post=6937&action=edit&message=10#
      4k. Check MainActivity.java.ftl
<instantiate from="src/app_package/activities/MainActivity.java.ftl" to="${escapeXmlAttribute(srcOut)}/activities/${activityClass}.java"/>
  4l. Check analytics_global_config.xml.ftl
<instantiate from="res/xml/analytics_global_config.xml.ftl" to="${escapeXmlAttribute(resOut)}/xml/analytics_global_config.xml"/>
  4m. Generate files: activity_main.xml, dimens.xml, strings.xml from template to project.
<instantiate from="res/layout/activity_main.xml.ftl" to="${escapeXmlAttribute(resOut)}/layout/${layoutName}.xml"/> <copy from="res/values/dimens.xml" to="${escapeXmlAttribute(resOut)}/values/dimens.xml"/> <merge from="res/values/strings.xml.ftl" to="${escapeXmlAttribute(resOut)}/values/strings.xml" />
  4n. Open files after the project is generated.
<open file="${escapeXmlAttribute(srcOut)}/activities/${activityClass}.java" /> <open file="${escapeXmlAttribute(resOut)}/layout/${layoutName}.xml" />
  Try Generating A Project For Your Own Template
If your Android Studio IDE is running, please restart it to see your own template as shown in following image.
If you encounter this error when you are generating a project from the template:
AssertionError: Wrong line separators: ‘…plication;\r\n\r\nimport…’ at offset 29:
Please check your line separators in all your files in the template. Please ensure that you use the correct line separators for your computer’s OS. Eg Window uses LF, Linux or MAC OS use CRLF.
  Conclusion
And that’s it. It isn’t that difficult to create custom Android code templates and you will benefit from it in the long-term because you would adhere to the DRY (Don’t Repeat Yourself) principle and save yourself some time. Have fun coding!
  RobustTechHouse is a leading tech company focusing on mobile app development, ECommerce, Mobile-Commerce and Financial Technology (FinTech) in Singapore. If you are interested to engage RobustTechHouse on your projects in Singapore, you can contact us here.
    References
Video showing the steps
Source code can be downloaded at GoogleAnalyticApplication-2015-05-31
Custom Android Code Templates Slides
GoogleSource Templates
ADT Template Format Documentation by Roman Nurik
      Tutorial How To Create Custom Android Code Templates was originally published on RobustTechHouse - Mobile App Development Singapore
0 notes
besttoptech-blog · 7 years ago
Text
AppChecker - Checklist APIs of Apps 1.9-b66 Mod Apk Rating Latast
AppChecker – Checklist APIs of Apps 1.9-b66 Mod Apk Rating Latast
Tumblr media
This app shows the TargetAPI of all of your installed apps. This permits you to absorb a study, which of your apps already toughen the most up-to-date parts of your Android Arrangement.
Whereas you are working Android 6 Marshmallow, this app helps you to absorb a study which of your apps already toughen the unusual granular permission settings.
Guidelines from Google: As unusual versions of…
View On WordPress
0 notes
jeeteshsurana · 6 years ago
Link
Getting Current Location via GPS and service call every 30 min.
__________________________________________________________
Gradle 
__________________________________________________________
dependencies {
implementation 'com.google.android.gms:play-services-location:16.0.0'
}
__________________________________________________________
GPSTracker.java
__________________________________________________________
package com.android.coroutines;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class GPSTracker extends Service implements LocationListener {
    // Get Class Name
    private static String TAG = GPSTracker.class.getName();
    private final Context mContext;
    // flag for GPS Status
    boolean isGPSEnabled = false;
    // flag for network status
    boolean isNetworkEnabled = false;
    // flag for GPS Tracking is enabled
    boolean isGPSTrackingEnabled = false;
    Location location;
    double latitude;
    double longitude;
    // How many Geocoder should return our GPSTracker
    int geocoderMaxResults = 1;
    // The minimum distance to change updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
    // Declaring a Location Manager
    protected LocationManager locationManager;
    // Store LocationManager.GPS_PROVIDER or LocationManager.NETWORK_PROVIDER information
    private String provider_info;
    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }
    /**
     * Try to get my current location by GPS or Network Provider
     */
    @SuppressLint("MissingPermission")
    public void getLocation() {
        try {
            locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
            //getting GPS status
            isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            //getting network status
            isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
            // Try to get location if you GPS Service is enabled
            if (isGPSEnabled) {
                this.isGPSTrackingEnabled = true;
                Log.d(TAG, "Application use GPS Service");
                /*
                 * This provider determines location using
                 * satellites. Depending on conditions, this provider may take a while to return
                 * a location fix.
                 */
                provider_info = LocationManager.GPS_PROVIDER;
            } else if (isNetworkEnabled) { // Try to get location if you Network Service is enabled
                this.isGPSTrackingEnabled = true;
                Log.d(TAG, "Application use Network State to get GPS coordinates");
                /*
                 * This provider determines location based on
                 * availability of cell tower and WiFi access points. Results are retrieved
                 * by means of a network lookup.
                 */
                provider_info = LocationManager.NETWORK_PROVIDER;
            }
            // Application can use GPS or Network Provider
            if (!provider_info.isEmpty()) {
                locationManager.requestLocationUpdates(
                        provider_info,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES,
                        this
                );
                if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(provider_info);
                    updateGPSCoordinates();
                }
            }
        }
        catch (Exception e)
        {
            //e.printStackTrace();
            Log.e(TAG, "Impossible to connect to LocationManager", e);
        }
    }
    /**
     * Update GPSTracker latitude and longitude
     */
    public void updateGPSCoordinates() {
        if (location != null) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
        }
    }
    /**
     * GPSTracker latitude getter and setter
     * @return latitude
     */
    public double getLatitude() {
        if (location != null) {
            latitude = location.getLatitude();
        }
        return latitude;
    }
    /**
     * GPSTracker longitude getter and setter
     * @return
     */
    public double getLongitude() {
        if (location != null) {
            longitude = location.getLongitude();
        }
        return longitude;
    }
    /**
     * GPSTracker isGPSTrackingEnabled getter.
     * Check GPS/wifi is enabled
     */
    public boolean getIsGPSTrackingEnabled() {
        return this.isGPSTrackingEnabled;
    }
    /**
     * Stop using GPS listener
     * Calling this method will stop using GPS in your app
     */
    public void stopUsingGPS() {
        if (locationManager != null) {
            locationManager.removeUpdates(GPSTracker.this);
        }
    }
    /**
     * Function to show settings alert dialog
     */
    public void showSettingsAlert() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
        //Setting Dialog Title
        alertDialog.setTitle("Title");
        //Setting Dialog Message
        alertDialog.setMessage("Dialog");
        //On Pressing Setting button
        alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });
        //On pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                dialog.cancel();
            }
        });
        alertDialog.show();
    }
    /**
     * Get list of address by latitude and longitude
     * @return null or List<Address>
     */
    public List<Address> getGeocoderAddress(Context context) {
        if (location != null) {
            Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
            try {
                /**
                 * Geocoder.getFromLocation - Returns an array of Addresses
                 * that are known to describe the area immediately surrounding the given latitude and longitude.
                 */
                List<Address> addresses = geocoder.getFromLocation(latitude, longitude, this.geocoderMaxResults);
                return addresses;
            } catch (IOException e) {
                //e.printStackTrace();
                Log.e(TAG, "Impossible to connect to Geocoder", e);
            }
        }
        return null;
    }
    /**
     * Try to get AddressLine
     * @return null or addressLine
     */
    public String getAddressLine(Context context) {
        List<Address> addresses = getGeocoderAddress(context);
        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String addressLine = address.getAddressLine(0);
            return addressLine;
        } else {
            return null;
        }
    }
    /**
     * Try to get Locality
     * @return null or locality
     */
    public String getLocality(Context context) {
        List<Address> addresses = getGeocoderAddress(context);
        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String locality = address.getLocality();
            return locality;
        }
        else {
            return null;
        }
    }
    /**
     * Try to get Postal Code
     * @return null or postalCode
     */
    public String getPostalCode(Context context) {
        List<Address> addresses = getGeocoderAddress(context);
        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String postalCode = address.getPostalCode();
            return postalCode;
        } else {
            return null;
        }
    }
    /**
     * Try to get CountryName
     * @return null or postalCode
     */
    public String getCountryName(Context context) {
        List<Address> addresses = getGeocoderAddress(context);
        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String countryName = address.getCountryName();
            return countryName;
        } else {
            return null;
        }
    }
    @Override
    public void onLocationChanged(Location location) {
    }
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
    @Override
    public void onProviderEnabled(String provider) {
    }
    @Override
    public void onProviderDisabled(String provider) {
    }
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
__________________________________________________________
GPSServiceIntent.kt
__________________________________________________________
package com.android.coroutines.util
import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.app.AlarmManager
import android.app.IntentService
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.net.Uri
import android.os.*
import android.util.Log
import androidx.annotation.NonNull
import androidx.annotation.RequiresApi
import com.android.coroutines.GPSTracker
import com.android.coroutines.dashboard.Constant
import com.google.android.gms.location.FusedLocationProviderClient
import okhttp3.MultipartBody
import okhttp3.RequestBody
import com.justcodenow.musicplayerdemo.util.helper.FileUtils
import okhttp3.MediaType
import java.util.*
@Suppress("UNREACHABLE_CODE", "NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS")
class GPSServiceIntent : IntentService("GPSServiceIntent") {
    private var mLocationManager: LocationManager? = null
    var LOCATION_REFRESH_TIME = 0L
    var LOCATION_REFRESH_DISTANCE = 0F
    var mLat = 0.0
    var mLng = 0.0
    var wakeLock: PowerManager.WakeLock? = null
    private var fusedLocationClient: FusedLocationProviderClient? = null
    init {
        setIntentRedelivery(true) //if you want this process started again then you should pass true other wise pass false
    }
    override fun onHandleIntent(intent: Intent?) {
        val mPendingIntent = PendingIntent.getActivity(applicationContext, 0, intent, 0)
    }
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        return START_STICKY
    }
    override fun onCreate() {
        super.onCreate()
        handler.post(periodicUpdate)
    }
    //init the values and api call
    @SuppressLint("MissingPermission")
    private fun init() {
        val gpsTracker: GPSTracker = GPSTracker(applicationContext!!)
        if (gpsTracker.isGPSTrackingEnabled) {
            Log.d(Constant.Tag,"lat-->${gpsTracker.latitude}")
            Log.d(Constant.Tag,"lng-->${gpsTracker.longitude}")
        }
    }
    override fun onDestroy() {
        super.onDestroy()
        Log.d(Constant.Tag, "-->Destroy Service")
        wakeLock?.release()
        Log.d(Constant.Tag, "-->wakeLock Release")
    }
    var handler = Handler()
    private val periodicUpdate = object : Runnable {
        @TargetApi(Build.VERSION_CODES.KITKAT)
        override fun run() {
            handler.postDelayed(this, 1000) // schedule next wake up every second
            val notificationIntent = Intent(this@GPSServiceIntent, GPSServiceIntent::class.java)
            val pendingIntent =
                PendingIntent.getActivity(this@GPSServiceIntent, 0, notificationIntent, 0)
            val keepAwake = getSystemService(Context.ALARM_SERVICE) as AlarmManager
            keepAwake.setExact(
                AlarmManager.ELAPSED_REALTIME_WAKEUP,
                SystemClock.elapsedRealtime() + 1000,
                pendingIntent
            )
            val current = System.currentTimeMillis()
            if ((current - current % 1000) % (1000 * 1800) == 0L) { // record on every tenth seconds (0s, 10s, 20s, 30s...)
                init()
            }
        }
    }
    @RequiresApi(Build.VERSION_CODES.KITKAT)
    private fun prepareFilePart(partName: String, fileUri: Uri): MultipartBody.Part {
        // http://bit.ly/1mM9Ggw
        // use the FileUtils to get the actual file by uri
        val file = FileUtils.getFile(this, fileUri)
        // create RequestBody instance from file
        val requestFile = RequestBody.create(
            MediaType.parse(Objects.requireNonNull(contentResolver.getType(fileUri))), file
        )
        // MultipartBody.Part is used to send also the actual file name
        return MultipartBody.Part.createFormData(partName, file!!.name, requestFile)
    }
}
__________________________________________________________
DashboardFragment.kt [run the service]
__________________________________________________________
if (!mBaseActivity!!.isServiceRunning(GPSServiceIntent::class.java)) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        context?.startForegroundService(Intent(context, GPSServiceIntent::class.java))
    } else {
        context?.startService(Intent(context, GPSServiceIntent::class.java))
    }
} else {
    Log.d(Constant.Tag, "service are already running ")
}
__________________________________________________________
BaseActivity.kt [copy paste the code in BaseActivity.kt]
__________________________________________________________
fun isServiceRunning(serviceClass: Class<*>): Boolean {
    val manager = this.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager?
    for (service in manager!!.getRunningServices(Integer.MAX_VALUE)) {
        if (serviceClass.name == service.service.className) {
            return true
        }
    }
    return false
}
__________________________________________________________
0 notes
momijinn · 8 years ago
Text
Genuino 101とAndroidをBLE接続する
インテル様のCPUが搭載しているGenuino 101を遊びで使っています
このマイコンはオンボードでBLEや6軸センサーが内蔵しています
昨年ぐらいにこのマイコンを使ってBLE通信を試みたのですが、知識不足だったこともあり通信ができませんでした・・・
  しかし、もう一度挑戦してみた所無事にBLE通信ができたので書き留めておきます
  Genuino 101
  Genuino 101側
はじめにGenuino 101のプログラムを色々といじります
基本はサンプルプログラムであるCurlBLE->LEDを参考にしています
いじった内容は受け取る文字で、Genuino 101はバイト型でデータを受け取るらしいです
Android側でバイト型に変換して送信しようとしてもうまく行かなかったので、Genuino 101のほうで無理やり合わせることにしました
下記のプログラムをGenuino 101へ書き込んでください
/* * Copyright (c) 2016 Intel Corporation. All rights reserved. * See the bottom of this file for the license terms. */ #include <CurieBLE.h> BLEPeripheral blePeripheral; // BLE Peripheral Device (the board you're programming) BLEService ledService("19B10000-E8F2-537E-4F6C-D104768A1214"); // BLE LED Service // BLE LED Switch Characteristic - custom 128-bit UUID, read and writable by central BLEUnsignedCharCharacteristic switchCharacteristic("19B10001-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite); const int ledPin = 13; // pin to use for the LED void setup() { Serial.begin(9600); // set LED pin to output mode pinMode(ledPin, OUTPUT); // set advertised local name and service UUID: blePeripheral.setLocalName("LED"); blePeripheral.setAdvertisedServiceUuid(ledService.uuid()); // add service and characteristic: blePeripheral.addAttribute(ledService); blePeripheral.addAttribute(switchCharacteristic); // set the initial value for the characeristic: switchCharacteristic.setValue(0); // begin advertising BLE service: blePeripheral.begin(); Serial.println("BLE LED Peripheral"); } void loop() { // listen for BLE peripherals to connect: BLECentral central = blePeripheral.central(); // if a central is connected to peripheral: if (central) { Serial.print("Connected to central: "); // print the central's MAC address: Serial.println(central.address()); // while the central is still connected to peripheral: while (central.connected()) { // if the remote device wrote to the characteristic, // use the value to control the LED: if (switchCharacteristic.written()) { //ココらへんを編集 Serial.println(switchCharacteristic.value()); //debug用 if (switchCharacteristic.value() == 48) { //android側は"0"を送信している Serial.println("LED on"); digitalWrite(ledPin, HIGH); // will turn the LED on } else if(switchCharacteristic.value() == 49) {//android側は"1"を送信している Serial.println(F("LED off")); digitalWrite(ledPin, LOW); // will turn the LED off } } } // when the central disconnects, print it out: Serial.print(F("Disconnected from central: ")); Serial.println(central.address()); } }
  Android側
Android側のプログラムは結構な量なのでポイントだけ記述します(全てのプログラムはGitHubに上げます)
  はじめにAndroidManifest.xmlの編集です
bleのスキャニングには位置情報も必要です
<!-- permission --> <uses-permission android:name="android.permission.BLUETOOTH"/> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/> <uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <!-- android 5.0以上の場合は必要 --> <uses-feature android:name="android.hardware.location.gps" />
  MainActivity.javaの編集
パ���ミッションの設定やマテリアルデザインのSnackBar等を入れています
SnackBarについてはここを参照してください
  おおまか流れとして、
レイアウトやボタンの等のIDのくくりつけ
端末でBLEが使えるか確認
BluetoothがONになっているか確認
位置情報のパーミッションはOKになっているか
接続ボタン(connect_button)を押すとGenuino 101へ接続
操作のボタン(left_button, right_button)で0と1を送信している
切断ボタン(disconnect_button)を押すとGenuino 101を切断
という流れになっています
  GATTがなんなのかがわかればなんとかなる?と思います
また、昨年の私もドツボにはまったのですが、Bluetoothのペアリングからの通信とBLEのペアリングからの通信は全く違うので注意が必要です
public class MainActivity extends AppCompatActivity implements View.OnClickListener{ private static final int REQUEST_ENABLE_BT = 1; private static final int REQUEST_CODE_LOCATE_PERMISSION = 5; //UUID系 private static String GENUINOMACADDRESS = "11:11:11:11:11:11"; //Genuino 101のBLEアドレス private static String LEDSERVICEUUID = "19B10000-E8F2-537E-4F6C-D104768A1214"; //custom service private static String CHARACTERISTICUUID = "19B10001-E8F2-537E-4F6C-D104768A1214"; //charactersticuuid //devicelevel private final static int SDKVER_LOLLIPOP = 21; //BLE private BluetoothAdapter mBluetoothAdapter; private BluetoothGatt mBleGatt; private BluetoothLeScanner mBluetoothLeScanner; private BluetoothGattCharacteristic mBluetoothGattCharacteristic; private boolean mIsBluetoothEnable = false; //接続判定 //いろいろ private Button connect_button, disconnect_button, right_button, left_buton; private RelativeLayout layout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /** * 初���化 */ //button connect_button = (Button)findViewById(R.id.connect_button); connect_button.setOnClickListener(this); disconnect_button = (Button)findViewById(R.id.disconnect_button); disconnect_button.setOnClickListener(this); right_button = (Button)findViewById(R.id.right_button); right_button.setOnClickListener(this); left_buton = (Button)findViewById(R.id.left_button); left_buton.setOnClickListener(this); //relytive layout = (RelativeLayout) findViewById(R.id.relativeLayout); //BLEがサポートしているかの確認 if(!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)){ Snackbar.make(layout, R.string.ble_not_supported, Snackbar.LENGTH_LONG).show(); finish(); } //bluetoothがONになっているか確認 final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); mBluetoothAdapter = bluetoothManager.getAdapter(); if(mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()){ Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); } //permisstion if(PermissionChecker.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){ requestLocatePermission(); return; } } /** * 位置情報のpermisstion */ private void requestLocatePermission() { if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) { new AlertDialog.Builder(this) .setTitle("パーミッションの追加説明") .setMessage("このアプリを使うには位置情報の許可が必要です") .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE_LOCATE_PERMISSION); } }) .create() .show(); return; } ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE_LOCATE_PERMISSION); return; } /** * デバイスの検索(LOLIPOP以上の時) */ private void scanLeDevice(){ if(Build.VERSION.SDK_INT >= SDKVER_LOLLIPOP){ //LOLIOPOP以上の処理 this.scanLeDeviceLolipop(); }else{ mBluetoothAdapter.startLeScan(mScanCallback); } } @TargetApi(SDKVER_LOLLIPOP) private void scanLeDeviceLolipop() { mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner(); //デバイスの検出 mBluetoothLeScanner.startScan(new ScanCallback() { @Override public void onScanResult(int callbackType, ScanResult result) { super.onScanResult(callbackType, result); //genoinoに接続 MACアドレスの比較 if(result.getDevice().toString().equals(GENUINOMACADDRESS)){ result.getDevice().connectGatt(getApplicationContext(), false, mGattCallback); } } @Override public void onScanFailed(int errorCode) { super.onScanFailed(errorCode); } }); } /** * デバイスの検索(LOLIPOP以下の処理) */ private final BluetoothAdapter.LeScanCallback mScanCallback = new BluetoothAdapter.LeScanCallback(){ @Override public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) { mBleGatt = device.connectGatt(getApplicationContext(), false, mGattCallback); } }; /** * GATTへ接続 */ private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback(){ @Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState){ if (newState == BluetoothProfile.STATE_CONNECTED) { // 接続できたらサービスの検索 gatt.discoverServices(); }else if(newState == BluetoothProfile.STATE_DISCONNECTED){ //接続が切れたらGATTを空にする if(mBleGatt != null){ mBleGatt.close(); mBleGatt = null; } mIsBluetoothEnable = false; } } @Override public void onServicesDiscovered(BluetoothGatt gatt, int status){ //Serviceがあれば実行 if (status == BluetoothGatt.GATT_SUCCESS) { //UUIDの突き合わせ BluetoothGattService service = gatt.getService(UUID.fromString(LEDSERVICEUUID)); if(service != null){ //charastaticseの突き合わせ mBluetoothGattCharacteristic = service.getCharacteristic(UUID.fromString(CHARACTERISTICUUID)); if(mBluetoothGattCharacteristic != null){ //LEDとCHARAが一緒ならgattの更新 mBleGatt = gatt; Snackbar.make(layout, "接続しました", Snackbar.LENGTH_LONG).show(); //ペアリング完了のフラッグ mIsBluetoothEnable = true; } } } } }; /** * Buttonの処理 * @param v */ @Override public void onClick(View v) { switch (v.getId()){ case R.id.connect_button: if(mIsBluetoothEnable == false) scanLeDevice(); else Snackbar.make(layout, "接続済みです", Snackbar.LENGTH_SHORT).show(); break; case R.id.disconnect_button: if(mIsBluetoothEnable == true){ mBleGatt.close(); mBleGatt = null; mIsBluetoothEnable = false; Snackbar.make(layout, "切断しました", Snackbar.LENGTH_SHORT).show(); } else Snackbar.make(layout, "切断しています", Snackbar.LENGTH_SHORT).show(); break; case R.id.right_button: if(mIsBluetoothEnable == true){ mBluetoothGattCharacteristic.setValue("1"); //"1"という文字列を送信 mBleGatt.writeCharacteristic(mBluetoothGattCharacteristic); }else{ Snackbar.make(layout, "接続してください", Snackbar.LENGTH_SHORT).show(); } break; case R.id.left_button: if(mIsBluetoothEnable == true){ mBluetoothGattCharacteristic.setValue("0"); //"0"という文字列を送信 mBleGatt.writeCharacteristic(mBluetoothGattCharacteristic); }else{ Snackbar.make(layout, "接続してください", Snackbar.LENGTH_SHORT).show(); } break; } } }
  実際に動作しているところ
去年できなかったandroidとgenuinoをble接続するプログラムを作ることに成功して嬉しみ 動画はLちかさせてます http://pic.twitter.com/t8RB1ZYZpS
— みやかわ (@momijinn_aka) 2017年4月18日
  AndroidでBLEペアリングができるようになったので、Genuino 101以外のマイコンでも接続できると思うので夢が広がります ( ˘ω˘)
  参考文献
http://ift.tt/2oXFRya
http://ift.tt/16xeVId
http://ift.tt/2oXL35a
http://ift.tt/1QqpAcj
from AutumnColor.com http://ift.tt/2oXQr8y via IFTTT
0 notes
besttoptech-blog · 7 years ago
Text
AppChecker - List APIs of Apps 1.Eight-b63 beta Mod Apk Bag Latast
AppChecker – List APIs of Apps 1.Eight-b63 beta Mod Apk Bag Latast
Tumblr media
This app displays the TargetAPI of all of your put in apps. This allows you to verify, which of your apps already toughen basically the most up-to-date components of your Android System.
For many who can also very successfully be working Android 6 Marshmallow, this app helps you to verify which of your apps already toughen the unique granular permission settings.
Guidelines from Google: As…
View On WordPress
0 notes
jeeteshsurana · 6 years ago
Text
Getting Current Location via GPS and service call every 30 min.
http://bit.ly/2Wtwu74
Getting Current Location via GPS and service call every 30 min.
__________________________________________________________
Gradle 
__________________________________________________________
dependencies {
implementation 'com.google.android.gms:play-services-location:16.0.0'
}
__________________________________________________________
GPSTracker.java
__________________________________________________________
package com.android.coroutines;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class GPSTracker extends Service implements LocationListener {
    // Get Class Name
    private static String TAG = GPSTracker.class.getName();
    private final Context mContext;
    // flag for GPS Status
    boolean isGPSEnabled = false;
    // flag for network status
    boolean isNetworkEnabled = false;
    // flag for GPS Tracking is enabled
    boolean isGPSTrackingEnabled = false;
    Location location;
    double latitude;
    double longitude;
    // How many Geocoder should return our GPSTracker
    int geocoderMaxResults = 1;
    // The minimum distance to change updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
    // Declaring a Location Manager
    protected LocationManager locationManager;
    // Store LocationManager.GPS_PROVIDER or LocationManager.NETWORK_PROVIDER information
    private String provider_info;
    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }
    /**
     * Try to get my current location by GPS or Network Provider
     */
    @SuppressLint("MissingPermission")
    public void getLocation() {
        try {
            locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
            //getting GPS status
            isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            //getting network status
            isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
            // Try to get location if you GPS Service is enabled
            if (isGPSEnabled) {
                this.isGPSTrackingEnabled = true;
                Log.d(TAG, "Application use GPS Service");
                /*
                 * This provider determines location using
                 * satellites. Depending on conditions, this provider may take a while to return
                 * a location fix.
                 */
                provider_info = LocationManager.GPS_PROVIDER;
            } else if (isNetworkEnabled) { // Try to get location if you Network Service is enabled
                this.isGPSTrackingEnabled = true;
                Log.d(TAG, "Application use Network State to get GPS coordinates");
                /*
                 * This provider determines location based on
                 * availability of cell tower and WiFi access points. Results are retrieved
                 * by means of a network lookup.
                 */
                provider_info = LocationManager.NETWORK_PROVIDER;
            }
            // Application can use GPS or Network Provider
            if (!provider_info.isEmpty()) {
                locationManager.requestLocationUpdates(
                        provider_info,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES,
                        this
                );
                if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(provider_info);
                    updateGPSCoordinates();
                }
            }
        }
        catch (Exception e)
        {
            //e.printStackTrace();
            Log.e(TAG, "Impossible to connect to LocationManager", e);
        }
    }
    /**
     * Update GPSTracker latitude and longitude
     */
    public void updateGPSCoordinates() {
        if (location != null) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
        }
    }
    /**
     * GPSTracker latitude getter and setter
     * @return latitude
     */
    public double getLatitude() {
        if (location != null) {
            latitude = location.getLatitude();
        }
        return latitude;
    }
    /**
     * GPSTracker longitude getter and setter
     * @return
     */
    public double getLongitude() {
        if (location != null) {
            longitude = location.getLongitude();
        }
        return longitude;
    }
    /**
     * GPSTracker isGPSTrackingEnabled getter.
     * Check GPS/wifi is enabled
     */
    public boolean getIsGPSTrackingEnabled() {
        return this.isGPSTrackingEnabled;
    }
    /**
     * Stop using GPS listener
     * Calling this method will stop using GPS in your app
     */
    public void stopUsingGPS() {
        if (locationManager != null) {
            locationManager.removeUpdates(GPSTracker.this);
        }
    }
    /**
     * Function to show settings alert dialog
     */
    public void showSettingsAlert() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
        //Setting Dialog Title
        alertDialog.setTitle("Title");
        //Setting Dialog Message
        alertDialog.setMessage("Dialog");
        //On Pressing Setting button
        alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });
        //On pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                dialog.cancel();
            }
        });
        alertDialog.show();
    }
    /**
     * Get list of address by latitude and longitude
     * @return null or List<Address>
     */
    public List<Address> getGeocoderAddress(Context context) {
        if (location != null) {
            Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
            try {
                /**
                 * Geocoder.getFromLocation - Returns an array of Addresses
                 * that are known to describe the area immediately surrounding the given latitude and longitude.
                 */
                List<Address> addresses = geocoder.getFromLocation(latitude, longitude, this.geocoderMaxResults);
                return addresses;
            } catch (IOException e) {
                //e.printStackTrace();
                Log.e(TAG, "Impossible to connect to Geocoder", e);
            }
        }
        return null;
    }
    /**
     * Try to get AddressLine
     * @return null or addressLine
     */
    public String getAddressLine(Context context) {
        List<Address> addresses = getGeocoderAddress(context);
        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String addressLine = address.getAddressLine(0);
            return addressLine;
        } else {
            return null;
        }
    }
    /**
     * Try to get Locality
     * @return null or locality
     */
    public String getLocality(Context context) {
        List<Address> addresses = getGeocoderAddress(context);
        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String locality = address.getLocality();
            return locality;
        }
        else {
            return null;
        }
    }
    /**
     * Try to get Postal Code
     * @return null or postalCode
     */
    public String getPostalCode(Context context) {
        List<Address> addresses = getGeocoderAddress(context);
        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String postalCode = address.getPostalCode();
            return postalCode;
        } else {
            return null;
        }
    }
    /**
     * Try to get CountryName
     * @return null or postalCode
     */
    public String getCountryName(Context context) {
        List<Address> addresses = getGeocoderAddress(context);
        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String countryName = address.getCountryName();
            return countryName;
        } else {
            return null;
        }
    }
    @Override
    public void onLocationChanged(Location location) {
    }
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
    @Override
    public void onProviderEnabled(String provider) {
    }
    @Override
    public void onProviderDisabled(String provider) {
    }
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
__________________________________________________________
GPSServiceIntent.kt
__________________________________________________________
package com.android.coroutines.util
import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.app.AlarmManager
import android.app.IntentService
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.net.Uri
import android.os.*
import android.util.Log
import androidx.annotation.NonNull
import androidx.annotation.RequiresApi
import com.android.coroutines.GPSTracker
import com.android.coroutines.dashboard.Constant
import com.google.android.gms.location.FusedLocationProviderClient
import okhttp3.MultipartBody
import okhttp3.RequestBody
import com.justcodenow.musicplayerdemo.util.helper.FileUtils
import okhttp3.MediaType
import java.util.*
@Suppress("UNREACHABLE_CODE", "NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS")
class GPSServiceIntent : IntentService("GPSServiceIntent") {
    private var mLocationManager: LocationManager? = null
    var LOCATION_REFRESH_TIME = 0L
    var LOCATION_REFRESH_DISTANCE = 0F
    var mLat = 0.0
    var mLng = 0.0
    var wakeLock: PowerManager.WakeLock? = null
    private var fusedLocationClient: FusedLocationProviderClient? = null
    init {
        setIntentRedelivery(true) //if you want this process started again then you should pass true other wise pass false
    }
    override fun onHandleIntent(intent: Intent?) {
        val mPendingIntent = PendingIntent.getActivity(applicationContext, 0, intent, 0)
    }
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        return START_STICKY
    }
    override fun onCreate() {
        super.onCreate()
        handler.post(periodicUpdate)
    }
    //init the values and api call
    @SuppressLint("MissingPermission")
    private fun init() {
        val gpsTracker: GPSTracker = GPSTracker(applicationContext!!)
        if (gpsTracker.isGPSTrackingEnabled) {
            Log.d(Constant.Tag,"lat-->${gpsTracker.latitude}")
            Log.d(Constant.Tag,"lng-->${gpsTracker.longitude}")
        }
    }
    override fun onDestroy() {
        super.onDestroy()
        Log.d(Constant.Tag, "-->Destroy Service")
        wakeLock?.release()
        Log.d(Constant.Tag, "-->wakeLock Release")
    }
    var handler = Handler()
    private val periodicUpdate = object : Runnable {
        @TargetApi(Build.VERSION_CODES.KITKAT)
        override fun run() {
            handler.postDelayed(this, 1000) // schedule next wake up every second
            val notificationIntent = Intent(this@GPSServiceIntent, GPSServiceIntent::class.java)
            val pendingIntent =
                PendingIntent.getActivity(this@GPSServiceIntent, 0, notificationIntent, 0)
            val keepAwake = getSystemService(Context.ALARM_SERVICE) as AlarmManager
            keepAwake.setExact(
                AlarmManager.ELAPSED_REALTIME_WAKEUP,
                SystemClock.elapsedRealtime() + 1000,
                pendingIntent
            )
            val current = System.currentTimeMillis()
            if ((current - current % 1000) % (1000 * 1800) == 0L) { // record on every tenth seconds (0s, 10s, 20s, 30s...)
                init()
            }
        }
    }
    @RequiresApi(Build.VERSION_CODES.KITKAT)
    private fun prepareFilePart(partName: String, fileUri: Uri): MultipartBody.Part {
        // http://bit.ly/1mM9Ggw
        // use the FileUtils to get the actual file by uri
        val file = FileUtils.getFile(this, fileUri)
        // create RequestBody instance from file
        val requestFile = RequestBody.create(
            MediaType.parse(Objects.requireNonNull(contentResolver.getType(fileUri))), file
        )
        // MultipartBody.Part is used to send also the actual file name
        return MultipartBody.Part.createFormData(partName, file!!.name, requestFile)
    }
}
__________________________________________________________
DashboardFragment.kt [run the service]
__________________________________________________________
if (!mBaseActivity!!.isServiceRunning(GPSServiceIntent::class.java)) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        context?.startForegroundService(Intent(context, GPSServiceIntent::class.java))
    } else {
        context?.startService(Intent(context, GPSServiceIntent::class.java))
    }
} else {
    Log.d(Constant.Tag, "service are already running ")
}
__________________________________________________________
BaseActivity.kt [copy paste the code in BaseActivity.kt]
__________________________________________________________
fun isServiceRunning(serviceClass: Class<*>): Boolean {
    val manager = this.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager?
    for (service in manager!!.getRunningServices(Integer.MAX_VALUE)) {
        if (serviceClass.name == service.service.className) {
            return true
        }
    }
    return false
}
__________________________________________________________
via Blogger http://bit.ly/2I4KwrG
0 notes
besttoptech-blog · 7 years ago
Photo
Tumblr media
AppChecker – Checklist APIs of Apps 1.Eight-b62 beta Mod Apk Download Latast This app shows the TargetAPI of your total build in apps. Due to this you can overview, which of your apps already toughen the most contemporary parts of your Android System.
0 notes
besttoptech-blog · 7 years ago
Photo
Tumblr media
AppChecker – Listing APIs of Apps 1.Eight-b62 Mod Apk Fetch Latast This app displays the TargetAPI of all of your installed apps. This lets you take a look at, which of your apps already purple meat up essentially the latest formula of your Android Scheme.
0 notes
besttoptech-blog · 7 years ago
Photo
Tumblr media
AppChecker – Checklist APIs of Apps 1.eight-b62 Mod Apk Download Latast This app shows the TargetAPI of your total installed apps. This permits you to test, which of your apps already lend a hand the most modern parts of your Android System.
0 notes