Showing posts with label Integration. Show all posts
Showing posts with label Integration. Show all posts

Monday, 3 July 2023

Google Project Jacquard: Where Fashion Meets Technology.

 In today's rapidly evolving world, the integration of technology into our everyday lives has become increasingly prevalent. From smartphones to smartwatches, we rely on these devices to enhance our efficiency and connectivity. However, there is one area where technology has made significant strides, bridging the gap between fashion and functionality. Google's Project Jacquard is a remarkable endeavor that seamlessly weaves technology into the very fabric we wear, transforming our clothing into interactive, intelligent interfaces.

The Birth of Project Jacquard:

Google's Project Jacquard takes its name from the loom invented in the early 19th century by Joseph Marie Jacquard, which revolutionized the weaving process. Similarly, Google aims to revolutionize our clothing by embedding technology within it. The project was initiated by Google's Advanced Technology and Projects (ATAP) group, known for its groundbreaking and experimental projects.

The Fusion of Technology and Fabric:

At the heart of Project Jacquard lies the development of smart fabrics, which are infused with conductive yarns. These yarns serve as touch-sensitive sensors that can detect various gestures and interactions. The beauty of this technology lies in its versatility, as these smart fabrics can be integrated into any textile, from jeans and jackets to furniture upholstery.

Working Mechanism:

Project Jacquard's technology works by connecting these conductive yarns to miniature electronic components that are seamlessly woven into the fabric. These components include sensors, processors, and wireless connectivity, enabling the fabric to collect and transmit data. The collected data can be processed and interpreted through software applications, opening up a wide range of possibilities.

Endless Possibilities:

The integration of Project Jacquard into clothing allows for a myriad of innovative applications. Imagine being able to control your smartphone or smart home devices simply by tapping or swiping on your sleeve. With a discreet touch or gesture, you could adjust the volume of your music, answer phone calls, or even navigate through maps.

The Potential Impact:

Project Jacquard has the potential to transform various industries. In the fashion world, designers can incorporate interactive elements into their creations, blurring the line between fashion and technology. Additionally, the healthcare industry can benefit from smart garments that monitor vital signs or assist in rehabilitation exercises. The automotive industry can also leverage this technology by integrating it into car interiors, creating safer and more intuitive driving experiences.

Collaborations and Success Stories:

Google's Project Jacquard has collaborated with various renowned brands to bring this technology to life. Partnerships with Levi's, Saint Laurent, and Adidas have led to the creation of innovative clothing items that seamlessly integrate technology into fashion.

One notable success story is the Levi's Commuter Trucker Jacket, powered by Project Jacquard. This smart denim jacket allows wearers to control their music, receive navigation cues, and manage calls and messages with simple touch gestures. It showcases the practicality and usability of this technology in our daily lives.

Privacy and Future Developments:

As with any technology that collects personal data, privacy and security are vital concerns. Google has assured users that Project Jacquard adheres to stringent privacy guidelines, with data being processed and stored securely. The technology is designed to respect the user's privacy and offers control over the collected data.

Looking ahead, Project Jacquard has the potential to reshape our relationship with technology. Continued advancements in smart fabrics, enhanced gesture recognition, and increased collaboration with fashion brands may lead to even more sophisticated and widespread adoption of this technology.

Conclusion:

Google's Project Jacquard represents an exciting intersection between fashion and technology. By embedding touch-sensitive sensors into fabrics, it transforms our clothing into interactive and intelligent interfaces. From improving convenience and functionality in our daily lives to revolutionizing various industries, the possibilities are limitless. As we witness the evolution of smart fabrics, Project Jacquard paves the way for a future where technology becomes seamlessly integrated into our wardrobes.

Sunday, 25 June 2023

The Evolution of Google Maps on Mobile: A Developer's Perspective.

 In the ever-expanding world of mobile applications, few have had as profound an impact as Google Maps. From its humble beginnings as a basic mapping service, Google Maps has evolved into a feature-rich, indispensable tool for users around the globe. In this blog post, we will delve into the evolution of Google Maps on mobile from a developer's perspective, highlighting key milestones and the opportunities they have presented.

The Birth of Mobile Mapping

