#dataevents
Explore tagged Tumblr posts
govindhtech · 1 year ago
Text
AWS CloudTrail Monitors S3 Express One Zone Data Events
Tumblr media
AWS CloudTrail
AWS CloudTrail is used to keep track of data events that occur in the Amazon S3 Express One Zone.
AWS introduced you to Amazon S3 Express One Zone, a single-Availability Zone (AZ) storage class designed to provide constant single-digit millisecond data access for your most frequently accessed data and latency-sensitive applications. It is intended to provide up to ten times higher performance than S3 Standard and is ideally suited for demanding applications. S3 directory buckets are used by S3 Express One Zone to store items in a single AZ.
In addition to bucket-level activities like CreateBucket and DeleteBucket that were previously supported, S3 Express One Zone now supports AWS CloudTrail data event logging, enabling you to monitor all object-level operations like PutObject, GetObject, and DeleteObject. In addition to allowing you to benefit from S3 Express One Zone’s 50% cheaper request costs than the S3 Standard storage class, this also enables auditing for governance and compliance.
This new feature allows you to easily identify the source of the API calls and immediately ascertain which S3 Express One Zone items were created, read, updated, or removed. You can immediately take steps to block access if you find evidence of unauthorised S3 Express One Zone object access. Moreover, rule-based processes that are activated by data events can be created using the CloudTrail connection with Amazon EventBridge.
S3 Express One Zone data events logging with CloudTrail
You open the Amazon S3 console first. You will make an S3 bucket by following the instructions for creating a directory bucket, selecting Directory as the bucket type and apne1-az4 as the availability zone. You can type s3express-one-zone-cloudtrail in the Base Name field, and the Availability Zone ID of the Availability Zone is automatically appended as a suffix to produce the final name. Lastly, you click Create bucket and tick the box indicating that data is kept in a single availability zone.
Now you open the CloudTrail console and enable data event tracking for S3 Express One Zone. You put in the name and start the CloudTrail trail that monitors my S3 directory bucket’s activities.
You can choose Data events with Advanced event pickers enabled under Step 2: Choose log events.
S3 Express is the data event type you have selected. To manage data events for every S3 directory bucket, you can select Log all events as my log selector template.
But you just want events for my S3 directory bucket, s3express-one-zone-cloudtrail–apne1-az4–x-s3, to be logged by the event data store. Here, you specify the ARN of my directory bucket and pick Custom as the log selection template.
Complete Step 3 by reviewing and creating. You currently have CloudTrail configured for logging.
S3 Express One Zone data event tracking with CloudTrail in action
You retrieve and upload files to my S3 directory bucket using the S3 interface
Log files are published by CloudTrail to an S3 bucket in a gzip archive, where they are arranged in a hierarchical structure according to the bucket name, account ID, region, and date. You list the bucket connected to my Trail and get the log files for the test date using the AWS CLI.
Let’s look over these files for the PutObject event. You can see the PutObject event type when you open the first file. As you remember, you only uploaded twice: once through the CLI and once through the S3 console in a web browser. This event relates to my upload using the S3 console because the userAgent property, which indicates the type of source that made the API call, points to a browser.
Upon examining the third file pertaining to the event that corresponds to the PutObject command issued through the AWS CLI, I have noticed a slight variation in the userAgent attribute. It alludes to the AWS CLI in this instance.
Let’s now examine the GetObject event found in file number two. This event appears to be related to my download via the S3 console, as you can see that the event type is GetObject and the userAgent relates to a browser.
Let me now demonstrate the event in the fourth file, including specifics about the GetObject command you issued using the AWS CLI. The eventName and userAgent appear to be as intended.
Important information
Starting out The CloudTrail console, CLI, or SDKs can be used to setup CloudTrail data event tracking for S3 Express One Zone.
Regions: All AWS Regions with current availability for S3 Express One Zone can use CloudTrail data event logging.
Activity tracking: You may record object-level actions like Put, Get, and Delete objects as well as bucket-level actions like CreateBucket and DeleteBucket using CloudTrail data event logging for S3 Express One Zone.
CloudTrail pricing
Cost: Just like other S3 storage classes, the amount you pay for S3 Express One Zone data event logging in CloudTrail is determined by how many events you log and how long you keep the logs. Visit the AWS CloudTrail Pricing page to learn more.
For S3 Express One Zone, you may activate CloudTrail data event logging to streamline governance and compliance for your high-performance storage.
Read more on Govindhtech.com
0 notes
cushydiet-blog · 8 years ago
Text
New Post has been published on Mortgage
MBS Day Ahead: Last Day of Moderate Data/Events Before ... - http://bit.ly/2luwiqO - #Ahead, #BreakingNews, #DataEvents, #Day, #MBS, #Moderate, #Mortgage
0 notes
globalmediacampaign · 4 years ago
Text
Amazon DynamoDB now supports audit logging and monitoring using AWS CloudTrail
Amazon DynamoDB is a fully managed, multi-Region, multi-master database that delivers reliable performance at any scale. Because of the flexible DynamoDB data model, enterprise-ready features, and industry-leading service level agreement, customers are increasingly moving sensitive workloads to DynamoDB. Regulated industries (e.g., education, media, finance, and healthcare) may require detailed information about data access activity to help implement security controls and meet industry requirements, including compliance, auditing, and governance of their AWS accounts. Previously, you could use AWS CloudTrail to log control plane activity on your DynamoDB tables and glean information such as who created or deleted a table and when a table was changed. You can now enable data plane activity logging for fine-grained monitoring of all DynamoDB item activity within a table by using CloudTrail. If you’re a database administrator or security professional, you can use this information as part of an audit, to help address compliance requirements, and to monitor which AWS Identity and Access Management (IAM) users, roles, and permissions are being used to access table data. CloudTrail records DynamoDB data events and publishes the log files to an Amazon Simple Storage Service (Amazon S3) bucket. Each event carries information, such as who performed an action and when, which resources were impacted, and many other details. Events are combined in JSON format and saved in CloudTrail log files. With these files, you can track and understand when, for example, an IAM user accessed sensitive information stored in a DynamoDB table. In this post, we show how to create a new trail on the CloudTrail console and enable data event logging for a DynamoDB table. You can use this trail to monitor, alarm, and archive item-level activity on a table. Solution overview This walkthrough provides a step-by-step example of how to create a DynamoDB table, create a CloudTrail trail, enable data events for DynamoDB, create a DynamoDB item, and then review the CloudTrail event. The post assumes that you’re working with an IAM role that can access DynamoDB, CloudTrail, and Amazon S3. If you don’t have an IAM role to access these resources, it’s recommended that you work with your AWS account administrator. The AWS usage in this post alone falls within the Free Tier, but if you consume resources beyond the walkthrough, you could incur associated costs. It’s recommended that you remove resources after the walkthrough. Creating a DynamoDB table To log DynamoDB data events in CloudTrail, you first need a DynamoDB table. For the purposes of this blog post, we create a basic table to follow along with this post. On the DynamoDB console, in the navigation pane, choose Dashboard. Choose Create table. For Table name, enter DynamoDB-CloudTrail. For Partition key, enter pk. Leave Sort key Select Default settings. Choose Create to create the table. Now that you have created the DynamoDB table, you can create and configure the CloudTrail trail to log the data events on the table. Creating a trail Before you enable data event logging in CloudTrail so that you can monitor item-level activity on the DynamoDB table, you must first create a new CloudTrail trail. For a detailed explanation about trail attributes, see Creating a Trail. On the CloudTrail console, choose Create a trail. Choose Trails in the navigation pane. Choose Create trail. For Trail name, enter DynamoDB-DataEvents-Trail. For Storage location, select Create new S3 bucket. For Trail log bucket and folder, enter an S3 bucket name. The console suggests a new bucket name, which must be unique across all existing bucket names in Amazon S3. You also can choose to make your own unique bucket name. Log file SSE-KMS encryption is an additional setting that, if required by your security controls, requires you to use either a new or existing AWS Key Management Service (AWS KMS) customer managed CMK. The remaining configurations are optional enhancements. 9. Choose Next.  You’re redirected to the Choose log events page of the Create trail wizard. Enabling CloudTrail data event logging To enable CloudTrail data event logging for items in your DynamoDB table, complete the following steps: On the Choose log events page, choose Data events. Deselect Management events. Select Data events. DynamoDB data event logging is enabled on a per-table basis in CloudTrail and is disabled by default. This resource-specific configuration allows for data events to be logged on sensitive tables for security and compliance requirements or audit purposes. For Data event source, choose DynamoDB. The default option is to log data events for all DynamoDB tables, but you can deselect the Read and Write check boxes to select individual tables in the subsequent section. Choose Browse to choose the DynamoDB table that you created initially. Choose Next. On the Review and create page, review the configuration and choose Create trail. Now that you have a new trail, you can create and delete an item in the DynamoDB table. On the details page for DynamoDB table you created, choose Create item. Enter the data to insert as a table item. For simplicity, you can disable View DynamoDB JSON and enter values to correspond with the item pk, as shown in the following screenshot. Choose Create item. You can see the new item you created in the Items preview section. You also can delete this item by selecting the item and choosing Delete item(s) from the Actions menu. Understanding and using data event records Creating and deleting items creates data event records in the newly created trail, which you can view in CloudTrail. The following code example shows a CloudTrail record of a DeleteItem action, which is the action you performed in the previous step: { "eventVersion": "1.06", "userIdentity": { "type": "AssumedRole", "principalId": ":", "arn": "arn:aws:sts:: :assumed-role//", "accountId": "", "accessKeyId": "", "sessionContext": { "sessionIssuer": { "type": "Role", "principalId": "", "arn": "arn:aws:iam:: :role/", "accountId": ", "userName": "" }, "attributes": { "creationDate": "2020-10-01T20:00:25Z", "mfaAuthenticated": "false" } } }, "eventTime": "2020-10-20T15:00:25Z ", "eventSource": "dynamodb.amazonaws.com", "eventName": "DeleteItem", "awsRegion": "us-east-1", "sourceIPAddress": "", "userAgent": "console.amazonaws.com", "requestParameters": { "tableName": "", "key": { "key": "" }, "returnValue": "NONE", "returnConsumedCapacity": "NONE" }, "responseElements": null, "requestID": "", "eventID": "", "readOnly": false, "resources": [ { "accountId": "", "type": "AWS::DynamoDB::Table", "ARN": "arn:aws:dynamodb:us-east-1::table/" } ], "eventType": "AwsApiCall", "apiVersion": "2012-08-10", "managementEvent": false, "recipientAccountId": "", } The preceding CloudTrail record is for a single request to DynamoDB, and it details the user and data request information. The record includes a detailed attribution of the principal and the assumed role sessionContext that sent the request, as well as the sourceIPAddress and userAgent (in this case, the console), and whether the user was mfaAuthenticated (not in this case). In addition to the user identity, each record contains detailed information about the data event on DynamoDB. These details include requestParameters, tableName, key, eventName, and more. If a request fails, the error code also is logged. The record combines user and activity, which makes monitoring, alarming, and archiving possible for security and compliance requirements. This record’s user and data event attribution is the information your security team needs to identify a bad actor and build an authoritative reference of compromised activity. Security teams across industries, including finance, healthcare, education, and social media, use these attribution systems not only as detective and preventive controls (identifying and blocking access), but also as a corrective control (impact analysis). Given the potentially high volume of requests per second on a DynamoDB table, it’s important that you consider how you use your data event logs. If your logs are for audit purposes, you should keep the logs active all the time and apply appropriate data lifecycle policies to the data in the S3 bucket. However, if you need the data event logs only for specific activities, such as user access audits, user behavior validation, or troubleshooting, you can enable and disable data event logging situationally in CloudTrail. For robust monitoring and alerting, you also can integrate data events with Amazon CloudWatch Logs. To enhance your analysis of DynamoDB service activity and identify changes in activities for an AWS account, you can query AWS CloudTrail logs using Amazon Athena. For example, you can use queries to identify trends and further isolate activity by attributes, such as source IP address or user. Cleaning up After you create a DynamoDB table and CloudTrail trail, enable data events, create a DynamoDB item, and review the result in CloudTrail, you should remove any resources that you created in this process. Resources that remain active can incur associated costs. Conclusion In this post, we showed how you can use CloudTrail to enable data plane event logging on DynamoDB tables so you can extract invaluable insights to help meet your organization’s security practices for compliance and auditing purposes. To learn more about DynamoDB data plane event logging, see Logging DynamoDB Operations by Using AWS CloudTrail. Additional charges apply for data events. For more information, see AWS CloudTrail pricing. About the Authors Mazen Ali is a Senior Technical Product Manager on the Amazon DynamoDB team.       https://aws.amazon.com/blogs/database/amazon-dynamodb-now-supports-audit-logging-and-monitoring-using-aws-cloudtrail/
0 notes
jacob-cs · 8 years ago
Text
Android wear 개발 방법 (Syncing Data Items)
original source: https://developer.android.com/training/wearables/data-layer/data-items.html
Syncing Data Items
A DataItem defines the data interface that the system uses to synchronize data between handhelds and wearables.
Payload - A byte array, which you can set with whatever data you wish. 크기는  100kb
Path - A unique string that must start with a forward slash
normally don't implement DataItem directly. Instead, you do the following:
Create a PutDataRequest object, specifying a string path to uniquely identify the item.
Call setData() to set the payload.
If a delay in syncing would negatively impact user experience, call setUrgent().
Call DataApi.putDataItem() to request the system to create the data item.
Sync Data with a Data Map
use the DataMap class. This approach lets you work with data items in the form of an Android Bundle, so the system does object serialization and deserialization for you, and you can manipulate data with key-value pairs.
Create a PutDataMapRequest object, setting the path of the data item.
Call PutDataMapRequest.getDataMap() to obtain a data map that you can set values on.
Set any desired values for the data map using the put...() methods, such as putString().
If a delay in syncing would negatively impact user experience, call setUrgent().
Call PutDataMapRequest.asPutDataRequest() to obtain a PutDataRequest object.
Call DataApi.putDataItem() to request the system to create the data item.
Note: If the handset and wearable devices are disconnected, the data is buffered and synced when the connection is re-established.
ex)
public class MainActivity extends Activity implements        DataApi.DataListener,        GoogleApiClient.ConnectionCallbacks,        GoogleApiClient.OnConnectionFailedListener {    private static final String COUNT_KEY = "com.example.key.count";    private GoogleApiClient mGoogleApiClient;    private int count = 0;    ...    // Create a data map and put data in it    private void increaseCounter() {        PutDataMapRequest putDataMapReq = PutDataMapRequest.create("/count");        putDataMapReq.getDataMap().putInt(COUNT_KEY, count++);        PutDataRequest putDataReq = putDataMapReq.asPutDataRequest();        PendingResult<DataApi.DataItemResult> pendingResult =                Wearable.DataApi.putDataItem(mGoogleApiClient, putDataReq);    }    ... }
Set DataItem priority
In Google Play services 8.3 and later, the DataApi interface allows urgent requests for syncing of DataItems. setUrgent() 을 설정한다.
Listen for Data Item Events
public class MainActivity extends Activity implements        DataApi.DataListener,        GoogleApiClient.ConnectionCallbacks,        GoogleApiClient.OnConnectionFailedListener {    private static final String COUNT_KEY = "com.example.key.count";    private GoogleApiClient mGoogleApiClient;    private int count = 0;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        mGoogleApiClient = new GoogleApiClient.Builder(this)                .addApi(Wearable.API)                .addConnectionCallbacks(this)                .addOnConnectionFailedListener(this)                .build();    }    @Override    protected void onResume() {        super.onResume();        mGoogleApiClient.connect();    }    @Override    public void onConnected(Bundle bundle) {        Wearable.DataApi.addListener(mGoogleApiClient, this);    }    @Override    protected void onPause() {        super.onPause();        Wearable.DataApi.removeListener(mGoogleApiClient, this);        mGoogleApiClient.disconnect();    }    @Override    public void onDataChanged(DataEventBuffer dataEvents) {        for (DataEvent event : dataEvents) {            if (event.getType() == DataEvent.TYPE_CHANGED) {                // DataItem changed                DataItem item = event.getDataItem();                if (item.getUri().getPath().compareTo("/count") == 0) {                    DataMap dataMap = DataMapItem.fromDataItem(item).getDataMap();                    updateCount(dataMap.getInt(COUNT_KEY));                }            } else if (event.getType() == DataEvent.TYPE_DELETED) {                // DataItem deleted            }        }    }    // Our method to update the count    private void updateCount(int c) { ... }    ... }
1 note · View note
mbaljeetsingh · 7 years ago
Text
Angular Components: Pass by Reference or Pass by Value?
In Angular, you can pass data from a parent component to a child component using the @Input() decorator, and a child component can emit an event to a parent component using the @Output() decorator.
You can learn more about the @Input() decorator and about the @Output decorator here.
The purpose of this blog post is to explain to you whether it is better to pass by reference or pass by value in the context of the @Input() and the @Output decorator.
To start with, let us assume that we have two components, as listed below:
As you see, we have two input properties.
In data property, we will pass an object.
In count property, we will pass a number.
From AppComponent, we are passing the values for both properties, as shown below:
As you see, we are passing data (object) and count (number) to the child component. Since data is being passed as an object, it will "Pass by Reference" and, since count is passed as number, it will "Pass by Value."
Therefore, if passing an object, array, or the like, then it is Passed by Reference, and for primitive types like numbers, it is Passed by Value.
To better understand it, let us raise two events on the child component, as shown in the listing below:
In both events, we are passing back the same @Input() decorated properties to the parent component. In dataEvent, the data is passed back and in countEvent the count is passed back to the parent component.
In the parent component, we are capturing the event as below:
Let us talk through the updateData and updateCount functions. These functions are capturing events raised on the child component.
In the updateData function, we are incrementing the value of the passed parameter, however, since it is an object, it will update the value of this.data and in the child component, the updated value will be rendered.
In the updateCount function, we are incrementing the value of the passed parameter, however, since it is a primitive type it will not update this.count and in the child component nothing will happen.
As an output on clicking of button, you will find the value of the data is incrementing but the value of the count is not incrementing.
We can summarize this as follows: if we pass objects in the @Input() decorator then it would be passed as a reference, and if we pass primitive types, then it would be passed as a value. I hope you found this article useful. Thanks for reading!
via DZone Web Dev Zone https://ift.tt/2KXS65M
0 notes
cushydiet-blog · 8 years ago
Text
MBS Day Ahead: Last Day of Moderate Data/Events Before ... - https://goo.gl/Nxs5vL - #Ahead, #BreakingNews, #DataEvents, #Day, #MBS, #Moderate, #Mortgage
0 notes
cushydiet-blog · 8 years ago
Text
New Post has been published on Mortgage
MBS Day Ahead: Last Day of Moderate Data/Events Before ... - https://goo.gl/Nxs5vL - #Ahead, #BreakingNews, #DataEvents, #Day, #MBS, #Moderate, #Mortgage
0 notes
jacob-cs · 8 years ago
Text
Android wear 개발방법 (Handling Data Layer Events)
original source : https://developer.android.com/training/wearables/data-layer/events.html
Handling Data Layer Events
When you make a call to the Data Layer API, you can receive the status of the call when it completes.
Note: A Wear app can communicate with a phone app using the Data Layer API, but connecting to a network using this API is discouraged
Wait for the Status of Data Layer Calls
때때로  Data Layer API call 작업(예를 들어  putDataItem() )은  PendingResult를 결과로 되돌린다. 이때 이  PendingResult 를 처리하는 방법에는 두가지가 있다.  (synchronously or asynchronously)
          Asynchronous calls(main thread에서 호출하는 경우)
If your code is running on the main UI thread, do not make blocking calls to the Data Layer API. You can run the calls asynchronously by adding a callback method to the PendingResult object, which fires when the operation is completed(버튼 클릭리스너를 만들어 버튼에 연결하듯 처리하는 방법)
pendingResult.setResultCallback(new ResultCallback<DataItemResult>() {    @Override    public void onResult(final DataItemResult result) {        if(result.getStatus().isSuccess()) {            Log.d(TAG, "Data item set: " + result.getDataItem().getUri());        }    } });
          Synchronous calls(다른 thread에서 호출하는 경우)
If your code is running on a separate handler thread in a background service (which is the case in a WearableListenerService), it's fine for the calls to block. In this case, you can call await() on the PendingResult object, which blocks until the request completes and returns a Result object:
DataItemResult result = pendingResult.await(); if(result.getStatus().isSuccess()) {    Log.d(TAG, "Data item set: " + result.getDataItem().getUri()); }
Listen for Data Layer Events
data layer synchronizes and sends data across the handheld and wearable.
To listen for data layer events, you have two options:
Create a service that extends WearableListenerService.
Create an activity that implements DataApi.DataListener.
          With a WearableListenerService
You typically create instances of this service in both your wearable and handheld apps. If you are not interested in data events in one of these apps, then you don't need to implement this service in that particular app.
Some of the events you can listen for using WearableListenerService are as follows:
onDataChanged(): Whenever a data item object is created, deleted, or changed, the system triggers this callback on all connected nodes.
onMessageReceived(): A message sent from a node triggers this callback on the target node.
onCapabilityChanged(): When a capability that an instance of your app advertises becomes available on the network, that event triggers this callback. If you're looking for a nearby node you can query the isNearby() method of the nodes provided in the callback.
In addition to those on this list, you can listen for events from ChannelApi.ChannelListener, such as onChannelOpened().
All of the above events are executed in a background thread, not on the main thread.
To create a WearableListenerService, follow these steps:
Create a class that extends WearableListenerService.
Listen for the events that you're interested in, such as onDataChanged().
Declare an intent filter in your Android manifest to notify the system about your WearableListenerService. This declaration allows the system to bind your service as needed.
public class DataLayerListenerService extends WearableListenerService {    private static final String TAG = "DataLayerSample";    private static final String START_ACTIVITY_PATH = "/start-activity";    private static final String DATA_ITEM_RECEIVED_PATH = "/data-item-received";    @Override    public void onDataChanged(DataEventBuffer dataEvents) {        if (Log.isLoggable(TAG, Log.DEBUG)) {            Log.d(TAG, "onDataChanged: " + dataEvents);        }        GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)                .addApi(Wearable.API)                .build();        ConnectionResult connectionResult =                googleApiClient.blockingConnect(30, TimeUnit.SECONDS);        if (!connectionResult.isSuccess()) {            Log.e(TAG, "Failed to connect to GoogleApiClient.");            return;        }        // Loop through the events and send a message        // to the node that created the data item.        for (DataEvent event : dataEvents) {            Uri uri = event.getDataItem().getUri();            // Get the node id from the host value of the URI            String nodeId = uri.getHost();            // Set the data of the message to be the bytes of the URI            byte[] payload = uri.toString().getBytes();            // Send the RPC            Wearable.MessageApi.sendMessage(googleApiClient, nodeId,                    DATA_ITEM_RECEIVED_PATH, payload);        }    } }
          Using filters with WearableListenerService
<service android:name=".DataLayerListenerService">  <intent-filter>      <action android:name="com.google.android.gms.wearable.DATA_CHANGED" />      <data android:scheme="wear" android:host="*"               android:path="/start-activity" />  </intent-filter> </service>
manifest에 위와 같이 작성한 서비스를 등록하는 과정설명. 위의 경우 the watch listens for the /start-activity data item, and the phone listens for the /data-item-received message response. 
To match on a wildcard host, use host="*". To match on a specific host, specify host=<node_id>.
For more information on the filter types that Wear supports, see the API reference documentation for WearableListenerService.
For more information on data filters and matching rules, see the API reference documentation for the data manifest element.
When matching intent filters, there are two important rules to remember:
If a scheme is not specified for the intent filter, the system ignores all the other URI attributes.
If no host is specified for the filter, the system ignores all the path attributes.
           With a live listener
If your app only cares about data-layer events when the user is interacting with the app, it may not need a long-running service to handle every data change. In such a case, you can listen for events in an activity by implementing one or more of the following interfaces:
DataApi.DataListener
MessageApi.MessageListener
CapabilityApi.CapabilityListener
To create an activity that listens for data events:
An alternative to adding listeners in onConnected() and removing them in onStop() is to add a filtered listener in an activity's onResume() and remove it in onPause(), to only receive data that is relevant to the current application state.
public class MainActivity extends Activity implements        DataApi.DataListener, ConnectionCallbacks, OnConnectionFailedListener {    private GoogleApiClient mGoogleApiClient;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        mGoogleApiClient = new GoogleApiClient.Builder(this)                .addApi(Wearable.API)                .addConnectionCallbacks(this)                .addOnConnectionFailedListener(this)                .build();    }    @Override    protected void onStart() {        super.onStart();        if (!mResolvingError) {            mGoogleApiClient.connect();        }    }    @Override    public void onConnected(Bundle connectionHint) {        if (Log.isLoggable(TAG, Log.DEBUG)) {            Log.d(TAG, "Connected to Google Api Service");        }        Wearable.DataApi.addListener(mGoogleApiClient, this);    }    @Override    protected void onStop() {        if (null != mGoogleApiClient && mGoogleApiClient.isConnected()) {            Wearable.DataApi.removeListener(mGoogleApiClient, this);            mGoogleApiClient.disconnect();        }        super.onStop();    }    @Override    public void onDataChanged(DataEventBuffer dataEvents) {        for (DataEvent event : dataEvents) {            if (event.getType() == DataEvent.TYPE_DELETED) {                Log.d(TAG, "DataItem deleted: " + event.getDataItem().getUri());            } else if (event.getType() == DataEvent.TYPE_CHANGED) {                Log.d(TAG, "DataItem changed: " + event.getDataItem().getUri());            }        }    } }
Using filters with live listeners
Just as you can specify intent filters for manifest-based WearableListenerService objects, you can also use intent filters when registering a listener through the Wearable API. The same rules are applicable to both API-based listeners manifest-based listeners.
A common pattern is to register a listener with a specific path or path prefix in an activity’s onResume() method, and to remove the listener in the activity’s onPause() method. Implementing listeners in this fashion allows your app to more selectively receive events, improving its design and efficiency.
0 notes
jacob-cs · 8 years ago
Text
Android wear 개발 방법 (Transferring Assets)
original source : https://developer.android.com/training/wearables/data-layer/assets.html
Transferring Assets
image와 같이 크기가 큰 data를 전달하는 경우, you can attach an Asset to a data item and the put the data item into the replicated data store.
data item의 경우 최대 크기가 100kb 이나 assets의 경우에는 그 제한이 없다.
Transfer an Asset
Create the asset using one of the create...() methods in the Asset class.    
private static Asset createAssetFromBitmap(Bitmap bitmap) { final ByteArrayOutputStream byteStream = new ByteArrayOutputStream();     bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteStream);     return Asset.createFromBytes(byteStream.toByteArray()); }
Using PutDataRequest
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image); Asset asset = createAssetFromBitmap(bitmap); PutDataRequest request = PutDataRequest.create("/image"); request.putAsset("profileImage", asset); Wearable.DataApi.putDataItem(mGoogleApiClient, request);
Using PutDataMapRequest
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image); Asset asset = createAssetFromBitmap(bitmap); PutDataMapRequest dataMap = PutDataMapRequest.create("/image"); dataMap.getDataMap().putAsset("profileImage", asset) PutDataRequest request = dataMap.asPutDataRequest(); PendingResult<DataApi.DataItemResult> pendingResult = Wearable.DataApi        .putDataItem(mGoogleApiClient, request);
Receive assets
@Override public void onDataChanged(DataEventBuffer dataEvents) {  for (DataEvent event : dataEvents) {    if (event.getType() == DataEvent.TYPE_CHANGED &&        event.getDataItem().getUri().getPath().equals("/image")) {      DataMapItem dataMapItem = DataMapItem.fromDataItem(event.getDataItem());      Asset profileAsset = dataMapItem.getDataMap().getAsset("profileImage");      Bitmap bitmap = loadBitmapFromAsset(profileAsset);      // Do something with the bitmap    }  } } public Bitmap loadBitmapFromAsset(Asset asset) {    if (asset == null) {        throw new IllegalArgumentException("Asset must be non-null");    }    ConnectionResult result =           mGoogleApiClient.blockingConnect(TIMEOUT_MS, TimeUnit.MILLISECONDS);    if (!result.isSuccess()) {        return null;    }    // convert asset into a file descriptor and block until it's ready    InputStream assetInputStream = Wearable.DataApi.getFdForAsset(            mGoogleApiClient, asset).await().getInputStream();            mGoogleApiClient.disconnect();    if (assetInputStream == null) {        Log.w(TAG, "Requested an unknown Asset.");        return null;    }    // decode the stream into a bitmap    return BitmapFactory.decodeStream(assetInputStream); }
0 notes