Share data between android

Sharing Content between Android apps

Sharing is caring, as they say, but sharing on Android means something perhaps slightly different. ‘Sharing’ is really shorthand for sending content such as text, formatted text, files, or images between apps.

So if ‘sharing’ == sending content, it makes slightly more sense that it is implemented using ACTION_SEND (or ACTION_SEND_MULTIPLE) Intents and its dozen extras.

While that approach is perfectly valid, I prefer to use ShareCompat, a set of classes in the v4 Support Library designed to make it easy to build intents for sharing content.

Sharing text

Sharing plain text is, as you might imagine, a good place to start. In fact, there’s not a whole lot to it:

ShareCompat.IntentBuilder uses a fluent API where you can chain together multiple method calls, using only the ones you need. For sharing, one of the most important parts is picking the right mime type — this is how apps filter what type of content they can receive. By using text/plain, we signify that our Intent will only contain plain text. Then, of course, setText() is how we actually add the CharSequence to the Intent to send. And while you can certainly send styled text using setText(), there’s no guarantee that the receiving app will honor that styling, so you should ensure that the text is legible with or without styling.

You’ll note we then use resolveActivity() before calling startActivity(). As mentioned in Protecting Implicit Intents with Runtime Checks, this is critical to prevent an ActivityNotFoundException when there is no Activity available to handle the mime type you have selected. While probably not as much of a concern with text/plain, it may be much more common with other types.

Note: when you use startActivity(shareIntent), that respects any default apps the user has set (i.e., if they’ve previously selected sharing all “text/plain” items to a certain app). If you’d like to instead always show a disambiguation chooser, use the intent generated from IntentBuilder.createChooserIntent() as explained in the ACTION_CHOOSER documentation.

Sharing HTML text

Some apps, most notably email clients, also support formatting with HTML. The changes, compared to plain text, are fairly minor:

The differences here are that we use of setHtmlText() in place of setText() and a mime type of text/html replacing text/plain. Here ShareCompat actually does a little bit extra: setHtmlText() also uses Html.fromHtml() to create a fallback formatted text to pass along to the receiving app if you haven’t previously called setText() yourself.

Given that many of the apps that can receive HTML text are email clients, there’s a number of helper methods to set the subject, to:, cc:, and bcc: email addresses as well — consider adding at least a subject to any share intent for best compatibility with email apps.

Of course, you’ll still want to call resolveActivity() just as before — nothing changes there.

Receiving text

While the focus so far has been on the sending side, it is helpful to know exactly what is happening on the other side (if not just to build a simple receiving app to install on your emulator for testing purposes). Receiving Activities add an intent filter to the Activity:

Читайте также:  Sunix texture pack android hack

The action is obviously the more critical part — without that there’s nothing that would denote this as an ACTION_SEND (the action behind sharing). The mime type, same as with our sending code, is also present here. What isn’t as obvious are the two categories. From the element documentation:

Note: In order to receive implicit intents, you must include the CATEGORY_DEFAULT category in the intent filter. The methods startActivity() and startActivityForResult() treat all intents as if they declared the CATEGORY_DEFAULT category. If you do not declare it in your intent filter, no implicit intents will resolve to your activity.

So CATEGORY_DEFAULT is required for our use case. Then, CATEGORY_BROWSABLE allows web pages to natively share into apps without any extra effort required on the receiving side.

And to actually extract the information from the Intent, the useful ShareCompat.IntentReader can be used:

Similar to IntentBuilder, IntentReader is just a simple wrapper that make it easy to extract information.

Sharing files and images

While sending and receiving text is straightforward enough (create text, include it in Intent), sending files (and particularly images — the most common type by far) has an additional wrinkle: file permissions.

The simplest code you might try might look like

And that almost works — the tricky part is in getting a Uri to the File that other apps can actually read, particularly when it comes to Android 6.0 Marshmallow devices and runtime permissions (which include the now dangerous READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE permissions).

My plea: don’t use Uri.fromFile(). It forces receiving apps to have the READ_EXTERNAL_STORAGE permission, won’t work at all if you are trying to share across users, and prior to KitKat, would require your app to have WRITE_EXTERNAL_STORAGE. And really important share targets, like Gmail, won’t have the READ_EXTERNAL_STORAGE permission — so it’ll just fail.

Instead, you can use URI permissions to grant other apps access to specific Uris. While URI permissions don’t work on file:// URIs as is generated by Uri.fromFile(), they do work on Uris associated with Content Providers. Rather than implement your own just for this, you can and should use FileProvider as explained in the File Sharing Training.

Once you have it set up, our code becomes:

Using FileProvider.getUriForFile(), you’ll get a Uri actually suitable for sending to another app — they’ll be able to read it without any storage permissions — instead, you are specifically granting them read permission with FLAG_GRANT_READ_URI_PERMISSION.

Note: we don’t call setType() anywhere when building our ShareCompat (even though in the video I did set it). As explained in the setDataAndType() Javadoc, the type is automatically inferred from the data URI using getContentResolver().getType(uriToImage). Since FileProvider returns the correct mime type automatically, we don’t need to manually specify a mime type at all.

If you’re interested in learning more about avoiding the storage permission, consider watching my Forget the Storage Permission talk or at least go through the slides, which covers this topic in depth at 14:55 (slide 11).

Receiving files

