Android Copy & Paste to any text field in any application - java

I am developing an app for commercial use with a background service that is getting transponder numbers (of animals) from an RFID reader via bluetooth.
After processing the received number I would like to send it to the clipboard and paste it in the focused text field of whatever application is currently in front which in my case is a browser app.
I already found a similar question from 2013 but with no accepted answer by now. All answers to the question just explained how to use ClipboardManager to copy and paste code within the developed application but that has not been meant by the problem as he clarified in a comment.
The simplest scenario that I could imagine is to just simulate a paste action on the android device. I would prefer not to need to install a third party app.

Just to add to Kirill's answer and assuming the app has Accessibility permission,
Create a class extending AccessibilityService and override onAccessibilityEvent method.
public class SampleAccessibilityService extends AccessibilityService {
#Override
public void onAccessibilityEvent(AccessibilityEvent accessibilityEvent) {
AccessibilityNodeInfo source = accessibilityEvent.getSource();
if (source != null) {
AccessibilityNodeInfo rowNode = getRootInActiveWindow();
if (rowNode != null) {
for (int i = 0; i < rowNode.getChildCount(); i++) {
AccessibilityNodeInfo accessibilityNodeInfo = rowNode.getChild(i);
if (accessibilityNodeInfo.isEditable() && accessibilityNodeInfo.isFocused()) {
accessibilityNodeInfo.performAction(AccessibilityNodeInfoCompat.ACTION_PASTE);
return;
}
}
}
}
}
#Override
public void onInterrupt() {
}
}
accessibilityNodeInfo.performAction(AccessibilityNodeInfoCompat.ACTION_PASTE) will paste the text that is copied to clipboard.
Also make sure you have right accessibility configuration.
config.xml
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
android:accessibilityFlags="flagDefault"
android:accessibilityEventTypes="typeViewClicked|typeViewFocused"
android:accessibilityFeedbackType="feedbackGeneric"
android:notificationTimeout="0"
android:canRetrieveWindowContent="true"
android:description="#string/testing" />
Here android:accessibilityEventTypes="typeViewClicked|typeViewFocused" will filter the events to view click or view focus.
You can also the events based on the packages using "android:packageNames" (so that your service won't get called often)
Finally declare the service in manifest,
<service android:name=".SampleAccessibilityService"
android:label="#string/app_name"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService"/>
</intent-filter>
<meta-data
android:name="android.accessibilityservice"
android:resource="#xml/config" />
</service>

If you want your app to interact with an app that isn't yours (the browser) you will have to give this app accessibility permissions. those are special kind of permission that allow apps to interact with something that is a bit more senstive.
there are accessibility actions, the one that you are looking for is the
AccessibilityNodeInfoCompat.ACTION_PASTE it allows you to preform a paste into a focused field.
Note that I'd recommend you to replace the browser with a inapp WebView, and inject the values with javascript this will be much more robust solution for your automation. you can find more info on how to run JS on a webview here: How to get return value from javascript in webview of android?

Related

Backup/restore shared preferences android

I'm trying to backup/restore shared preferences of my app, I followed this step using Android Backup Service:
In Manifest.xml in <application> tag
<meta-data android:name="com.google.android.backup.api_key" android:value="My Key" />
added this class:
public class MyBackupAgent extends BackupAgentHelper {
// The name of the SharedPreferences file
static final String PREFS = "my_preferences";
#Override
public void onCreate() {
SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, PREFS);
addHelper(Utilities.SETTINGS_KEY, helper);
}
}
when set value to shared preference I do this:
BackupManager backupManager = new BackupManager(context);
backupManager.dataChanged();
But if I uninstall/reinstall app, changes doesn't apply...
My guess is you forgot to add
android:allowBackup="true"
inside your <application> tag in the AndroidManifest.xml file
You have to allocate a helper and add it to the backup agent like this:
#Override
public void onCreate() {
FileBackupHelper helper = new FileBackupHelper(this,
TOP_SCORES, PLAYER_STATS);
addHelper(FILES_BACKUP_KEY, helper);
}
and also consider overriding onBackup() and onRestore() methods.
See explanation here:
https://developer.android.com/guide/topics/data/keyvaluebackup.html#BackupAgentHelper
when you call dataChanged() you just notify system that something is changed, it does not start backup in this moment, give it some time and wi fi connection. Check in your device's settings under 'Backup and reset' if 'automatic restore' is set.
Make sure that you writing to the same preferences (with the same key) which you are saving context.getSharedPreferences("my_preferences", Context.MODE_PRIVATE);
I assume you have setting something like this (depends on android version and even on the device)
"Cloud and Accounts"->"Backup and Restore"->"Automatic restoration"
turned on. If not, turning it on may solve your problem.

Android studio change startup activity only once

