What is the Get_Tasks Permission and what is it used for? - permissions

I'm looking into developing apps for a project and I started researching permissions. I know the technical definition of GET_TASKS- Allows an application to get information about the currently or recently running tasks: a thumbnail representation of the tasks, what activities are running in it, etc. What I don't know is just what a "thumbnail" representation is- is it an actual picture (i.e screenshot of what is going on in another app), or is it just some information about the app? Also, what does the definition mean by "what activities are running in it"? Does that mean that someone can develop an app that can practically tell exactly what someone is doing, almost like a spy app (i.e if someone were checking their bank information on their browser, could the app see that?). Thanks for all the help, I'm a total noob here just trying to get used to the developer tools.

It is used within the "context" of a Context... so, gives your Activities. E.g.
Context context = this.hostActivity.getApplicationContext();
ActivityManager am = (ActivityManager)context.getSystemService("activity");
List taskInfo = null;
try {
taskInfo = am.getRunningTasks(1);
if ((taskInfo != null) && (!taskInfo.isEmpty())) {
ComponentName topActivity = ((ActivityManager.RunningTaskInfo)taskInfo.get(0)).topActivity;
if (!topActivity.getPackageName().equals(context.getPackageName())) {
this.logger.debug("The application was displaced by new one.");
needPause = true;
} else {
this.logger.debug("The activity was displaced by new one in the same application.");
}
}
} catch (SecurityException e) {
needPause = true;
this.logger.warn("The application has no GET_TASKS permission.");
}

Related

Ionic AdMob Plus - How to track user rewards in a RewardedAd and show the updated balance in the UI?

I am working with the AdMob-Plus plugin and trying to integrate the RewardedAd as shown here.
THE ISSUE:
I want to offer 3 coins for every RewardedAd watched. My main issue is that I am unable to figure out how to track successfully after a user has watched a complete RewardedAd and increment the existing count of the coins in the user account by adding the new coin value to it and show this new value to the user in the UI.
EXAMPLE:
If the user already has 6 coins in his account and watches a RewardedAd, then his account should show the new balance as 9 coins. How can I achieve this?
THE CODE THAT I HAVE TRIED SO FAR:
async loadRewardsAd(): Promise<void> {
this.rewarded = new this.admob.RewardedAd({
adUnitId: this.adRewardedId,
serverSideVerification: {
customData: 'coin=3',
userId: '1234567',
}
});
// Load rewarded
await this.rewarded.load();
// Display rewarded
await this.rewarded.show();
}
As far as I see there is no option to get the total amount to display in the ad but only the fresh rewarded points like shown here:
if (mRewardedAd != null) {
Activity activityContext = MainActivity.this;
mRewardedAd.show(activityContext, new OnUserEarnedRewardListener() {
#Override
public void onUserEarnedReward(#NonNull RewardItem rewardItem) {
// Handle the reward.
Log.d(TAG, "The user earned the reward.");
int rewardAmount = rewardItem.getAmount();
String rewardType = rewardItem.getType();
}
});
} else {
Log.d(TAG, "The rewarded ad wasn't ready yet.");
}
this is the same code in Kotlin:
if (mRewardedAd != null) {
mRewardedAd?.show(this, OnUserEarnedRewardListener() {
fun onUserEarnedReward(rewardItem: RewardItem) {
var rewardAmount = rewardItem.amount
var rewardType = rewardItem.type
Log.d(TAG, "User earned the reward.")
}
})
} else {
Log.d(TAG, "The rewarded ad wasn't ready yet.")
}
Beware the hint on the top of the page:
Warning: There are many breaking changes coming in version 20.0.0. Version 19.7.0 introduces many new APIs, deprecates many classes and APIs and renames many classes in preparation for version 20.0.0. Please read the migration guide for more details on the changes.
Getting the total amount seems to require to login into the AdMob Reporting API, which is not available for common viewers:
admob/api
The reporting by the cordova-admop api seems even to be impossible, I never found any functionality for it.

User login with Smart Card for Windows UWP app

