open pdf file - Android Studio

Alright so I am developing an android app and I am looking for a way to open a pdf file by pushing a button does anyone know how to do this?
I want to be able to push a button on a activity that will open up a pdf file so you can view it
thanks in advance

whitesled said:
Alright so I am developing an android app and I am looking for a way to open a pdf file by pushing a button does anyone know how to do this?
I want to be able to push a button on a activity that will open up a pdf file so you can view it
thanks in advance
Click to expand...
Click to collapse
Hi try this code:
Code:
try {
var f = Ti.Filesystem.getFile('your.pdf');
Ti.Android.currentActivity.startActivity(Ti.Android.createIntent({
action: Ti.Android.ACTION_VIEW,
type: 'application/pdf',
data: f.getNativePath()
}));
}
catch (err) {
var alertDialog = Titanium.UI.createAlertDialog({
title: 'No PDF Viewer',
message: 'We tried to open a PDF but failed. Do you want to search the marketplace for a PDF viewer?',
buttonNames: ['Yes','No'],
cancel: 1
});
alertDialog.show();
alertDialog.addEventListener('click', function(evt) {
if (evt.index == 0) {
Ti.Platform.openURL(linkweb + 'q=pdf');
}
});
}

Related

XML parsing-best method, general discussion

I am relatively new to programing and have been teaching myself as I go. I am trying to now integrate ESPN's API into my app which outputs XML data. I have done enough research to understand that I need to use an XML parser and that the XML can be displayed as a list view or web view by adding HTML markup.
I would like this thread to become a general discussion for all new developers on what XML parsing is and what it does. How it works, the code behind it etc.
I am currently trying to modify a code snippet from the developer.google.com website.
Android includes built in libraries for XML Parsing.
You can see a minimal use of the library here:
Code:
import java.io.IOException;
import java.io.StringReader;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
public class SimpleXmlPullApp
{
public static void main (String args[])
throws XmlPullParserException, IOException
{
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput( new StringReader ( "<foo>Hello World!</foo>" ) );
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if(eventType == XmlPullParser.START_DOCUMENT) {
System.out.println("Start document");
} else if(eventType == XmlPullParser.START_TAG) {
System.out.println("Start tag "+xpp.getName());
} else if(eventType == XmlPullParser.END_TAG) {
System.out.println("End tag "+xpp.getName());
} else if(eventType == XmlPullParser.TEXT) {
System.out.println("Text "+xpp.getText());
}
eventType = xpp.next();
}
System.out.println("End document");
}
}
So essentially, you can grab the xml from ESPN, save it to a file, parse it with that library, and output as desired.
Full details here: http://developer.android.com/reference/org/xmlpull/v1/XmlPullParser.html
the fastest way I know is the parser written in c/c++ and compiled with ndk.
bitpushr said:
Android includes built in libraries for XML Parsing.
So essentially, you can grab the xml from ESPN, save it to a file, parse it with that library, and output as desired.
Full details here: http://developer.android.com/reference/org/xmlpull/v1/XmlPullParser.html
Click to expand...
Click to collapse
I will have to try out this code. Because I am learning as I go there are many things in java I don't yet understand which ultimately make it a lot harder to accomplish tasks but I am slowly catching on
If you want to do this in a .NET (Windows x86/64, Windows Mobile, Windows Phone) environment, or a Linux MONO environment then the following will carry out the bare minimum of parsing.
Assuming you have the data in an XML file :- PARAMS.XML in the same folder as the program, created similar to this:
Code:
<?xml version="1.0" encoding="UTF-8" ?>
<PARAMS>
<Library>TESTLIB</Library>
<Source>C:\RetData\</Source>
</PARAMS>
Then the following C# code will read and extract the parameters:
Code:
using System.Xml;
string LibName,RetDir;
XmlReader xrdr = XmlReader.Create(Application.StartupPath+"\\PARAMS.xml");
xrdr.ReadToFollowing("Library");
Libname=xrdr.ReadElementContentAsString();
xrdr.ReadToFollowing("Source");
RetDir = xrdr.ReadElementContentAsString();
xrdr.Close();
After executing this code then:
LibName = "TESTLIB"
RetDir = "C:\RetData\"
CAVEAT:
I mentioned that this is the bare minimum. An XmlReader object is a forward only reader. Also, this code has no error checking.
In this case the elements must be read in the order they occur or the reader will encounter a null element and throw an error.