I am developing an Android app with a Navigation Drawer working this way: the user opens the app and a Tutorial (an activity with a pager sliding fragments, called ScreenSlideActivity.java) pops up; when the user finishes sliding the tutorial, he presses the "finish" button resulting in the initialization of the MainActivity (creating a drawerLayout, drawerToggle etc.)
What I need to do is opening the Tutorial activity just once, after the app's first launch.
I've tried with this code in the main Activity:
if (savedInstanceState == null) {
SelectItem("tutorial");
}
making sure that ScreenSlideActivity.java is immediately started. The problem with this solution is that when the tutorial is opened, from there I'm not able to access MainActivity.java anymore, neither from the "up" botton neither from the Tutorial's last page's "finish" button, probably because for some reason I don't have the main as the parent activity anymore.
Then I've tried this solution change application's starting activity - Android modifying the manifest xml file. Adding:
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
to ScreenSlideActivity.
The problem with this solution is that it changes the structure of my project, making my ScreenSlideActivity.java as the Main and Launching Activity (and therefore from here I cannot access the MainActivity anymore) while all I want to do is to display it once.
What else can I do?
You can use SharedPreferences to check/set if it's the first time opening the app
String preferences_name = "isFirstTime";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
firstTime();
}
...
public void firstTime(){
SharedPreferences sharedTime = getSharedPreferences(preferences_name,0);
if (sharedTime.getBoolean("firstTime",true))
{
//Your tutorial code
sharedTime.edit().putBoolean("firstTime",false).apply();
}
else
{
//When not using tutorial code
}
}
Similiar question here : https://stackoverflow.com/a/13237848/4555911
What I usually to deal with temporary screens is similar to your first solution:
In your MainActivity check if it is the first time the user launches the application. The most common way to do this is using SharedPreferences and checking if a boolean is true or false.
If it is the first time, you start a new activity for your ScreenSlideActivity class with no particular flags. your MainActivity will be in the stack:
MainsActivity -> ScreenSlideActivity
When the users press the finish button you can call the finish() method on your ScreenSlideActivity which will remove the activity from the stack and bring back your MainActivity.

How to add custom view in android's JellyBean Launcher

I am working on making custom launcher in android. I have referred the code of android's Jellybean launcher. now I want to make some modification in this launcher.
What I want : As we know there are default five work-space screens and I want to add custom view in any one of the workspace screen. My xml file should be inflated in any one of the screen.
I have tried many ways to do it but as the default launcher code is very complex still having no luck to finding out way for it.
There is already app named SOHO in Playstore doing exactly what I want. I have add the screenshot for referencing what i want.
Please help me if anyone of you having any idea to do it.
I've the answer for you. You can do it both in Launcher2 and Launcher3 package from (AOSP). Jellybean is using Launcher2 may be. I personally suggest you to go with Launcher3, it has buit-in way to do so.
Launcher3:
create a class that extends the com.android.launcher3.Launcher class and override the necessary methods like so:
public class MyLauncher extends Launcher {
#Override
protected boolean hasCustomContentToLeft() {
return true;
}
#Override
protected void addCustomContentToLeft() {
View customView = getLayoutInflater().inflate(R.layout.custom, null);
CustomContentCallbacks callbacks = new CustomContentCallbacks() {
#Override
public void onShow() {}
#Override
public void onScrollProgressChanged(float progress) {}
#Override
public void onHide() {}
};
addToCustomContentPage(customView, callbacks, "custom view");
}
}
Here R.layout.custom is the custom view that you wanted.
Then in the manifest file change the launcher activity class from Launcher to MyLauncher. And that's it.
Launcher2:
in Workspace.java create the following method:
public void addCustomView(View child){
CellLayout layout = (CellLayout) getChildAt(0);
layout.addView(child);
}
then in Launcher.java, find the following line:
mWorkspace = (Workspace) mDragLayer.findViewById(R.id.workspace);
then paste the following code somewhere after that line:
View child = LayoutInflater.from(this).inflate(R.layout.custom, null);
mWorkspace.addCustomView(child);
If I remember correctly you just need to implement a standard activity which displays a home launcher. In your Manifest.xml you just need to define it like this:
<activity android:name=".YourLauncher" android:label="#string/launcher_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
you can simply add view in default lanucher use code
wm = (WindowManager) getSystemService("window");
params = new LayoutParams();
params.type = LayoutParams.TYPE_PHONE;
params.format = PixelFormat.RGBA_8888;
params.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL
| LayoutParams.FLAG_NOT_FOCUSABLE;
params.x = 100;
params.y = 100;
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
params.width = WindowManager.LayoutParams.WRAP_CONTENT;
params.gravity = Gravity.LEFT | Gravity.TOP;
wm.addView(view, params);
when you want to remove it
just
wm.removeView(v);
you also need permission
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
Good news, not so good news, bad news. Good new first.
It is possible to do what you want.
Now the not so good news.
You will have to write the launcher application from scratch(aka Home Screen). Yep, that involves doing all those nice and nifty things that the default launcher does(multiple pages, drag and drop, delete/add app icons, etc). Fortunately, its not as difficult as it sounds. Because the default launcher app itself is opensource. Though this code is complete, its not easy to read. A easier place to start would be the SDK
Android-SDK/samples/android-x/Home/
where x is the API level.
They have provided source code for an example home screen and it should give you a good start. With some perseverance and coffee, you should be able to modify the Launcher2 code to add a customized page of your own.
Now the Hard part.
Because a part of your goal is to keep the existing pages same and add a new page, getting this to work for all the flavors of android... HTC sense, Samsung TouchWiz, etc, etc is not a single person workload. They all have different features for the Home screen. Preserving these features and adding a new customized page is a tough task.