Google Maps made its debut on mobile devices in 2005 with the release of Google Maps for Java ME, a platform primarily used in early feature phones. This marked the beginning of a new era in mobile navigation, as users could now access interactive maps on the go. From a developer's standpoint, this opened up possibilities for integrating location-based services into their applications.

Introduction of the Google Maps API

Recognizing the potential of Google Maps beyond its standalone application, Google introduced the Google Maps API in 2006. This allowed developers to embed interactive maps directly into their own applications, enabling them to create location-aware experiences. The API provided access to a wealth of geographic data, such as place searches, directions, and satellite imagery, empowering developers to build innovative and personalized applications.

The Rise of Location-Based Services

As smartphones became more prevalent, so did the demand for location-based services. Google Maps responded by introducing additional features and APIs to support this growing trend. The Places API, released in 2010, enabled developers to integrate location-specific information, such as nearby restaurants, hotels, and points of interest, into their apps. This opened up opportunities for businesses to offer personalized recommendations and enhanced user experiences.

Navigation and Real-Time Updates

One of the most significant advancements in Google Maps was the introduction of turn-by-turn navigation in 2009. This feature revolutionized mobile navigation, providing users with voice-guided directions and real-time traffic updates. From a developer's perspective, this meant the ability to incorporate navigation capabilities into their applications, making them more useful and user-friendly.

Indoor Maps and Street View

In 2011, Google introduced indoor maps, allowing users to navigate through large indoor spaces like airports, shopping malls, and museums. Developers gained the ability to leverage this feature to create applications that offered indoor navigation and location-based services within complex structures. Additionally, the integration of Street View in Google Maps provided a 360-degree panoramic view of streets and landmarks, enabling developers to enhance their applications with immersive street-level experiences.

Integration with Other Services

Google Maps continued to evolve by integrating with other Google services and third-party platforms. The integration with Google Places allowed developers to incorporate user-generated content, such as reviews and ratings, into their applications. Furthermore, the introduction of the Google Maps SDK for gaming enabled developers to build location-based games, blending virtual experiences with the real world.

Customization and Personalization

To cater to the diverse needs of developers, Google introduced several customization options and APIs. The Styling Wizard, released in 2013, made it easier for developers to customize the appearance of maps to align with their app's branding. The introduction of the Google Maps Directions API allowed developers to provide customized routing options, such as avoiding tolls or highways, providing users with more control over their navigation experience.

Augmented Reality and Machine Learning

The latest advancements in Google Maps have brought about the integration of augmented reality (AR) and machine learning (ML) technologies. With features like Live View, users can now overlay virtual directions on the real world using their device's camera. From a developer's standpoint, AR and ML technologies present exciting opportunities to create immersive location-based experiences, revolutionizing industries such as tourism, gaming, and navigation.

Conclusion

The evolution of Google Maps on mobile has been nothing short of remarkable, and from a developer's perspective, it has offered a wealth of opportunities for innovation. From the early days of embedding maps into applications to the integration of advanced technologies like AR and ML, Google Maps has continually pushed the boundaries of what is possible in the realm of mobile mapping. As developers, it is crucial to stay abreast of these advancements and leverage the powerful tools and APIs provided by Google Maps to create engaging and personalized experiences for our users.

Tuesday, 17 January 2023

How to Integrate ChatGPT In Android With TTS (Text-To-Speech).

AI (Artificial Intelligence) Technology has been progressing towards futuristic ideas on daily basis. OpenAI coming up with their R&D as ChatGPT is prominent development in this field. ChatGPT (Generative Pre-trained Transformer) is a chatbot launched by OpenAI in November 2022. It is built on top of OpenAI's GPT-3 family of large language models, and is fine-tuned with both supervised and reinforcement learning techniques.

Methods-
ChatGPT trained this model using Reinforcement Learning from Human Feedback (RLHF), using the same methods as InstructGPT, but with slight differences in the data collection setup. They trained an initial model using supervised fine-tuning: human AI trainers provided conversations in which they played both sides—the user and an AI assistant. Then provide the trainers access to model-written suggestions to help them compose their responses. They mixed this new dialogue dataset with the InstructGPT dataset, which are transformed into a dialogue format.


ChatGPT is fine-tuned from a model in the GPT-3.5 series, which finished training in early 2022. You can learn more about the 3.5 series here. ChatGPT and GPT 3.5 were trained on an Azure AI supercomputing infrastructure.