[Q] detect if app is sideloaded in windows runtime

I am working on a windows phone Runtime app I want to know how can I find if the app is side loaded or it downloaded from Store directly ? Note : I want to prevent application run when it's sideloaded. I want to prevent crack installation of application
ngame said:
I am working on a windows phone Runtime app I want to know how can I find if the app is side loaded or it downloaded from Store directly ? Note : I want to prevent application run when it's sideloaded. I want to prevent crack installation of application
Click to expand...
Click to collapse
Application License file is your solution.
I think it is difficult to implement. If your app is paid then it will be easy to implement.
Can you mention more details is your app is paid or free or anything else more what you want to do ?
I can do it reading the registry value if some debug cap is attached or configuring write access to the installation path(It is available only the app is side-loaded).
djamol said:
Application License file is your solution.
I think it is difficult to implement. If your app is paid then it will be easy to implement.
Can you mention more details is your app is paid or free or anything else more what you want to do ?
I can do it reading the registry value if some debug cap is attached or configuring write access to the installation path(It is available only the app is side-loaded).
Click to expand...
Click to collapse
It will be a paid app .
in C# you know for example if you type
#if DEbUG
#endif
the code between these two lines will only run when the app running in the debug mode
or
#if Windows_Phone_App
#endif
will only run these lines when app running on a Windows Phone Device .
I'm looking for something like these #if or something else to detect this app isn't installed from store to run this code :
App.Current.Exit();
to prevent using cracked versions and also block these users .
No different between how to detect if the app is sideloaded or not
but the most important thing is this app want to be published on Store so I have to use not restricted APIs and codes .
@ngame
Yeah, forget about that. but you can use file access method for store app.
Is it perfect for you ? It is old method but good one to prevent from side-loading.
Code:
using System.Xml.Linq;
using Microsoft.Phone.Controls;
using System.Linq;
using System.Collections.Generic;
using Microsoft.Phone.Marketplace;
using Microsoft.Phone.Tasks;
using System.Collections.ObjectModel;
using Coding4Fun.Phone.Controls.Data;
public static bool IsHacked()
{
try
{
if (Debugger.IsAttached == true) //then WMAppPRHeader.xml file will be added during AppHub certification only! So this has to be skipped during development.
return false;
//scramble WMAppPRHeader.xml file name to make life a little harder in case of reverse engineering
string fl = "xxx" + "W" + "xxxx" + "M" + "xxxx" + "A" + "xxxx" + "p" + "xxxpxxx" + "PxR" + "xxxxx" + "Hxxxxxxx" + "exxxxxxa" + "xxxx" + "d" + "xxxx" + "xxxxe" + "rxx" + "xxx";
fl = fl.Replace("x", string.Empty) + "." + "x" + "m" + "l";
XDocument doc = XDocument.Load(fl); //is hacked, this file is missing or empty!!!
return false;
}
catch (Exception)
{
MessageBox.Show("This app was pirated and is not safe to use, please download the original one from Marketplace.");
MarketplaceDetailTask marketplaceDetailTask = new MarketplaceDetailTask();
//ProcutdID will be changed after APpHub certification, so has to be read from manifest!
marketplaceDetailTask.ContentIdentifier = PhoneHelper.GetAppAttribute("ProductID").Replace("{", string.Empty).Replace("}", string.Empty).Trim(); //download Coding4Fun toolkit for this helper
marketplaceDetailTask.ContentType = MarketplaceContentType.Applications;
marketplaceDetailTask.Show();
return true;
}
}
djamol said:
@ngame
Yeah, forget about that. but you can use file access method for store app.
Is it perfect for you ? It is old method but good one to prevent from side-loading.
Code:
using System.Xml.Linq;
using Microsoft.Phone.Controls;
using System.Linq;
using System.Collections.Generic;
using Microsoft.Phone.Marketplace;
using Microsoft.Phone.Tasks;
using System.Collections.ObjectModel;
using Coding4Fun.Phone.Controls.Data;
public static bool IsHacked()
{
try
{
if (Debugger.IsAttached == true) //then WMAppPRHeader.xml file will be added during AppHub certification only! So this has to be skipped during development.
return false;
//scramble WMAppPRHeader.xml file name to make life a little harder in case of reverse engineering
string fl = "xxx" + "W" + "xxxx" + "M" + "xxxx" + "A" + "xxxx" + "p" + "xxxpxxx" + "PxR" + "xxxxx" + "Hxxxxxxx" + "exxxxxxa" + "xxxx" + "d" + "xxxx" + "xxxxe" + "rxx" + "xxx";
fl = fl.Replace("x", string.Empty) + "." + "x" + "m" + "l";
XDocument doc = XDocument.Load(fl); //is hacked, this file is missing or empty!!!
return false;
}
catch (Exception)
{
MessageBox.Show("This app was pirated and is not safe to use, please download the original one from Marketplace.");
MarketplaceDetailTask marketplaceDetailTask = new MarketplaceDetailTask();
//ProcutdID will be changed after APpHub certification, so has to be read from manifest!
marketplaceDetailTask.ContentIdentifier = PhoneHelper.GetAppAttribute("ProductID").Replace("{", string.Empty).Replace("}", string.Empty).Trim(); //download Coding4Fun toolkit for this helper
marketplaceDetailTask.ContentType = MarketplaceContentType.Applications;
marketplaceDetailTask.Show();
return true;
}
}
Click to expand...
Click to collapse
my code is runtime not a silverlight but I think I got what I have to do from your codes .
I implement a little code in my Program to see what will happen on my Beta release in store .
thanks a lot .
It Works .
write access to Install Directory solved the problem really easy .
Thanks