Android receive images from Gallery in order

I currently have an Android application that has an intent-filter to receive images from the Gallery. It is important that the images are received in the same order that the user selected them in. This seems to be the default behavior on most devices, however on some devices (so far I've seen this on Motorola's running Android 4.x) the order seems undefined. Does anyone know a way to declare in the intent that the images should be received in order? Or a way once the images are recieved to determine the selected order?
Here is relevant code from the manifest
<activity
android:label="#string/app_name"
android:name=".activities.ImportImagesActivity" >
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND_MULTIPLE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
</intent-filter>
</activity>
And from ImportImagesActivity
private List<Uri> parseIncomingData() {
List<Uri> uriList = null;
Intent intent = this.getIntent();
if(intent != null) {
String action = intent.getAction();
//Single Image
if (action.equalsIgnoreCase("android.intent.action.SEND")) {
//removed for brevity
}
}
//Multiple Images
else if (action.equalsIgnoreCase("android.intent.action.SEND_MULTIPLE")) {
uriList = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
}
}
//more code - at this point images have been recieved
return uriList;
}
EDIT
To give a little context, let me explain the general flow of the app.
The user opens the Gallery and selects images. They choose to 'Share' them with my app. My application receives a list of Uri's which are then displayed using an internal gallery backed by a custom Adapter class. The images display correctly based on the Uri list, the issue is the order of the List<Uri> is sometimes incorrect. It is important to my users that the images appear in the same order they select them in.
Clarification
When I use the term Gallery I am referring to the built in Android app Gallery.
When I use the term 'Share' I am referring to the the Share button within the Gallery app. This allows the user to select from a list of services such as Facebook, Email, and in this case my app.
For Example
imagine a Gallery with 3 images, displayed in an arbitrary order: A, B, and C. The user selects first C then A then B and chooses to share them with my app. On most phones my list will be correctly ordered {C, A, B}, on offending phones this order seems random.
I cannot use the creation timestamp because the creation time is generally irrelevant to the selection order. Adding custom meta data doesn't help either because I don't know the correct initial order.
My observation is that Android gallery displays images in accordance to their recency.
For the devices where you're unable to determine the order, you can import the images from the gallery and check their creation time. Here's a way to do that. Or you could use a metadata extractor app, many jars can be found.
Now, you could just arrange the images in the order of recency and you should be done.
[EDIT]
I have a question. You said they may be selected in any order, so are they "uploading" it onto a server by "sharing"?
If so, then one way is to check which image was uploaded or if you want the order of selection, you could do this. Edit the metadata of the images, there's bound to be a useless tag, select one and edit it on touch. So, if I select image A it changes to 1 and then I select image B it becomes 2. But if I unselect image A now then image B should become 1. So, you could use nodes here. This is the first in first out (FIFO) method. Upon un-selection, A is thrown out of the list and B replaces it.
Is this what you wanted?
EDIT
Sorry, I don't think you can do this without creating your own gallery. Why don't you just import the android gallery into a grid view in your app?
Yeah, I just faced the same problem right now. I am also using Fedor's lazy loading concept.I am not sure how far this will be helpful and whether this is the right approach. But still it solved the problem for me.
I had to do a little modification in the getView(),
#Override
public View getView(int position, View convertView, ViewGroup parent) {
System.gc();
ImageView view;
if(convertView == null) {
view = new ImageView(context);
view.setScaleType(ImageView.ScaleType.FIT_CENTER);
view.setLayoutParams(new GridView.LayoutParams(screenWidth/4, screenHeight/4));
view.setAdjustViewBounds(false);
view.setPadding(2, 2, 2, 2);
System.gc();
}else {
view = (ImageView) convertView;
}
if(view!=null)
{
imageLoader.DisplayImage(urlList.get(position), view);
notifyDataSetChanged(); //Calling this helped to solve the problem.
}
System.gc();
return view;
}

Use system PIN dialog in Android application

