Showing posts with label Developer Console. Show all posts
Showing posts with label Developer Console. Show all posts

Monday, 14 October 2019

Using Google Maps SDK For Android Using Kotlin.

We know that with the Maps SDK for Android, you can add maps based on Google Maps data to your application. The API automatically handles access to Google Maps servers, data downloading, map display, and response to map gestures. You can also use API calls to add markers, polygons, and overlays to a basic map, and to change the user's view of a particular map area. These objects provide additional information for map locations, and allow user interaction with the map.

Now, lets try the same with Kotlin,

Refer the below link for complete sample code:-

Download Sample Code

Have a look on few code snippets,

//MapsActivity.kt
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package com.elitetechnologies.googlemapkotlin

import android.content.pm.PackageManager
import android.graphics.Color
import android.location.Location
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v7.app.AppCompatActivity
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.Marker
import com.google.android.gms.maps.model.MarkerOptions
import com.google.android.gms.maps.model.PolylineOptions



class MapsActivity : AppCompatActivity(), OnMapReadyCallback, GoogleMap.OnMarkerClickListener {
    companion object {
        private const val LOCATION_PERMISSION_REQUEST_CODE = 1
    }

    private lateinit var mMap: GoogleMap
    private lateinit var fusedLocationClient: FusedLocationProviderClient
    private lateinit var lastLocation: Location

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_maps)
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        val mapFragment = supportFragmentManager
            .findFragmentById(R.id.map) as SupportMapFragment
        mapFragment.getMapAsync(this)
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    override fun onMapReady(googleMap: GoogleMap) {
        mMap = googleMap
        mMap.uiSettings.isZoomControlsEnabled = true
        mMap.setOnMarkerClickListener(this)
        setUpMap()
    }

    override fun onMarkerClick(p0: Marker?): Boolean {
        // Add a marker in Sydney and move the camera
        val sydney = LatLng(-34.0, 151.0)
        var marker = mMap.addMarker(MarkerOptions().position(sydney).title("Marker in Sydney"))
        marker.showInfoWindow()
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))
        return true
    }

    private fun setUpMap() {
        if (ActivityCompat.checkSelfPermission( this,android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION), LOCATION_PERMISSION_REQUEST_CODE
            )
        }

        mMap.isMyLocationEnabled = true
        fusedLocationClient.lastLocation.addOnSuccessListener(this) { location ->
            // Got last known location. In some rare situations this can be null.
            // 3
                lastLocation = location
                val currentLatLng = LatLng(location.latitude, location.longitude)
                mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentLatLng, 12f))

                val markerLocation = LatLng(location.latitude + 2, location.longitude)
                var marker = mMap.addMarker(MarkerOptions().position(markerLocation).title("marker postion"))
                marker.showInfoWindow()

                val polylineOptions = PolylineOptions()
                polylineOptions.add(currentLatLng)
                    .add(LatLng(location.latitude + 2, location.longitude))
                    .add(LatLng(-34.0, 151.0))
                    .width(5f)
                    .color(Color.RED)
                mMap.addPolyline(polylineOptions)
        }
    }
}

Saturday, 1 October 2016

HB Blog 120: How To Sign Your APKs Using Android Studio.

                 Android is open source but, it has security checks at its own level too. It requires that all APKs be digitally signed with a certificate before they can be installed. This tutorial describes how to sign your APKs using Android Studio.
A public-key certificate, also known as a digital certificate or an identity certificate, contains the public key of a public/private key pair, as well as some other metadata identifying the owner of the key (for example, name and location). The owner of the certificate holds the corresponding private key.
When you sign an APK, the signing tool attaches the public-key certificate to the APK. The public-key certificate serves as as a "fingerprint" that uniquely associates the APK to you and your corresponding private key. This helps Android ensure that any future updates to your APK are authentic and come from the original author.
A keystore is a binary file that contains one or more private keys. When you sign an APK for release using Android Studio, you can choose to generate a new keystore and private key or use a keystore and private key you already have. You should choose a strong password for your keystore, and a separate strong password for each private key stored in the keystore. You must keep your keystore in a safe and secure place. You must use the same certificate throughout the lifespan of your app in order for users to be able to install new versions as updates to the app.
You can use Android Studio to manually generate signed APKs, either one at a time, or for multiple build variants at once. Instead of manually signing APKs, you can also configure your Gradle build settings to handle signing automatically during the build process.