We as technophiles strongly believe in ‘Sharing Is Caring’. We have create a sample demo where we will integrate ChatGPT in Android to demonstrate how it works with TTS (Text-To-Speech).


Here, we have asked for food recipe via ChatGPT bot which is read by TTS bot. We can also create a recipe from a list of ingredients. There are unlimited use-cases and ideas that are possible to explore and make life easy and technological advance.

Refer the below link for complete sample code:-

Download Sample Code

Have a look on few code snippets,

//MainActivity.java
 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
package com.elitetechnority.chatgptdemo;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.StrictMode;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.theokanning.openai.OpenAiService;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.completion.CompletionResult;

import java.util.Locale;

public class MainActivity extends AppCompatActivity {

    private TextToSpeech textToSpeech;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        OpenAiService service = new OpenAiService("Your Token");
        TextView tv_bot=(TextView)findViewById(R.id.tv_bot);
        EditText et_bot=(EditText)findViewById(R.id.et_bot);
        et_bot.setText("Tell about ChatGPT");
        Button btn_bot=(Button)findViewById(R.id.btn_bot);
        btn_bot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CompletionRequest completionRequest = CompletionRequest.builder()
                        .prompt(et_bot.getText().toString())
                        .model("text-davinci-003")
                        .topP(1.0)
                        .temperature(0.3)
                        .maxTokens(150)
                        .frequencyPenalty(0.0)
                        .presencePenalty(0.0)
                        .build();
                CompletionResult completionResult=service.createCompletion(completionRequest);
                System.out.println(completionResult);
                tv_bot.setText(completionResult.getChoices().get(0).getText());
                String toSpeak = tv_bot.getText().toString();
                textToSpeech.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
            }
        });

         textToSpeech=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if(status != TextToSpeech.ERROR) {
                    textToSpeech.setLanguage(Locale.UK);
                }
            }
        });
    }

    @Override
    protected void onPause() {
        if(textToSpeech !=null){
            textToSpeech.stop();
            textToSpeech.shutdown();
        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        if(textToSpeech !=null){
            textToSpeech.stop();
            textToSpeech.shutdown();
        }
        super.onDestroy();
    }
}

Friday, 20 May 2016

HB Blog 111: NDK - Hello World Tutorial.

The Native Development Kit (NDK) is a set of tools that allow you to leverage C and C++ code in your Android apps. You can use it either to build from your own source code, or to take advantage of existing prebuilt libraries. However, it can be useful in cases in which you need to,
  • Squeeze extra performance out of a device for computationally intensive applications like games or physics simulations.
  • Reuse your own or other developers' C or C++ libraries.
In this post, I will explain how to setup NDK as well as run a Hello World program. It's pretty simple.
Basically, installing and setting up the NDK is similar to our normal Android SDK. 
To install and configure the NDK, follow these steps,
  1. Get and install the Android SDK.
  2. Download and extract the NDK, making sure to download the correct version for your development platform. You may place the unzipped directory anywhere on your local drive.
  3. Update your PATH environment variable with the location of the directory that contains the NDK.
  4. Set ndk.dir path in local.properties.
  5. Finally, run normal gradle sync to check it all files are installed clearly. 
There are 2 important files that plays a role in building our NDK application namely, Android.mk and Application.mk. They are actually the make files. Android.mk files defines properties specific to individual modules, or libraries. Whereas, Application.mk defines properties for all the modules that you use in your app.

Android.mk: - The Android.mk file resides in a subdirectory of your project's jni/ directory, and describes your sources and shared libraries to the build system. The syntax of the Android.mk allows you to group your sources into modules. A module is either a static library, a shared library, or a standalone executable. Below is a sample file,

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# Defines the root to all other relative paths
# The macro function my-dir, provided by the build system,
# specifies the path of the current directory (i.e. the
# directory containing the Android.mk file itself)
LOCAL_PATH := $(call my-dir)

# Clear all LOCAL_XXX variables with the exception of
# LOCAL_PATH (this is needed because all variables are global)
include $(CLEAR_VARS)

# List all of our C/C++ files to be compiled (header file
# dependencies are automatically computed)
LOCAL_SRC_FILES := HelloWorldC.c

# The name of our shared module (this name will be prepended
# by lib and postfixed by .so)
LOCAL_MODULE := helloworld