Background
I am trying to write an application which works like described below.
When user start application it check if user have registered PIN on his device.
If user have registered PIN, application must show button "Continue with PIN".
When user press on button "Continue with PIN" system standard PIN dialog must appears.
User enter his PIN and press "Continue" button.
After System must check if entered PIN is correct or no and continue working.
Searches
I have made some searches and found some articles on stackoverflow and other internet sources which say "There is no way to develop a new custom unlock mechanism on a non-rooted phone." or "I would be surprised if you could, because then you would be probably able to steal the pin code, and I don't think anyone would want that.".
Also I have watched some video tutorials like Tutorial: Android Internals - Building a Custom ROM, Pt. 1 of 2 and Tutorial: Android Internals - Building a Custom ROM, Pt. 2 of 2.
EDITED
I have made some searches today and found a very interesting thing, I think I am on a right way to the solution, and I want to share my ideas with you. So looking in android sources I found an interesting files ChooseLockPassword.java (packages\apps\Settings\src\com\android\settings) and LockPatternUtils.java (*frameworks\base\core\java\com\android\internal\widget*) now I am interest in:
Question
How can I call LockPatternUtils class function from my code ? Or Why I cant see that function in Eclipse ?
Decision
So I think that the only way to get access to the Android system PIN dialog is to root the phone make some changes in the system files and use system PIN dialod
Question
Can somebody provide me useful links about getting access to the system PIN dialog in the rooted phone.
Am I on a right way and can I solve my problem in this way?
If anybody encountered such problem please help me to solve.
Any Solutions?
Okay, I have solved this problem and now I want to share my solution with you.
At first as I told I have android sources so I have made some changes in android sources to get access to the PIN and Pattern dialogs. And here they are:
in ~\AndroidSources\pakages\apps\Settings\AndroidManifest.xml I have changed following lines of code
<activity android:name="ConfirmLockPattern"
android:exported="true"> // This line was added by me.
</activity>
<activity android:name="ConfirmLockPassword"
android:exported="true" // This line was added by me.
android:them="#android:style/Them.NoTitleBar">
</activity>
<activity android:name="ChooseLockPattern"
android:exported="true" // This line was added by me.
android:label="#string/lockpattern_change_lock_pattern_label">
</activity>
This modifications allow me to call "ConfirmLockPattern", "ConfirmLockPassword" and "ChooseLockPattern" activities from my own application. After I compile android Source codes and launch system.img on my emulator.
In my application I have write following functions in order to call "ConfirmLockPattern" or "ChooseLockPattern" activities:
/**
* Show PIN/Password confirmation dialog.
*/
void ShowConfirmLockPINActivity() {
CustomLog.i(TAG, "Show Confirm Lock PIN Activity");
Intent intent = new Intent(Intent.ACTION_RUN);
intent.setComponent(new ComponentName("com.android.settings",
"com.android.settings.ConfirmLockPassword"));
startActivityForResult(intent, mRequestCode);
} /* ShowConfirmLockPINActivity() */
/**
* Show set PIN/Password dialog.
*/
void ShowSetLockPINActivity() {
CustomLog.i(TAG, "Show Set Lock PIN Activity");
Intent intent = new Intent(Intent.ACTION_RUN);
intent.setComponent(new ComponentName("com.android.settings",
"com.android.settings.ChooseLockPassword"));
startActivityForResult(intent, mRequestCode);
} /* ShowSetLockPINActivity() */
/**
* Show Pattern Confirmation dialog.
*/
void ShowSetLockPatternActivity() {
CustomLog.i(TAG, "Show Set Lock Pattern Activity");
Intent intent = new Intent(Intent.ACTION_RUN);
intent.setComponent(new ComponentName("com.android.settings",
"com.android.settings.ConfirmLockPattern"));
startActivityForResult(intent, mRequestCode);
} /* ShowSetLockPatternActivity() */
Here are some considerations regarding your question.
Diving deep into Android's code is not very good idea in this particular case, since verifying PIN code is an important security point and its mechanism must be hidden and well protected to avoid any malicious intentions.
Thus, the actions you want to perform (ask for PIN and then check it against real PIN) are prohibited and would look like an intrusion. So, you shouldn't try to get an access to the storage of user passwords.
It would be more correct to try launching standard PIN screen via some Intent and ask it to make all job for you. However, a brief investigation didn't give me any results in this direction; perhaps, you'll find something.
Modifying the ROM is obviously dead-end - no one will flash the phone to install one app. Requiring rooted phone is a bit better, there are apps that cannot run on non-rooted phone, but still it forwards us back to the point #2 (intrusion).
Users may disable PIN check and there are devices with no SIM.
So, according to the all mentioned I'd suggest you think of different verification method for your app.
Since API level 21 there is KeyguardManager.createConfirmDeviceCredentialIntent that can be used to authenticate current user with the device lock pin.
See the usage example.

Categories