To sign your APK for release in Android Studio, follow these steps:
  1. In the menu bar, click Build > Generate Signed APK.
  2. Select the module you would like to release from the drop down, and click Next.
  3. If you already have a keystore, go to step 5. If you want to create a new keystore, click Create new.
  4. On the New Key Store window, provide the following information for your keystore and key, as shown below,
    Keystore
  •         Key store path: Select the location where your keystore should be created.
  •         Password: Create and confirm a secure password for your keystore.
    Key
  •         Alias: Enter an identifying name for your key.
  •         Password: Create and confirm a secure password for your key. This should be different from the password you chose for your keystore
  •         Validity (years): Set the length of time in years that your key will be valid. Your key should be valid for at least 25 years, so you can sign app updates with the same key through the lifespan of your app.
  •         Certificate: Enter some information about yourself for your certificate. This information is not displayed in your app, but is included in your certificate as part of the APK.
Once you complete the form, click OK.
    5. On the Generate Signed APK Wizard window, select a keystore, a private key, and enter the passwords for both. (If you created your keystore in the last step, these fields are already populated for you.) Then click Next.
    6. On the next window, select a destination for the signed APK(s), select the build type, (if applicable) choose the product flavor(s), and click Finish.
When the process completes, you will find your signed APK in the destination folder you selected above. You may now distribute your signed APK through an app marketplace like the Google Play Store, or using the mechanism of your choice.  For more about how to publish your signed APK to the Google Play Store, you can follow my blog,  How To Publish Android Application On Google Play.

Sunday, 1 May 2016

HB Blog 109: Content Assist - The Developer's Friend.

Android Studio and similar other IDE's provide various features to developers which make a comfort environment for them. Hence, it is called as Integrated Development Environment (IDE). More technical, an integrated development environment is a software application that provides comprehensive facilities to computer programmers for software development. One of the most helpful feature is the content assist.

Content/Code assist helps the developer to write code faster and more efficiently. This is achieved by simplifying the task of coding to allow it to focus on the business task being coded. Based on the context of the code, content assist provides the developer with a list of accessible keywords according to a programming language specification, variable, methods, data types.
Autocomplete: - Autocomplete, or word completion, is a feature in which an IDE predicts the rest of a word a user is typing.

For example, in an XML context, when the developer types an opening tag "<" he is offered a list of tags via autocomplete, contextualized following the DTD or XML schema of the document. As the developer types more letters, the offered choices are filtered to only retain the relevant completions. When the developer finally completes the tag, the editor automatically generates the closing tag.

Another example, a developer can just type in the first letter if lowercase and the uppercase letters from a type/variable name then press Ctrl+space to be offered all the choices that match the entered letters that are valid for the current context (class name, interface name, variable or field names).

Code snippet/templates: - Code snippets allow the developer to add a complex coding structure by typing a minimal amount of text. Code snippets can only be used in a valid context (statements snippets are only offered when you can insert statements).

Specifically, in Android Studio ctrl+space (content assist) does 50% work of the developer's work.
Android studio has few more interesting features as well which makes development pretty simple.

Refer below link to meet Android studio,
https://developer.android.com/studio/intro/index.html

Tuesday, 1 September 2015

HB Blog 91: Android Studio's Attractive Features.

Android Studio is the official IDE for Android application development, based on IntelliJ IDEA.
Android Studio offers:
    Flexible Gradle-based build system
    Build variants and multiple apk file generation
    Code templates to help you build common app features
    Rich layout editor with support for drag and drop theme editing
    lint tools to catch performance, usability, version compatibility, and other problems
    ProGuard and app-signing capabilities
    Built-in support for Google Cloud Platform, making it easy to integrate Google Cloud Messaging and App Engine
    And much more.


Most attractive features of android studio from a developer perspective are as follows:-

1)Android Studio allows you to work with layouts in both a Design View. Easily select and preview layout changes for different device images, display densities, UI modes, locales, and Android versions (multi-API version rendering).
From the Design View, you can drag and drop elements from the Palette to the Preview or Component Tree. The Text View allows you to directly edit the XML settings, while previewing the device display.
It updates preview of the layout xml while creating UI which provides read–eval–print loop (REPL) kind of features.