This seems like such a simple thing but I have been trying to figure this out for over a week now and cannot seem to figure it out. We are creating a Windows UWP app using WinJS and would like the user to login to the app with a PIV (smart card)/PIN combination. Essentially, when the app starts it will verify that there is a smart card inserted into the device and then prompt the user for the PIN. If the PIN is validated against the smart card the app will log the user in.
We do have Windows 7 applications that currently do this and I attempted to convert that code however it appears the APIs we used are not valid for Windows UWP apps. I did post the question about those APIs but did not receive any responses (https://stackoverflow.com/questions/43344679/x509certificate2ui-class-equivalent-with-windows-uwp-and-winjs). With Windows 7 we used the X509Certificate2UI (https://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509certificate2ui(v=vs.110).aspx ) class to select a certificate which prompted the user for the PIN.
After a lot of research, I believe (and could be wrong) with Windows UWP I need to use the smart card APIs (https://learn.microsoft.com/en-us/uwp/api/windows.devices.smartcards ). I have been reading the past couple of days and went through several Microsoft documents on smart cards like this one: https://learn.microsoft.com/en-us/windows/uwp/security/smart-cards but have not been able to find a way to validate a user entered PIN against the PIN on the smart card.
From the SmartCardProvisioning class (https://learn.microsoft.com/en-us/uwp/api/windows.devices.smartcards.smartcardprovisioning ) we are able to call the requestPinChangeAsync() method which prompts the user for the current PIN and the new PIN. I am looking for similar functionality except that it only asks for the current PIN and then returns a value that will let the app know if the PIN was correct.
I have also read through Microsoft’s Hello (https://learn.microsoft.com/en-us/windows/uwp/security/microsoft-passport ) API but did not see a way to use it with smart cards.
Can anyone point me in the right direction on how to use two-factor authentication in my app using a smart card/PIN combination. It seems like I have been in a Google bubble for the past several days going round and round and need help to get out.
Thanks
edit to explain why it is not a duplicate:
Not really a duplicate, both questions were asked by me and I mention the other post in the bod of the question. In the other post I was looking for an equivalent to the X509Certificate2UI class for Windows UWP with WinJS. With further research, I am thinking that might not be the correct way to go therefore with this post I am looking to see if anyone can point me in the right direction to doing two-factor authentication using a PIV (smart card) and the PIN associated with the card.
EDIT: Share code that works:
Here is the WinJS code that seems to work. Not sure is there is a better way or not:
if (certToUse != null) {
Windows.Security.Cryptography.Core.PersistedKeyProvider.openKeyPairFromCertificateAsync(certToUse, Windows.Security.Cryptography.Core.HashAlgorithmNames.sha256, Windows.Security.Cryptography.Core.CryptographicPadding.rsaPkcs1V15).then(function (keyPair) {
var buffer = 'data to sign'
var data = Windows.Security.Cryptography.CryptographicBuffer.convertStringToBinary(buffer, Windows.Security.Cryptography.BinaryStringEncoding.utf16BE)
Windows.Security.Cryptography.Core.CryptographicEngine.signAsync(keyPair, data).then(function (signed) {
var results = Windows.Security.Cryptography.Core.CryptographicEngine.verifySignature(keyPair, data, signed)
completeValidatePin = true
successCallback(true)
}, function (reason) {
completeValidatePin = true
errorCallback('User cancelled login')
})
}, function (reason) {
completeValidatePin = true
errorCallback('Error using certificate')
})
} else {
errorCallback('Certificate not found')
}
I'm currently investigating your question and trying to determine if there is a good solution.
I did write the following code which I thought should work:
IReadOnlyList<Certificate> Certs;
CertificateQuery CertQuery = new CertificateQuery();
CertQuery.HardwareOnly = true;
Certs = await CertificateStores.FindAllAsync(CertQuery);
string strEncrypt = "test";
IBuffer BufferToEncrypt = CryptographicBuffer.ConvertStringToBinary(strEncrypt, BinaryStringEncoding.Utf8);
foreach (Certificate Cert in Certs)
{
if (Cert.HasPrivateKey && ((Cert.KeyStorageProviderName == "Microsoft Base Smart Card Crypto Provider") || Cert.KeyStorageProviderName == "Microsoft Smart Card Key Storage Provider"))
{
CryptographicKey Key = null;
try
{
Key = await PersistedKeyProvider.OpenKeyPairFromCertificateAsync(Cert, HashAlgorithmNames.Sha1, CryptographicPadding.RsaPkcs1V15);
}
catch (Exception ex)
{
// Could not open Smart Card Key Pair
}
if (Key != null)
{
try
{
// Try to Sign with Cert Private key
IBuffer EncryptedBuffer = CryptographicEngine.Sign(Key, BufferToEncrypt);
}
catch (Exception ex)
{
// Could not sign
}
}
}
}
Unfortunately, OpenKeyPairFromCertificateAsync creates a provider with a silent context so CryptographicEngine.Sign is unable to display a PIN dialog. I will have to look into it a bit more.

Trouble Attaching File Programmatically to Email in Windows Metro App C#/XAML using Share Charm

I'm simply trying to attach a file named Document.pdf in the DocumentsLibrary to an email using the Share Charm. My code below works perfectly on the Local Machine:
private async void OnDataRequestedFiles(DataTransferManager sender, DataRequestedEventArgs e)
{
List<IStorageItem> shares = new List<IStorageItem>();
StorageFile filetoShare = await Windows.Storage.KnownFolders.DocumentsLibrary.GetFileAsync("Document.pdf");
if (filetoShare != null)
{
shares.Add(filetoShare);
filetoShare = null;
}
if (shares != null)
{
DataPackage requestData = e.Request.Data;
requestData.Properties.Title = "Title";
requestData.Properties.Description = "Description"; // The description is optional.
requestData.SetStorageItems(shares);
shares = null;
}
else
{
e.Request.FailWithDisplayText("File not Found.");
}
}
But when I run the exact same code on a Windows Surface Tablet, I get the dreaded "There's nothing to share right now." on the right in the Charms flyout area.
Here's a little more background to help:
I'm not looking to use a File Picker...I know the exact file I'm looking for
I've enabled the Documents Library Capability in the manifest
I've added a File Type Association for pdf in the manifest
and yes, the file does exist and is in the Documents Library
an email account is properly setup in the Mail App on the surface
I can successfully send text emails from the Tablet...just not emails with attachments
Like I said, this works on my Win 8 Development Machine as expected...just not on the Surface. I'm wondering if the Surface has different file or folder permissions?
Thanks for the help...this is driving me CRAZY
I finally figured it out - the problem was that my Event Handler was async (so that I could use await to set the StorageFile variable).
I solved it by setting the StorageFile variable earlier in my code so that it was already available when the Event Handler was called.
I still have no idea why it worked on my development machine, but no on the WinRT surface...
The handler can be an async method. In this case, it is critical to use DataTransferManager. Please refer to the MSDN page specifically for this scenario. For your convenience, the code from the page is copied to here:
private void RegisterForShare()
{
DataTransferManager dataTransferManager = DataTransferManager.GetForCurrentView();
dataTransferManager.DataRequested += new TypedEventHandler<DataTransferManager,
DataRequestedEventArgs>(this.ShareStorageItemsHandler);
}
private async void ShareStorageItemsHandler(DataTransferManager sender,
DataRequestedEventArgs e)
{
DataRequest request = e.Request;
request.Data.Properties.Title = "Share StorageItems Example";
request.Data.Properties.Description = "Demonstrates how to share files.";
// Because we are making async calls in the DataRequested event handler,
// we need to get the deferral first.
DataRequestDeferral deferral = request.GetDeferral();
// Make sure we always call Complete on the deferral.
try
{
StorageFile logoFile =
await Package.Current.InstalledLocation.GetFileAsync("Assets\\Logo.png");
List<IStorageItem> storageItems = new List<IStorageItem>();
storageItems.Add(logoFile);
request.Data.SetStorageItems(storageItems);
}
finally
{
deferral.Complete();
}
}
It is critical to place the following statement before any async method is called:
DataTransferManager dataTransferManager = DataTransferManager.GetForCurrentView();
You only have half a second to get the whole job done (getting the file, attaching...etc.). If the half-second deadline occurs you'll get this "driving crazy" message. Consider implementing some resumable logic and replace the message with "the attachment is being prepared please try again in a few seconds" (or else).
Your WinRT device might be just slower than your development machine. The latter just does the job before the deadline...

Error when trying add data to RavenDb

I'm using autofac and the interfaces are correctly resolved but this code fails with "No connection could be made because the target machine actively refused it 127.0.0.1:8081"
using (var store = GetService<IDocumentStore>())
{
using (var session = store.OpenSession())
{
session.Store(new Entry { Author = "bob", Comment = "My son says this", EntryId = Guid.NewGuid(), EntryTime = DateTime.Now, Quote = "I hate you dad." });
session.SaveChanges();
}
}
Here is the registration
builder.Register<IDocumentStore>(c =>
{
var store = new DocumentStore { Url = "http://localhost:8081" };
store.Initialize();
return store;
}).SingleInstance();
When I navigate to http://localhost:8081 I do get the silverlight management UI. Although I'm running a Windows VM and vmware and Silverlight5 don't play together. That's another issue entirely. Anyways does anyone see what I'm doing wrong here or what I should be doing differently? Thanks for any code, tips, or tricks.
On a side note, can I enter some dummy records from a command line interface? Any docs or examples of how I can do that?
Thanks All.
Just curious, are you switching RavenDB to listen on 8081? The default is 8080. If you're getting the management studio to come up, I suspect you are.
I'm not too familiar with autofac but, it looks like you're wrapping your singleton DocumentStore in a using statement.
Try:
using (var session = GetService<IDocumentStore>().OpenSession())
{
}
As far as dummy records go, the management studio will ask you if you want to generate some dummy data if your DB is empty. If you can't get silverlight to work in the VM, I'm not sure if there's another automated way to do it.
Perhaps using smuggler:
http://ravendb.net/docs/server/administration/export-import
But you'd have to find something to import.

Facebook Application building. How do I do a simple API call?

I have 4.5 years experience as a professional PHP developer, I have loads of experience with session handling, etc.
I am wanting to learn how to build Facebook applications. I have gone through the process of downloading the Facebook Developer application, I have used to it Create an App, I have set the canvas URL to where the app is hosted.
I can successfully "install" the app using a Facebook user account, and I can successfully access it. I have noted that when the app is loaded, a whole string of data gets passed to it, with parameter names like fb_sig_user and fb_sig_session_key. Currently, I am doing nothing with these parameters.
On the application end, obviously I am supposed to create a Facebook object by using my own APP ID key and SECRET key, which I have done.
But I can't seem to figure out how to start making API calls from my application back to Facebook.
How do I, at this point, just do something simple like get the person's name and display it to them?
Eg, how do I:
$first_name = $facebook->getUserFirstName();
.. do something like that?
I just want to do a simple test to ensure the API stuff is working.
Any help would be appreciated. Thanks.
The Facebook PHP SDK would probably be your first stop, with some example code as a close runner up.
Making API calls with the Facebook SDK set up alright is as easy as;
$me = $facebook->api('/me'); // Returns array containing data for currently logged in user depending on given permissions
or
$my_friends = $facebook->api('/me/friends'); // Returns array containing information on friends of currently logged in user
and even
$my_profile_img = $facebook->api('/me/picture'); // Returns a string containing URL to users profile picture.
Also, everything within the open graph has unique id's that you can plug in instead of me in /me.
For further and more in-depth description of the Open Graph, I suggest going to the official Graph API Overview page.
Quite easy and fun to work with once you get it set up - albeit a bit slow.
Update:
In order to get the Facebook cookie and set up a session from it I did:
$cookie = get_facebook_cookie($fbconfig['appid'], $fbconfig['secret']);
function get_facebook_cookie($app_id, $application_secret) {
$args = array();
parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
ksort($args);
$payload = '';
foreach ($args as $key => $value) {
if ($key != 'sig') {
$payload .= $key . '=' . $value;
}
}
if (md5($payload . $application_secret) != $args['sig']) {
return null;
}
return $args;
}
if (isset($cookie)) {
$session = $facebook->getSession($cookie);
}
Then updated Facebook.php line 332 to be
public function getSession($passedCookie) {
and line 373 to be
$this->setSession($passedCookie, $write_cookie);
Lame hacking, but it worked for me at least