Android Code: Downloading from within an app - G1 Q&A, Help & Troubleshooting

I've searched the android website but I cannot find any sample code that will allow you to download something from a webpage/website. I'm trying to create a simple application that will allow you to download a podcast from a website straight onto the phone's sdcard. Any help is appreciated. Thanks!
[Edit]: I've found http://developer.android.com/reference/android/webkit/DownloadListener.html it seems right but I'm still a beginner and not sure how to apply the code / modify it and where to place it.

Networking is a big series of tests. Just about everything needs to be within a try/catch block, and you need to think of and test every possible contingency. Without doing that, you WILL get crashes and ugliness.
It is not the simplest thing for a newb to implement.
The SECOND thing you need to note is that WEBKIT is not what you want to mess with for *pure downloads*. If you just want to pull a file and do something manual with it, you do NOT want to be messing with an html rendering engine (that's what webkit is...).
Third, network requests should be done in a SEPARATE THREAD from the UI, otherwise it will result in a terrible user experience, ANR's, and general appearance of FREEZUPS.
You can try some of this:
Code:
public class HTTPGetData {
private byte[] data;
public HTTPGetData(){
}
public byte[] toByteArray(){
return data;
}
public void getViaHttpConnection(String url) throws IOException{
HttpClient httpClient = new DefaultHttpClient();
Log.d("***HTTPGetData",url);
HttpGet request = new HttpGet(url);
request.addHeader("Accept-Encoding", "gzip");
HttpResponse response;
try {
response = httpClient.execute(request);
boolean gzip = false;
if (response.containsHeader("Content-Encoding")){
Header[] headers = response.getHeaders("Content-Encoding");
for (int i=0; i<headers.length; i++){
if (headers[i].getValue().compareToIgnoreCase("gzip")==0) gzip = true;
}
}
int status = response.getStatusLine().getStatusCode();
// we assume that the response body contains the error message
if (status != HttpStatus.SC_OK) {
ByteArrayOutputStream ostream = new ByteArrayOutputStream();
response.getEntity().writeTo(ostream);
Log.e("HTTP_CLIENT", ostream.toString());
throw new IOException("HTTP response code: " + status);
} else {
int len = (int)response.getEntity().getContentLength();
InputStream content;
if (gzip) content = new GZIPInputStream(response.getEntity().getContent());
else content = response.getEntity().getContent();
if (len>0 && !gzip){
byte[] theData = new byte[len];
int rec = 0;
int cread = 0;
boolean fail=false;
while (rec < len){
if ((cread=content.read(theData, rec, len-rec))==0){
Log.e("HTTP_CLIENT","Short");
fail=true;
break;
}
rec+=cread;
}
if (!fail) data=theData;
} else {
int ch;
ByteVector bv = new ByteVector(1000);
while ((ch = content.read()) != -1){
bv.add((byte)ch);
}
data = bv.toByteArray();
}
content.close(); // this will also close the connection
}
} catch (ClientProtocolException e) {
Log.e("HTTP_CLIENT","ClientProtocolException");
throw new IOException("ClientProtocolException caught in HTTPGetData.getViaHttpConnection(String url)");
} catch (IOException e) {
Log.e("HTTP_CLIENT","IOException");
throw new IOException("IOException caught in HTTPGetData.getViaHttpConnection(String url)");
}
}
}
What you can do with that is something like this;
try{
HTTPGetData hgd = new HTTPGetData();
hgd.getViaHttpConnection("http://someurl");
//open file and dump in hgd.toByteArray();
catch(IOException e){
//do something with e
}
... and of course, put that in some new thread and while its running, make something spin to give the user the impression of progress.

Thanks lb. I don't really understand perfectly but I will look up the stuff I do not understand. Thanks for the help

Related

TwoLineListItem with icon

Hello!
I would like to ask you for help. I do not know how to create an custom adapter for TwoLineListItem with icon. I know how to set text using ListArray with HashMap. But how to add image (as @android:id/icon)?
Code:
String[][] ss = new String[][]{
{"string 1", "string 2"}
{"string 3", "string 4"}
{"string 5", "string 6"}};
List<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
for(int i=0; i<ss.length;i++) {
HashMap<String,String> item = new HashMap<String,String>();
item.put("text1", ss[i][0]);
item.put("text2", ss[i][1]);
list.add(item);
}
ListAdapter adapter = new SimpleAdapter(this,
list,
R.layout.list_position_layout,
new String[] {"text1","text2"},
new int[] {android.R.id.text1, android.R.id.text2 });
setListAdapter(adapter);
I suppose that solution is very easy... But I do not know how to do it.

[Q] hooking RecentLocationApps.getAppList()

I am trying to hook this method, I want to filter out the "Google Play services" from there...(is under settings app)
Code:
/**
* Fills a list of applications which queried location recently within
* specified time.
*/
public List<Preference> getAppList() {
// Retrieve a location usage list from AppOps
AppOpsManager aoManager =
(AppOpsManager) mActivity.getSystemService(Context.APP_OPS_SERVICE);
List<AppOpsManager.PackageOps> appOps = aoManager.getPackagesForOps(
new int[] {
AppOpsManager.OP_MONITOR_LOCATION,
AppOpsManager.OP_MONITOR_HIGH_POWER_LOCATION,
});
// Process the AppOps list and generate a preference list.
ArrayList<Preference> prefs = new ArrayList<Preference>();
long now = System.currentTimeMillis();
for (AppOpsManager.PackageOps ops : appOps) {
// Don't show the Android System in the list - it's not actionable for the user.
// Also don't show apps belonging to background users.
int uid = ops.getUid();
boolean isAndroidOs = (uid == Process.SYSTEM_UID)
&& ANDROID_SYSTEM_PACKAGE_NAME.equals(ops.getPackageName());
if (!isAndroidOs && ActivityManager.getCurrentUser() == UserHandle.getUserId(uid)) {
Preference pref = getPreferenceFromOps(now, ops);
if (pref != null) {
prefs.add(pref);
}
}
}
return prefs;
}
I can't hook this method, I'v tried something like :
Code:
if (lpparam.packageName.equals("com.android.settings")) {
findAndHookMethod("com.android.settings.location.LocationSettings", lpparam.classLoader, "getAppList", new XC_MethodHook() {
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
XposedBridge.log("Called");
}
what is the best approach to achieve this?
devtrop said:
I can't hook this method
Click to expand...
Click to collapse
Why not? Are there any errors in the Xposed log?
If not, I'd make sure the package name is correct and that the method is actually called when you expect it to be.
Code:
09-29 11:06:53.600 5277 5277 I Xposed : java.lang.NoSuchMethodError: com.android.settings.location.RecentLocationApps#getAppList(java.util.List)#exact
running on Samsumg Note 3.
devtrop said:
Code:
09-29 11:06:53.600 5277 5277 I Xposed : java.lang.NoSuchMethodError: com.android.settings.location.RecentLocationApps#getAppList(java.util.List)#exact
running on Samsumg Note 3.
Click to expand...
Click to collapse
That error doesn't correspond to the code you've posted in the first post. Post the modified code and the error.
Purely guessing, though: Samsung modified the code you're trying to hook. You're hooking the methods you're seeing in the AOSP code, but that's not the case on your device.
You are correct, sorry. I'm trying a lot of different stuff.
this is the code:
Code:
try
{
findAndHookMethod("com.android.settings.location.RecentLocationApps", lpparam.classLoader,
"getAppList", List.class, new XC_MethodHook() {
@SuppressWarnings("unchecked")
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable
{
XposedBridge.log("RecentLocationApps.getAppList()");
}
});
}
catch(Throwable t)
{
XposedBridge.log(t);
}
the throwable is :
Code:
09-29 11:56:08.559 5282 5282 I Xposed : java.lang.NoSuchMethodError: com.android.settings.location.RecentLocationApps#getAppList(java.util.List)#exact
if tried to do that for every package, not just com.android.settings or com.android.settings.location and it doesn't seem to work.
do you know what's the correct package? do I have to start dedexing Samsung's packages to get the answer?
devtrop said:
do you know what's the correct package?
Click to expand...
Click to collapse
com.android.settings should be the correct package, if I'm not mistaken.
devtrop said:
do I have to start dedexing Samsung's packages to get the answer?
Click to expand...
Click to collapse
That'd be the best thing to do as it looks like Samsung has changed some things.

[Q] when i use XPrivace.XPackageManager in my own module, error occurred, help me

[Q] when i use XPrivace.XPackageManager in my own module, error occurred, help me, urgent, thanks!
In the XPackageManager.java,
protected void after(XParam param) throws Throwable {
....
case Srv_getInstalledApplications:
if (param.getResult() != null)
if (isRestricted(param)) {
Method mGetList = param.getResult().getClass().getDeclaredMethod("ge tList");
List<ApplicationInfo> listAppInfo = (List<ApplicationInfo>) mGetList.invoke(param.getResult());
Constructor<?> constructor = param.getResult().getClass().getConstructor(List.c lass);
param.setResult(constructor.newInstance(filterAppl icationInfo(listAppInfo)));
}
break;
there throw exceptions: java.lang.NoSuchMethodException:getList[]
i log the class name use param.getResult().getClass().toString() the value is : class android.content.pm.ParceledListSlice,
but i can't import it use: import android.content.pm.ParceledListSlice;
how can i make the program run correct? thanks!
is there anybody can help me on it, thanks!

Code, to select an image from gallery? (Newbie)

Hello world,
Question: What's the code line(S) to select an image from gallery? Thank you in advance.
Code:
private void openPictureChooser() {
PackageManager manager = getPackageManager();
String memoryState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(memoryState)) {
Intent mIntent = new Intent(Intent.ACTION_PICK);
mIntent.setType("image/*");
List list = manager.queryIntentActivities(mIntent, PackageManager.MATCH_DEFAULT_ONLY);
if (!list.isEmpty()) {
startActivityForResult(mIntent, REQUEST_CODE);
}
} else {
Toast.makeText(this, getString(R.string.your_message), Toast.LENGTH_LONG).show();
}
}

Json body with retrofit issues with format

As simple as this json looks I cannot get it formatted correctly to post in body.
Code:
{
"requests": [
{
"action": "reject",
"justification": "admin reason",
"requestId": "23423423refsdsdgdg"
}
],
"justification": "admin reason"
}
Here is what I have so far in Android studio using retrofit2
Code:
Gson gson = new GsonBuilder()
.setLenient()
.create();
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl("https://myurl.com/")
.addConverterFactory(GsonConverterFactory.create(gson));
JsonObject jsonObject = new JsonObject();
JsonObject jsonObjectN = new JsonObject();
jsonObject.addProperty("action", action);
jsonObject.addProperty("request_id", request_id);
jsonObject.addProperty("justification", "blablabla");
jsonObjectN.add("requests", jsonObject);
jsonObjectN.addProperty("justification", justification);
Retrofit retrofit = builder.build();
Client client = retrofit.create(Client.class);
Call<PostRequest> user = client.postRequests(
jsonObjectN
);
in client class I have
Code:
@Headers("Content-Type: application/json")
@POST("/requests")
Call<PostRequest> postRequests(@Body JsonObject body
);
So the request is like this
Code:
Request{method=POST, url=https://myurl.com/requests, tags={class retrofit2.Invocation=com.login.Client.postRequests() [{"requests":{"action":"reject","request_id":"23423423refsdsdgdg","justification":"blablabla"},"justification":"Action done by Admin"}]}}
Very close but I cant quite figure out how to make it in the exact array/json format as its expecting??
Hopefully someone knows Android and jsonObject well enough to help.

Categories

Resources