2)Android Studio provides a memory and CPU monitor view so you can more easily monitor your app's performance and memory usage to track CPU usage, find deallocated objects, locate memory leaks, and track the amount of memory the connected device is using. With your app running on a device or emulator, click the Android tab in the lower left corner of the runtime window to launch the Android runtime window. Click the Memory or CPU tab.
When you're monitoring memory usage in Android Studio you can, at the same time, initiate garbage collection and dump the Java heap to a heap snapshot in an Android-specific HPROF binary format file. The HPROF viewer displays classes, instances of each class, and a reference tree to help you track memory usage and find memory leaks.
Android Studio allows you to track memory allocation as it monitors memory use. Tracking memory allocation allows you to monitor where objects are being allocated when you perform certain actions. Knowing these allocations enables you to adjust the method calls related to those actions to optimize your app's performance and memory use.

3)Android Studio projects contain a top-level build file and a build file for each module. The build files are called build.gradle, and they are plain text files that use Groovy syntax to configure the build with the elements provided by the Android plugin for Gradle. In most cases, you only need to edit the build files at the module level. For example, the build file for the app module in the BuildSystemExample project looks like this:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
apply plugin: 'com.android.application'

android {
    compileSdkVersion 19
    buildToolsVersion "19.0.0"

    defaultConfig {
        minSdkVersion 8
        targetSdkVersion 19
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile project(":lib")
    compile 'com.android.support:appcompat-v7:19.0.1'
    compile fileTree(dir: 'libs', include: ['*.jar'])
}

 4)The build system can help you create different versions of the same application from a single project. This is useful when you have a demo version and a paid version of your app, or if you want to distribute multiple APKs for different device configurations on Google Play.
The build system uses product flavors to create different product versions of your app. Each product version of your app can have different features or device requirements. The build system also uses build types to apply different build and packaging settings to each product version. Each product flavor and build type combination forms a build variant. The build system generates a different APK for each build variant of your app.
To define two product flavors, edit the build file for the app module to add the following configuration:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
...
android {
    ...
    defaultConfig { ... }
    signingConfigs { ... }
    buildTypes { ... }
    productFlavors {
        demo {
            applicationId "com.buildsystemexample.app.demo"
            versionName "1.0-demo"
        }
        full {
            applicationId "com.buildsystemexample.app.full"
            versionName "1.0-full"
        }
    }
}
...
The product flavor definitions support the same properties as the defaultConfig element. The base configuration for all flavors is specified in defaultConfig, and each flavor overrides any default values. The build file above uses the applicationId property to assign a different package name to each flavor: since each flavor definition creates a different app, they each need a distinct package name.

5)With smart rendering, Android Studio displays links for quick fixes to rendering errors. For example, if you add a button to the layout without specifying the width and height attributes, Android Studio displays the rendering message Automatically add all missing attributes. Clicking the message adds the missing attributes to the layout.
While debugging, you can now right-click on bitmap variables in your app and invoke View Bitmap. This fetches the associated data from the debugged process and renders the bitmap in the debugger.
When referencing images and icons in your code, a preview of the image or icon appears (in actual size at different densities) in the code margin to help you verify the image or icon reference. Pressing F1 with the preview image or icon selected displays resource asset details, such as the dp settings.  

Saturday, 1 August 2015

HB Blog 86: Android Device Monitor Tools.

The Android SDK includes a variety of tools that help you develop mobile applications for the Android platform. Android Device Monitor is a stand-alone tool that provides a graphical user interface for several Android application debugging and analysis tools. The Monitor tool does not require installation of an integrated development environment, such as Android Studio, and encapsulates the following tools:
DDMS :-
Android Studio includes a debugging tool called the Dalvik Debug Monitor Server (DDMS), which provides port-forwarding services, screen capture on the device, thread and heap information on the device, logcat, process, and radio state information, incoming call and SMS spoofing, location data spoofing, and more. On Android, every application runs in its own process, each of which runs in its own virtual machine (VM). Each VM exposes a unique port that a debugger can attach to.
When DDMS starts, it connects to adb. When a device is connected, a VM monitoring service is created between adb and DDMS, which notifies DDMS when a VM on the device is started or terminated. Once a VM is running, DDMS retrieves the VM's process ID (pid), via adb, and opens a connection to the VM's debugger, through the adb daemon (adbd) on the device. DDMS can now talk to the VM using a custom wire protocol.
Start DDMS :-
To use it, launch the Android Device Monitor, and click the DDMS menu button. DDMS works with both the emulator and a connected device. If both are connected and running simultaneously, DDMS defaults to the emulator.