# We need to tell the linker about our use of the liblog.so
LOCAL_LDLIBS += -llog

# Collects all LOCAL_XXX variables since "include $(CLEAR_VARS)"
#  and determines what to build (in this case a shared library)
include $(BUILD_SHARED_LIBRARY)

Application.mk: - The Application.mk file is really a tiny GNU Makefile fragment that defines several variables for compilation. It usually resides under $PROJECT/jni/, where $PROJECT points to your application's project directory. Below is a sample file,
1
2
3
4
5
6
7
8
ANDROID_JPEG_NO_ASSEMBLER := true
APP_PLATFORM := android-9
APP_STL := gnustl_static #gnustl_shared
# ARMv7 is significanly faster due to the use of the hardware FPU
APP_ABI := armeabi armeabi-v7a x86 
APP_OPTIM := release
#APP_CPPFLAGS += -frtti
APP_BUILD_SCRIPT := Android.mk

Now, for creating our Hello World application we need to add this Android.mk and Application.mk make files in jni folder under main folder.We need C or C++ files to be added into the same jni folder. We need header and C main file as per our program functionality. I will show a sample code to display HelloWorld message from C program into java textview. Then, run "javah" utility for compiling this C files, which produces shared output(.so) files in libs folder based on CPUs and Architectures defined in our make files.

Refer the below link for complete sample code:-

Download Sample Code

Have a look on few code snippets,

//HelloWorldC.h
1
2
3
4
5
6
7
8
//
// Created by harshal.benake on 27-04-2016.
//

#ifndef NDKHELLOWORLD_HELLOWORLDC_H
#define NDKHELLOWORLD_HELLOWORLDC_H
JNIEXPORT jstring JNICALL Java_com_example_harshalbenake_ndkhelloworld_MainActivity_getMessage(JNIEnv *, jobject);
#endif //NDKHELLOWORLD_HELLOWORLDC_H

//HelloWorldC.c
1
2
3
4
5
6
7
#include <jni.h>
#include <string.h>
#include "HelloWorldC.h"

JNIEXPORT jstring Java_com_example_harshalbenake_ndkhelloworld_MainActivity_getMessage(JNIEnv *env, jobject thisObj) {
   return (*env)->NewStringUTF(env, "Hello World from native code running successfully");
}

//MainActivity.java 
 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
package com.example.harshalbenake.ndkhelloworld;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {
    static {
        System.loadLibrary("helloworld"); // "helloworldjni.dll" in Windows, "libhelloworldjni.so" in Unixes
    }

    // A native method that returns a Java String to be displayed on the
    // TextView
    public native String getMessage();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Create a TextView.
        TextView textView = new TextView(this);
        // Retrieve the text from native method getMessage()
        textView.setText(getMessage());
        setContentView(textView);
    }
}

Saturday, 16 January 2016

HB Blog 102: How To Decode QR Code From An Image Programmtically???

A barcode is an optical machine-readable representation of data relating to the object to which it is attached.QR code (abbreviated from Quick Response Code) is the trademark for a type of matrix barcode (or two-dimensional barcode).
Various Android applications came on Google Play for scanning QR code and barcodes. For integrating QR code in Android you can follow my blog How To Integrate Barcode/QrCode Scanner For Android?

In this post, I would like to show barcode/QrCode scanner for android using Zxing library without  camera intent.We can scan QR code directly from a image which can be browsed directly from sd-card.

Refer the below link for complete sample code:-

Download Sample Code

Have a look on few code snippets,

//MainActivity.java
 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
package com.example.harshalbenake.decodeqrcode;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.RGBLuminanceSource;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;