How to get access to System folders when making a new app?

Does anyone know how to get access to system folders when making a new app? I am trying to create a new Ad Blocking application for windows (Based on AdAway from android) but cannot get permissions to write to C:\Windows\System32\DRIVERS\ETC\HOSTS.
Can anyone help me out super quick?
sandix said:
Does anyone know how to get access to system folders when making a new app? I am trying to create a new Ad Blocking application for windows (Based on AdAway from android) but cannot get permissions to write to C:\Windows\System32\DRIVERS\ETC\HOSTS.
Can anyone help me out super quick?
Click to expand...
Click to collapse
send your code to access that folder + your app CAPABILITIES to make it faster to answer you . .
I think you have to add many Second_Party and First_PARTY capabilities to your app .
ngame said:
send your code to access that folder + your app CAPABILITIES to make it faster to answer you . .
I think you have to add many Second_Party and First_PARTY capabilities to your app .
Click to expand...
Click to collapse
Is that for the AppxManifest.xml file? Where and what do I add?
ngame said:
send your code to access that folder + your app CAPABILITIES to make it faster to answer you . .
I think you have to add many Second_Party and First_PARTY capabilities to your app .
Click to expand...
Click to collapse
I am using this to write to the AppData folder for my app, but can I do something similar to get to the \Windows\System32\DRIVERS\etc folder?
Code:
private async Task WriteToFile(string content)
{
// Get the text data from the textbox.
byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(content.ToCharArray());
// Get the local folder.
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
// Create a new folder name DataFolder.
var dataFolder = await local.CreateFolderAsync("DataFolder",
CreationCollisionOption.OpenIfExists);
// Create a new file named DataFile.txt.
var file = await dataFolder.CreateFileAsync("hosts.txt",
CreationCollisionOption.ReplaceExisting);
// Write the data from the textbox.
using (var s = await file.OpenStreamForWriteAsync())
{
s.Write(fileBytes, 0, fileBytes.Length);
}
}
sandix said:
I am using this to write to the AppData folder for my app, but can I do something similar to get to the \Windows\System32\DRIVERS\etc folder?
Code:
private async Task WriteToFile(string content)
{
// Get the text data from the textbox.
byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(content.ToCharArray());
// Get the local folder.
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
// Create a new folder name DataFolder.
var dataFolder = await local.CreateFolderAsync("DataFolder",
CreationCollisionOption.OpenIfExists);
// Create a new file named DataFile.txt.
var file = await dataFolder.CreateFileAsync("hosts.txt",
CreationCollisionOption.ReplaceExisting);
// Write the data from the textbox.
using (var s = await file.OpenStreamForWriteAsync())
{
s.Write(fileBytes, 0, fileBytes.Length);
}
}
Click to expand...
Click to collapse
You have to use
StorageFileFile.GetFilefromPath("c:\\ window\\syste32\\drivers\\etc\\Hosts");
This will let you access this storage file if you use correct capabilities on wmappmanfest
I assume that the proper capabilities need to be manually entered into that file?
If so what ones do I need? Because a lot of the ones I've tried give me errors (invalid capabilities)
CAN A MOD PLEASE CLOSE THIS THREAD, I WAS ABLE TO FIGURE THIS OUT ON MY OWN.
Thanks!