Hierarchy Viewer :-
The Hierarchy Viewer allows you to debug and optimize your user interface. It provides a visual representation of the layout's View hierarchy (the Layout View) and a magnified inspector of the display (the Pixel Perfect View).
Start Hierarchy Viewer :-
From Android Studio, choose Tools > Android Device Monitor or click the Android Device Monitor icon. Click the Open Perspectives icon and select Hierarchy View.

Systrace :-
The Systrace tool helps analyze the performance of your application by capturing and displaying execution times of your applications processes and other Android system processes. The tool combines data from the Android kernel such as the CPU scheduler, disk activity, and application threads to generate an HTML report that shows an overall picture of an Android device’s system processes for a given period of time.
The Systrace tool is particularly useful in diagnosing display problems where an application is slow to draw or stutters while displaying motion or animation. 
Start Systrace :-
The Systrace tool has different command line options for devices running Android 4.3 (API level 18) and higher versus devices running Android 4.2 (API level 17) and lower.
The general syntax for running Systrace from the command line is as follows.
$ cd android-sdk/platform-tools/systrace
$ python systrace.py [options] [category1] [category2] ... [categoryN]
Traceview :-
Traceview is a graphical viewer for execution logs that you create by using the Debug class to log tracing information in your code. Traceview can help you debug your application and profile its performance. When you have a trace log file (generated by adding tracing code to your application or by DDMS), you can load the log files in Traceview, which displays the log data in two panels:
    A timeline panel -- describes when each thread and method started and stopped
    A profile panel -- provides a summary of what happened inside a method

Start Traceview :-
In the Android Device Monitor tool bar, click DDMS and select a process.
Click the Start Method Profiling icon to start method profiling.
After the profiling is complete, click the Stop Method Profiling icon to display the traceview.

Friday, 1 August 2014

HB Blog 6: New Google Play Store API v2 For Developers.API That Gives Total Control Over APK Updates And Product Listings.

The Google Play Developer Console has undergone some pretty major changes over the years, including a complete overhaul 2 years ago. While the improvements continue to make for a more powerful and usable tool, some developers still find areas where it could be better. Google's engineers don't have time to build everything for everybody, but a new version of the Google Play Developer API makes it possible to build quite a few things for yourself. The new API allows developers to programmatically upload apks and modify almost every detail about your store listings.
2014-07-28_19h54_05
The new web API allows developers to build scripts or applications to automate deployment and update product listings quickly and without directly working with the Developer Console. Most of the new functionality is bundled into the Publishing API, a transaction-based system for managing Play Store listings and apks. It exposes the ability to change just about every field, image, and apk based on language. Further, apks and expansion files can be uploaded to select tracks (i.e. alpha, beta, production, rollout). It's even possible to make modifications to testing groups as needed. It's also possible to change pricing for in-app products, but it is done outside of the transactional model.
The Publishing API will probably become a staple in the distribution systems of larger publishers. Companies will be able to build custom software to enforce their own policies and limit the changes employees can make based on their roles. For example, a marketing manager might be limited to modifying descriptions and featured images, but cannot affect pricing, screenshots, or apk updates. This will also allow publishers to rapidly launch promotions and major updates across several countries and different apps instantly.
Version 1.1 of the API was dedicated to accessing the status of an individual in-app purchase or subscription, and cancelling subscriptions. These functions were available so external servers could fulfill in-app transactions (e.g. giving a paid item to a customer after their purchase is complete) and occasionally for customer service. While the original versions of these methods should remain functional for a long time, new names have been given to these methods, which should probably be used in all future development.
Google hasn't made an announcement regarding these changes (a brief note in the developer console mentions it, thanks Matthieu HarlĂ©), but its cached pages show that the documentation was updated sometime after July 4th. If you're interested in automating some of your Play Store distribution, or even building an app or web service for other developers to use, check out the developer docs for more details.