import org.json.JSONObject;
import org.json.XML;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button=(Button)findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                decodeQRCode();
            }
        });
    }

    public void decodeQRCode(){
        try
        {
            File directory = new File (Environment.getExternalStorageDirectory() + "/hb");
            File file = new File(directory, "hbcode.jpg"); //or any other format supported
            FileInputStream inputStream = new FileInputStream(file);

            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            if (bitmap == null)
            {
                System.out.println("uri is not a bitmap," + inputStream.toString());
            }
            int width = bitmap.getWidth(), height = bitmap.getHeight();
            int[] pixels = new int[width * height];
            bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
            bitmap.recycle();
            bitmap = null;
            RGBLuminanceSource source = new RGBLuminanceSource(width, height, pixels);
            BinaryBitmap bBitmap = new BinaryBitmap(new HybridBinarizer(source));
            MultiFormatReader reader = new MultiFormatReader();
                Result result = reader.decode(bBitmap);
                System.out.println("XML result: "+result);
                JSONObject xmlJSONObj = XML.toJSONObject(result.toString());
                String jsonPrettyPrintString = xmlJSONObj.toString();
                System.out.println(jsonPrettyPrintString);
                System.out.println("JSON result: "+jsonPrettyPrintString);

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

Sunday, 25 October 2015

HB Blog 100: How To Draw Graphic Elements On MapView Using ArcGIS Android SDK???

In this post, I will brief little about ArcGIS. ArcGIS is a geographic information system (GIS) for working with maps and geographic information. It is used for: creating and using maps; compiling geographic data; analyzing mapped information; sharing and discovering geographic information; using maps and geographic information in a range of applications; and managing geographic information in a database.

Refer below link for Android setup and documentation for ArcGIS Android SDK.
https://developers.arcgis.com/android/

There are many customization that can be done in maps using ArcGIS, I would like to show how to plot point, polylines, polygone, etc. Basically, ArcGIS is made with different layers such as featured layer, graphic layer, etc.  While drawing or plotting grahpical elements or callout on map we use graphic layer. MapView has two layers (that is, a TiledMapServiceLayer and GraphicsLayer). The TiledMapServiceLayer points to a map service on one of Esri's servers, while the GraphicsLayer holds graphic elements that a user draws on the screen. When the sample application starts, a MapView, TiledMapServiceLayer, and GraphicsLayer are instantiated. A TouchListener is added to a MapView and other Android user interface (UI) elements (AlertDialog, Buttons) are also instantiated.
When a user selects a geometry type from the AlertDialog, the AlertDialog's onClick() handler method assigns the appropriate symbology to the GraphicLayer's renderer. The MapView's TouchListener class has handlers to listen to SingleTap, OnDragPointerMove, and OnDragPointerUp events. These collect geometry based on the user's actions on the screen and assign this geometry to a graphic object, which is then added to the GraphicsLayer. This application also retains its state when the device is flipped or the user switches to another application.


Refer the below link for complete sample code:-
Download Sample Code
Download Apk File
Download Support Library
Have a look on few code snippets,

AndroidManifest.xml
 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
<?xml version="1.0" encoding="utf-8"?>
<manifest
  xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.esri.arcgis.android.samples.helloworld"
  android:versionCode="1"
  android:versionName="1.0">

  <uses-sdk
    android:minSdkVersion="10"
    android:targetSdkVersion="19" />

  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

  <uses-feature
    android:glEsVersion="0x00020000"
    android:required="true" />

  <application
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    android:allowBackup="true" >


      <activity
          android:name=".DrawGraphicElements"
          android:configChanges="orientation"
          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>

DrawGraphicElements.java
  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
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
package com.esri.arcgis.android.samples.helloworld;

/**
 * Created by harshalbenake on 01/07/15.
 */
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.esri.android.map.GraphicsLayer;
import com.esri.android.map.MapOnTouchListener;
import com.esri.android.map.MapView;
import com.esri.android.map.ags.ArcGISTiledMapServiceLayer;
import com.esri.android.map.event.OnStatusChangedListener;
import com.esri.core.geometry.MultiPath;
import com.esri.core.geometry.Point;
import com.esri.core.geometry.Polygon;
import com.esri.core.geometry.Polyline;
import com.esri.core.map.Graphic;
import com.esri.core.symbol.SimpleFillSymbol;
import com.esri.core.symbol.SimpleLineSymbol;
import com.esri.core.symbol.SimpleMarkerSymbol;
import com.esri.core.symbol.SimpleMarkerSymbol.STYLE;

public class DrawGraphicElements extends Activity {

    /*
     * ArcGIS Android elements
     */
    MapView mapView = null;
    ArcGISTiledMapServiceLayer tiledMapServiceLayer = null;
    GraphicsLayer graphicsLayer = null;
    MyTouchListener myListener = null;

    /*
     * Android UI elements
     */
    Button geometryButton;
    Button clearButton;
    TextView label;

    /*
     * Other elements that hold app state
     */
    String mapURL = "http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/PublicSafety/PublicSafetyBasemap/MapServer";

    final String[] geometryTypes = new String[] { "Point", "Polyline",
            "Polygon" };

    int selectedGeometryIndex = -1;

    @SuppressWarnings("serial")
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//      setContentView(mapView);
        setContentView(R.layout.main_draw);
        /*
         * Initialize ArcGIS Android MapView, tiledMapServiceLayer, and Graphics
         * Layer
         */
//      mapView = new MapView(this);
        mapView = (MapView)findViewById(R.id.map);
        myListener = new MyTouchListener(DrawGraphicElements.this, mapView);
        mapView.setOnTouchListener(myListener);

        /*
         * Initialize Android Geometry Button
         */
        geometryButton = (Button) findViewById(R.id.geometrybutton);
        geometryButton.setEnabled(false);
        geometryButton.setOnClickListener(new View.OnClickListener() {
            /*
             * This displays an AlertDilaog as defined in onCreateDialog()
             * method. Invocation of show() causes onCreateDialog() to be called
             * internally.
             */
            public void onClick(View v) {
                showDialog(0);
            }
        });

        label = (TextView) findViewById(R.id.label);

        clearButton = (Button) findViewById(R.id.clearbutton);
        clearButton.setEnabled(false);
        clearButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                graphicsLayer.removeAll();


                clearButton.setEnabled(false);
            }
        });

        /*
         * Initialize MapView, TiledMapServiceLayer and GraphicsLayer. This
         * block will be executed when app is started the first time.
         */