Help enabling downloads through webview (Kotlin)

Good day. I'm new to android development and I'm trying to develop a simple webview application, picked a nice template and went through the steps and made good progress, I managed to load my site fully and enable javascript, that works as intended, however I'm not able to make the app download anything, I host a few pdf files that should open or download through it, but nothing happens.
I looked at a few answers here and it is to my understanding that I need to specifically add a function for that, could you give me a hand? I have tried multiple different code and tweaking them, but I wasn't able to get it to work, here is my base code:
Code:
package com.logista.test.ui.home
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import android.app.DownloadManager
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.logista.test.R
class HomeFragment : Fragment() {
private lateinit var homeViewModel: HomeViewModel
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
homeViewModel =
ViewModelProvider(this).get(HomeViewModel::class.java)
val root = inflater.inflate(R.layout.fragment_home, container, false)
val myWebView: WebView = root.findViewById(R.id.webview)
myWebView.webViewClient = WebViewClient()
myWebView.settings.javaScriptEnabled = true
myWebView.loadUrl("https://www.example.org/")
return root
}
}
I believe I should be adding
Code:
import android.app.DownloadManager
And tweak this
Code:
// Set web view download listener
web_view.setDownloadListener(DownloadListener {
url,
userAgent,
contentDescription,
mimetype,
contentLength ->
// Initialize download request
val request = DownloadManager.Request(Uri.parse(url))
// Get the cookie
val cookies = CookieManager.getInstance().getCookie(url)
// Add the download request header
request.addRequestHeader("Cookie",cookies)
request.addRequestHeader("User-Agent",userAgent)
// Set download request description
request.setDescription("Downloading requested file....")
// Set download request mime tytpe
request.setMimeType(mimetype)
// Allow scanning
request.allowScanningByMediaScanner()
// Download request notification setting
request.setNotificationVisibility(
DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
// Guess the file name
val fileName = URLUtil.guessFileName(url, contentDescription, mimetype)
// Set a destination storage for downloaded file
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName)
// Set request title
request.setTitle(URLUtil.guessFileName(url, contentDescription, mimetype));
// DownloadManager request more settings
request.setAllowedOverMetered(true)
request.setAllowedOverRoaming(false)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
request.setRequiresCharging(false)
request.setRequiresDeviceIdle(false)
}
request.setVisibleInDownloadsUi(true)
// Get the system download service
val dManager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
// Finally, request the download to system download service
dManager.enqueue(request)
})
// Load button click listener
button_load.setOnClickListener{
// Load url in a web view
web_view.loadUrl(url)
}
}
Taken from here: https://android--code.blogspot.com/2018/03/android-kotlin-webview-file-download.html
I did the basics, renaming the function accordingly and such, but it gives me quite a few errors when building the app, for instance uri isn't defined, cookiemanager isn't defined, environment isn't defined, build isn't defined, and such, could you give me some guidance?