Receiving files isn’t too different from text because you’re still going to use ShareCompat.IntentReader. For example, to make a Bitmap out of an incoming file, it would look like:

Читайте также:  Ol about для андроид что это

Of course, you’re free to do whatever you want with the InputStream — watch out for images that are so large you hit an OutOfMemoryException. All of the things you know about loading Bitmaps still apply.

The Support Library is your friend

With both ShareCompat (and its IntentBuilder and IntentReader) and FileProvider in the v4 Support Library, you’ll be able to include sharing text, HTML text, and files in your app with the best practices by default.

Источник

Sharing Data Between Different Activities in Android Programming

Scope, Local, Global…What do they mean? Find out!

Have you ever heard of the word “scope”? The first thing that pops in your mind could be the zoom-lens that’s attached on top of a sniper rifle, but it means something completely different in the programming world. Scope is an important programming concept you need to understand to become a better programmer.

Today, we’ll talk about the concept of Scope and talk about why it is relevant to programming in Sketchware.

What you’ll need

  1. Sketchware — a mobile IDE on your smartphone
  2. Passion to learn! 🙂

What you’ll learn

  1. Concept of Scope in programming
  2. Passing and retrieving data between activities

Scope

Scope refers to the visibility of variables. In other words, it means which parts of your program can see or use it. Let’s talk about it in terms of Sketchware. I will explain more as we progress through the example below.

Let’s say I created two views — view A and view B:

Note that each activity is linked to its own activity. You can notice that under each .xml files, a corresponding .java file follows after.

Under the activity of view A , I created a variable named a . However, when I move to the activity of view B , I don’t see the variable anywhere! This is because any variable created under view A has a scope that’s limited to only view A . In other words, any activities other than view A has no access to the variable. This concept is not only applied to variables, but also widgets and components. Check out the picture below for better understanding.

Also, take a look at another example below. This is an event generated by using MoreBlock. I named the function scope , and it takes an argument called variable . This variable is ONLY accessible inside this specific event. The concept of scope can be applied in so many ways — these examples were few of the many examples.

Local vs. Global

The variables only accessible by certain files or groups are called local variables. On the other hand, variables accessible anywhere are called global variables.

Sketchware keeps everything local by default.

Now that you understand the difference between local and global variables, a question may come to your mind.

Why do you guys keep everything locally? Wouldn’t it be easier for everyone to create a variable once and use it everywhere?

It’s a really good question. Sure, creating global variable is not a wrongdoing and it’s something developers often do to simplify some things up. However, creating global variables opens a whole another chapter in programming. These variables are usually called “static,” and they should be used only if you know what you’re doing. Creating global variables without having a deep understanding usually messes up the architecture. We wanted Sketchware to be not only a tool but also a great learning experience, so we took the traditional approach.

Читайте также:  Пазлы для android для детей

How can I transfer data to another Activity?

Since global variables are not a thing in Sketchware, there are two ways we can share data between Activities:

  1. Sharing data using File Component
  2. Passing value to another activity using Intent Component

File component lets you save data locally, so even if you exit the application the data remains up-to-date when you re-open the application. Even though the component is not shared globally when you create it, any persisted data is shared globally. Check out the previous Memo tutorial which uses File Component to share data.

Intent

Intent component lets you pass data to another Activity upon navigating. Unlike saving any data locally for future use, it’s just a temporary action. Let’s dig deeper by creating an example.

Start off by adding a new Intent component:

Источник

Shared ViewModel in Android: Shared between Fragments

Communication between Activities or Fragments in Android is a very common thing. Almost every application has some communication between various activities or fragments.

In this blog, we will learn how we can use the ViewModel in our application to communicate between various fragments in our application. We say it as SharedViewModel.

Data sharing between Fragments

Using SharedViewModel, we can communicate between fragments. If we consider two fragments, both the fragments can access the ViewModel through their activity.

Here, one fragment updates the data within the ViewModel which is shared between both the fragments and another fragment observes the changes on that data.

Let’s take a small example and learn it.

Note: Do not forget to add the dependencies required for ViewModel, LiveData.

First, we will create a class SharedViewModel.

Now, we are going to create two Fragments:

  • MessageReceiverFragment : This Fragment is going to receive the message which will be sent by MessageSenderFragment. It will have a TextView which will show the received message.
  • MessageSenderFragment : This Fragment is going to send the message which will be received by MessageReceiverFragment. It will have a Button to send the message.

Now, let’s update the activity_main.xml .

Our MainActivity Class.

Now, you are ready to run the app, see if it is working as expected. It should work.

Let’s discuss how it is working:

  • Here, we have created an activity that consists of two fragments. The same activity is the host for both the fragment.
  • In both the fragment, we have created the object of SharedViewModel which is the same object as we are using the same single activity as an owner. This is the reason it is shared. Notice that we have used the requireActivity() .
  • In the MessageSenderFragment, we are sending the message on button click, which sets the value of message — LiveData in the SharedViewModel.
  • Then, in the MessageReceiverFragment, we are observing the change in the message — LiveData , and whenever the message is coming, we are updating the data in textView.

This is how it works.

Important: Create SharedViewModel using the same owner.

Conclusion

In this blog, we learned about Shared ViewModel in Android to communicate with other fragments. In the last, we saw one example of fragment communication using Shared ViewModel. Hope you enjoyed this blog.

Источник

Оцените статью