//      mapView.setExtent(new Envelope(-85.61828847183895, 38.19242311866144, -85.53589100936443, 38.31361605305102),0);

        tiledMapServiceLayer = new ArcGISTiledMapServiceLayer(mapURL);
        graphicsLayer = new GraphicsLayer();

        /*
         * Use TiledMapServiceLayer's OnStatusChangedListener to listen to
         * events such as change of status. This event allows developers to
         * check if layer is indeed initialized and ready for use, and take
         * appropriate action. In this case, we are modifying state of other UI
         * elements if and when the layer is loaded.
         */
        tiledMapServiceLayer
                .setOnStatusChangedListener(new OnStatusChangedListener() {
                    /*
                     * This callback method will be invokes when status of layer
                     * changes
                     */
                    public void onStatusChanged(Object arg0, STATUS status) {
                        /*
                         * Check if layer's new status = INITIALIZED. If it is,
                         * initialize UI elements
                         */
                        if (status
                                .equals(OnStatusChangedListener.STATUS.INITIALIZED)) {
                            geometryButton.setEnabled(true);
                        }
                    }
                });

        /**
         * Add TiledMapServiceLayer and GraphicsLayer to map
         */
        mapView.addLayer(tiledMapServiceLayer);
        mapView.addLayer(graphicsLayer);
    }

    /*
     * MapView's touch listener
     */
    class MyTouchListener extends MapOnTouchListener {
        // ArrayList<Point> polylinePoints = new ArrayList<Point>();

        MultiPath poly;
        String type = "";
        Point startPoint = null;

        public MyTouchListener(Context context, MapView view) {
            super(context, view);
        }

        public void setType(String geometryType) {
            this.type = geometryType;
        }

        public String getType() {
            return this.type;
        }

        /*
         * Invoked when user single taps on the map view. This event handler
         * draws a point at user-tapped location, only after "Draw Point" is
         * selected from Spinner.
         *
         * @see
         * com.esri.android.map.MapOnTouchListener#onSingleTap(android.view.
         * MotionEvent)
         */
        public boolean onSingleTap(MotionEvent e) {
            if (type.length() > 1 && type.equalsIgnoreCase("POINT")) {
                graphicsLayer.removeAll();
                Graphic graphic = new Graphic(mapView.toMapPoint(new Point(e.getX(), e
                        .getY())),new SimpleMarkerSymbol(Color.RED,25,STYLE.CIRCLE));
                //graphic.setGeometry();
                graphicsLayer.addGraphic(graphic);

                clearButton.setEnabled(true);
                return true;
            }
            return false;

        }

        /*
         * Invoked when user drags finger across screen. Polygon or Polyline is
         * drawn only when right selected is made from Spinner
         *
         * @see
         * com.esri.android.map.MapOnTouchListener#onDragPointerMove(android
         * .view.MotionEvent, android.view.MotionEvent)
         */
        public boolean onDragPointerMove(MotionEvent from, MotionEvent to) {
            if (type.length() > 1
                    && (type.equalsIgnoreCase("POLYLINE") || type
                    .equalsIgnoreCase("POLYGON"))) {

                Point mapPt = mapView.toMapPoint(to.getX(), to.getY());

                /*
                 * if StartPoint is null, create a polyline and start a path.
                 */
                if (startPoint == null) {
                    graphicsLayer.removeAll();
                    poly = type.equalsIgnoreCase("POLYLINE") ? new Polyline()
                            : new Polygon();
                    startPoint = mapView.toMapPoint(from.getX(), from.getY());
                    poly.startPath((float) startPoint.getX(),
                            (float) startPoint.getY());

                    /*
                     * Create a Graphic and add polyline geometry
                     */
                    Graphic graphic = new Graphic(startPoint,new SimpleLineSymbol(Color.RED,5));

                    /*
                     * add the updated graphic to graphics layer
                     */
                    graphicsLayer.addGraphic(graphic);
                }

                poly.lineTo((float) mapPt.getX(), (float) mapPt.getY());

                return true;
            }
            return super.onDragPointerMove(from, to);

        }

        @Override
        public boolean onDragPointerUp(MotionEvent from, MotionEvent to) {
            if (type.length() > 1
                    && (type.equalsIgnoreCase("POLYLINE") || type
                    .equalsIgnoreCase("POLYGON"))) {

                /*
                 * When user releases finger, add the last point to polyline.
                 */
                if (type.equalsIgnoreCase("POLYGON")) {
                    poly.lineTo((float) startPoint.getX(),
                            (float) startPoint.getY());
                    graphicsLayer.removeAll();
                    graphicsLayer.addGraphic(new Graphic(poly,new SimpleFillSymbol(Color.RED)));

                }
                graphicsLayer.addGraphic(new Graphic(poly,new SimpleLineSymbol(Color.BLUE,5)));
                startPoint = null;
                clearButton.setEnabled(true);
                return true;
            }
            return super.onDragPointerUp(from, to);
        }
    }

    /*
     * Returns an AlertDialog that includes names of all layers in the map
     * service
     */
    protected Dialog onCreateDialog(int id) {
        return new AlertDialog.Builder(DrawGraphicElements.this)
                .setTitle("Select Geometry")
                .setItems(geometryTypes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        graphicsLayer.removeAll();

                        // ignore first element
                        Toast toast = Toast.makeText(getApplicationContext(),
                                "", Toast.LENGTH_LONG);
                        toast.setGravity(Gravity.BOTTOM, 0, 0);

                        // Get item selected by user.
                        String geomType = geometryTypes[which];
                        label.setText(geomType + " selected.");
                        selectedGeometryIndex = which;

                        // process user selection
                        if (geomType.equalsIgnoreCase("Polygon")) {
                            myListener.setType("POLYGON");
                            toast.setText("Drag finger across screen to draw a Polygon. \nRelease finger to stop drawing.");
                        } else if (geomType.equalsIgnoreCase("Polyline")) {
                            myListener.setType("POLYLINE");
                            toast.setText("Drag finger across screen to draw a Polyline. \nRelease finger to stop drawing.");
                        } else if (geomType.equalsIgnoreCase("Point")) {
                            myListener.setType("POINT");
                            toast.setText("Tap on screen once to draw a Point.");
                        }

                        toast.show();
                    }
                }).create();
    }


    @Override
    protected void onPause() {
        super.onPause();
        mapView.pause();
    }
    @Override   protected void onResume() {
        super.onResume();
        mapView.unpause();
    }

}

main_draw.xml
 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
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">

  <!-- MapView layout, including basemap layer, initial center point, and zoom level -->
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/geometrybutton"
        android:layout_gravity="center_horizontal" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/clearbutton"
        android:layout_gravity="center_horizontal" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/label"
        android:layout_gravity="center_horizontal" />

    <com.esri.android.map.MapView
    android:id="@+id/map"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    mapoptions.MapType="Topo" />

</LinearLayout>