[DexKit] Xposed Module Jni Lib | An easy-to-use, high-performance dex deobfuscation library

Library: DexKit
Project Link: https://github.com/LuckyPray/DexKit
About: An easy-to-use, high-performance dex deobfuscation library. Easy to use your CMAKE/Android projects.
Highlight:
JNI multi-threaded processing Dex bytecode, more efficient than JVM implementation.
It single search is ms level, You can even inject the host application at runtime without causing an ANR, to the extent permitted.
You can use it to handle reinforced apps(use ClassLoader cookies).
API introduction​There are two APIs can meet most of your usage scenarios:
DexKit::BatchFindClassesUsingStrings
DexKit::BatchFindMethodsUsingStrings
Note: In all cases you should avoid searching for keywords that contain duplicate content, eg: {"key_word", "word"}, as this will cause tags to be overwritten, resulting in inaccurate search results. If there is such a need, open the advanced search mode as much as possible, and use the string to match the content exactly, for example, modify it to this: {"^key_word$", "^word$"}
Click to expand...
Click to collapse
And there are many other APIs:
DexKit::FindMethodCaller: find caller for specified method.
DexKit::FindMethodInvoking: find the called method
DexKit::FindMethodUsingField: Find method to get/set specified field
DexKit::FindMethodUsingString: find method used utf8 string
DexKit::FindMethod: find method by multiple conditions
DexKit::FindSubClasses: find all direct subclasses of the specified class
DexKit::FindMethodUsingOpPrefixSeq: find all method using opcode prefix sequence(op range: 0x00-0xFF)
DexKit::FindMethodUsingOpCodeSeq: find all method using opcode sequence(op range: 0x00-0xFF)
DexKit::GetMethodOpCodeSeq: get method opcode sequence(op range: 0x00-0xFF)
Note: At present, all instructions are only for standard dex instructions and do not include odex optimization instructions.
Click to expand...
Click to collapse
For more detailed instructions, please refer to dex_kit.h.
Quick start​However, this approach will import an extra so file. If you don't want to import an extra so file, please use the second/third method.
build.gradle:
Code:
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
app/build.gradle:
Code:
dependencies {
implementation 'com.github.LuckyPray:DexKit:<version>'
}
​JAVA Example​DexKitBridge provides 2 factory methods to create Dexkit instances:
DexKitBridge.create(apkPath): normally, please use it.
DexKitBridge.create(classLoader, true): for reinforced apps, used classLoader and set option useCookieDexFile to true.
PS: DexKitBridge.create(classLoader, useCookieDexFile = false) ≈ DexKitBridge.create(apkPath), but the former may contain part of the system dex.
Java:
import io.luckypry.dexkit.DexKitBridge;
// ...
public class DexUtil {
static {
System.loadLibrary("dexkit");
}
public static void findMethod() {
// for no-reinforced apps please use apkpath to load, because of the exist of dex2oat and CompactDex(cdex),
// dexkit currently only handles StandardDex.
String apkPath = application.applicationInfo.sourceDir
// try-with-resources, auto close DexKitBridge, no need to call DexKitBridge.close()
// if you don't use try-with-resources, be sure to manually call DexKitBridge.close() to release the jni memory
try (DexKitBridge dexKitBridge = DexKitBridge.create(apkPath)) {
if (dexKitBridge == null) {
Log.e("DexUtil", "DexKitBridge create failed");
return;
}
List<DexClassDescriptor> classes = dexKitBridge.findSubClasses("android.app.Activity", null);
for (DexClassDescriptor clazz : classes) {
String name = clazz.getName();
String simpleName = clazz.getSimpleName();
Class<?> clz = clazz.getClassInstance(hostClassLoader);
Log.i("DexUtil", "findSubClasses: " + clz);
}
} catch (Throwable e) {
Log.e("DexUtil", Log.getStackTraceString(e));
}
}
}
If you have problems using it, please create an issue on the github repo.
Reserved

Categories

Resources