[Q] Canvas to Bitmap And Back Again - Android - General Questions and Answers

Hey guys,
I'm making an App that needs to be able to draw new graphics on top of the last set.
This is my current onDraw() method -
PHP:
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.WHITE);
//do some stuff here - this is all working ok
canvas.drawLine(p1.x, p1.y, p2.x, p2.y, linePaint);
}
Basically, I need to draw the new graphics as a layer on top of the last, so what I'm looking for is a way to carry the image of the last canvas to the current. There is a LOT of lines drawn every frame so simple drawing them all again isn't an option.
I have tried to figure it out myself using the canvas.setBitmap() method but it acts very funny.
This is what I put at the start of the onDraw() method, in my head it makes sense but it doesn't seem to do anything
PHP:
if(bitmap != null) {
canvas.drawBitmap(bitmap, 0, 0, paint);
canvas.setBitmap(bitmap);
}
Any help appreciated
P.S if it's needed, the the class extends SurfaceView and implements SurfaceHolder.Callback

Related

[APP] Shark for Root + SharkReader

There were AndroShark, tool for capturing traffic on Android. But there were no newer releases and it seems that original developer dropped project. I liked this tool and used it a lot. But it was set to expire... So there was no simple capture tools available... http://forum.xda-developers.com/showthread.php?t=675206 is home of AndroShark.
So I made Shark for Root, alternative for AndroShark. Some people asked for possibility to see packets on phone, and for that purpose SharkReader has created (first, "quick and dirty" release).
Shark for Root
With tcpdump http://swapper.n3o.lv/lv.n3o.shark_1.0.2.apk
Native http://swapper.n3o.lv/lv.n3o.sharknative_1.0.2.apk
SharkReader - unstable...
(note - run Shark Updater to get traffic analysator)
http://swapper.n3o.lv/lv.n3o.sharkreader_0.1.6.apk
Older versions http://swapper.n3o.lv/
EPIC
Thank you!
If you press stop, it doesn't truly stop. tcpdump seems like it is still going in the background. The file will continue getting larger and larger even though it has been told to stop capturing.
Running CyanogenMod 6 RC1.
Thank you.
Far as I can tell it's working good, Thanks for the reader, helps a lot, I can see this program becoming a portable wireshark app for android, keep up the great work and thank you.
Awesome start!! Thanks!
Sent from my Nexus One using XDA App
does this program work with rooted x10? i clcik on start and all i see is "not found".. my parameters are empty is this also correct ?
thanks
cool app! thanks!
duffy1807 said:
does this program work with rooted x10? i clcik on start and all i see is "not found".. my parameters are empty is this also correct ?
thanks
Click to expand...
Click to collapse
Default parameters are -vv -s 0
Can You send me more information about Your error?
Could someone tell about using different parameters or point me to some website where i could study these?(now i got the defaults)
And when i open Shark reader i see many "RAW Packet" but i cant get any information from them, just "Packet #number".
.pcap files are fine when i open them with Wireshark.
At the bottom i see this: -NULL , what else i can use here and how it effects?
Interesting app, keep up the good work!
A changelog would be nice.
I also can not run Shark on my X10. I get the error 'reloc_library [1215]: cannot locate _aeabi_fdiv CANNOT LINK EXECUTABLE
Sent from my X10a using XDA App
acips said:
Could someone tell about using different parameters or point me to some website where i could study these?(now i got the defaults)
And when i open Shark reader i see many "RAW Packet" but i cant get any information from them, just "Packet #number".
.pcap files are fine when i open them with Wireshark.
At the bottom i see this: -NULL , what else i can use here and how it effects?
Interesting app, keep up the good work!
Click to expand...
Click to collapse
Hello!
For Shark for Root parameters look at some examples/manuals about tcpdump. F.e. http://www.cs.ucr.edu/~marios/ethereal-tcpdump.pdf
Shark reader marks packets as RAW if it does not recognize it (currently it means it's not tcp/udp packet).
For filters you can use any tag and any tag with - sign. Tags are those in first column. Traffic is tagged by content (signature) and port. Signatures and ports you may update with Shark Updater (included in Shark Reader), but I have too little time to manage all those resources. I'll make this system public for tags submission/port submission, so interested users will be able to add necessary tags.
So, if you want to see only non zero bytes packets with http content, you may use this setting:
Code:
[ ] all [o] none | http -NULL |
Filters are processed in order. So http shows all http packets and -NULL hides those with nulls. First option works as global filter (show all or show none).
Warning! Not all traffic is tagged, so if you miss something, it could mean some tags are incorrectly assigned or skipped.
Hope it helps.
mcampbellsmith said:
I also can not run Shark on my X10. I get the error 'reloc_library [1215]: cannot locate _aeabi_fdiv CANNOT LINK EXECUTABLE
Sent from my X10a using XDA App
Click to expand...
Click to collapse
Which OS version your X10a have? I saw that there are some problems with reloc_library in Android 1.5.
It's Android 1.6 only on the X10
Sent from my X10a using XDA App
i made an spanish thread on my android site, lets see how it works on milestone
thanks!!!!
Can some please explain in lamon terms what this does?
hy there =) can you make a capture filter to msn conversations ? it would be nice =)
I use an app similar called 3G Watchdog (it's free).
Let's you know how much data you've used with a widget too!
slow4g63 said:
I use an app similar called 3G Watchdog (it's free).
Let's you know how much data you've used with a widget too!
Click to expand...
Click to collapse
LOL this is nothing like that my friend.. nothing at all
ex87,
Awesome work bro, life got too busy for me to work more on AndroShark, I really didn't drop it on purpose. But with a busy life, and me still really new at java, it was just too much. I am really glad you picked up the idea and ran with it.
Do you have any plans to opensource it at all (no worries if you dont)? I would like to be a contributor if you do decide to open source it.
I really doubt this is of any use. It was the second java app I ever worked on, and was really just a front end. Below is androshark source code. Like I said, this was my second attempt at writing an app, so please don't laugh If I were to do it today, I would completely change how it worked. /res/raw/sharktap was just tcpdump.
Code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
/**
* ToDo:
* Check for root
* Check for first run
* Install Binaries on first run
* Check for sdcard mount
* Display file stats
* Name pcap based on file name
* Insert License
* kill sharktap on die
*
* @author jcase
*
*/
public class androshark extends Activity implements /*RadioGroup.OnCheckedChangeListener,*/ Button.OnClickListener {
Button btnStart, btnStop;
RadioButton radAll, rad3g, radWifi; //http://java.dzone.com/articles/google-android-tutorial?page=0,4
RadioGroup grpRadio;
TextView txtStatus, txtFilename, txtFilesize;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnStart = (Button)this.findViewById(R.id.btnStart);
btnStart.setOnClickListener(this);
btnStop = (Button)this.findViewById(R.id.btnStop);
btnStop.setOnClickListener(this);
long epoch = System.currentTimeMillis()/1000;
boolean exists = (new File("/data/data/net.andirc.androshark/files/sharktap")).exists();
if (exists) {
} else {
Process myproc = null;
try
{
try{
String strDirectoy ="/data/data/net.andirc.androshark/files";
new File(strDirectoy).mkdir();
}
finally {}
InputStream ins = getResources().openRawResource(R.raw.sharktap);
int size = ins.available();
byte[] buffer = new byte[size];
ins.read(buffer);
ins.close();
FileOutputStream fos = new FileOutputStream("/data/data/net.andirc.androshark/files/sharktap");
fos.write(buffer);
fos.close();
}
catch (Exception ex)
{
Log.e("yourTag", "Oops something happened: " + ex.getMessage(), ex);
}
finally {}
}
boolean exists2 = (new File("/sdcard/androshark/")).exists();
if (exists2) {
} else {
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED)) {
Process myproc = null;
try
{
myproc = Runtime.getRuntime().exec(new String[] {"su", "-c","chmod 755 /data/data/net.andirc.androshark/files/sharktap && mkdir /sdcard/androshark/"});
new AlertDialog.Builder(this)
.setMessage("This is a beta trial version of androshark and will expire on May 15th 2010. This app can potentially consume a lot of sdcard space, depending on how long you allow it to sniff traffic and how much bandwidth you are using.")
.setPositiveButton("OK", null)
.show();
}
catch (Exception ex)
{
Log.e("yourTag", "Oops something happened: " + ex.getMessage(), ex);
}
finally {}
} else {
new AlertDialog.Builder(this)
.setMessage("Error sd01: sdCard not found!")
.setPositiveButton("OK", null)
.show();
}
}
if (epoch >= 1273990849) { // May 15th 2010 1273990849
System.exit(0);
}
}
public void onClick(View v) {
Process myproc = null;
try
{
if (v == btnStart) {
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED)) {
myproc = Runtime.getRuntime().exec(new String[] {"su", "-c", "kill $(ps | grep sharktap | tr -s ' ' | cut -d ' ' -f2) && /data/data/net.andirc.androshark/files/sharktap -vv -s 0 -w /sdcard/androshark/dump.pcap"});
TextView txtStatus =
(TextView) this.findViewById(R.id.txtStatus);
txtStatus.setText("Status: Running");
TextView txtFilename =
(TextView) this.findViewById(R.id.txtFilename);
txtFilename.setText("Filename: /sdcard/androshark/dump.pcap");
/* int running = 1;
do {
File file = new File("/sdcard/androshark/dump.pcap");
long length = file.length();
TextView txtFilesize =
(TextView) this.findViewById(R.id.txtFilesize);
txtFilesize.setText("File Size: " + length/1024 + "KB");
} while (running <= 1); */
} else {
new AlertDialog.Builder(this)
.setMessage("Error sd02: sdCard not found!")
.setPositiveButton("OK", null)
.show();
}
} else if (v == btnStop) {
myproc = Runtime.getRuntime().exec(new String[] {"su", "-c", "kill $(ps | grep sharktap | tr -s ' ' | cut -d ' ' -f2)"});
myproc.waitFor();
File file = new File("/sdcard/androshark/dump.pcap");
long length = file.length();
TextView txtStatus =
(TextView) this.findViewById(R.id.txtStatus);
txtStatus.setText("Status: Stopped");
TextView txtFilesize =
(TextView) this.findViewById(R.id.txtFilesize);
txtFilesize.setText("File Size: " + length/1024 + "KB");
}
}
catch (Exception ex)
{
Log.e("yourTag", "Oops something happened: " + ex.getMessage(), ex);
}
finally {}
}
}
racemepls said:
Can some please explain in lamon terms what this does?
Click to expand...
Click to collapse
shdwknt said:
LOL this is nothing like that my friend.. nothing at all
Click to expand...
Click to collapse
Apparently you know, and still haven't helped those of us who have no idea what this app is for!

Random letter generator (Right selection?)

Hey guys, is there an app that can generate a random LETTER? I don't know if this is the right selection but... here is an example for what I'm looking for
# i can't post links... on google, search for "random letter generator" and click the first link
Thx.
Sent from my Desire HD using Tapatalk
not availaible at this moment bro! sorry!
Someone else that has an idea?
Sent from my Desire HD using Tapatalk
It's not difficult in C# under Windows Mobile .NET as the image below can testify, but it is no good on your Desire HD.
I'm a WinMo developer, not Android, but if anyone wants to port this code into Java under Android, here's the code to do it. Shouldn't be too difficult.
Code:
using System;
using System.Windows.Forms;
namespace RndLetters
{
public partial class Form1 : Form
{
string tmp = new string(' ', 50);
Random rnd = new Random();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int i, j;
listBox1.Items.Clear();
if (textBox1.Text.Length > 0)
{
for (j = 0; j < numericUpDown2.Value; j++)
{
tmp = "";
for (i = 0; i < numericUpDown1.Value; i++)
tmp+=textBox1.Text[rnd.Next(textBox1.Text.Length)];
listBox1.Items.Add(tmp);
}
}
}
}
}
P.S. RndLetters.exe is included in the zip file. It is compiled for .NET CF 2.0, but should run on all later versions.
Awesome!
# lol it's possible to create a random NUMBER generator but it isn't possible to make a random LETTER generator. Lol what is the diffrence?
Sent from my Desire HD using Tapatalk
The above code just picks a random character from the given string and adds it to the current one until it reaches the required length. It could not give a damn what is in the string.
Give it the digits 0-9 and it will churn out random numbers :-
I do know how to program a generator in visual basic, but i have no clue how to translate it to android or whatever the program language is called
Sent from my Desire HD using Tapatalk
xOMG said:
Awesome!
# lol it's possible to create a random NUMBER generator but it isn't possible to make a random LETTER generator. Lol what is the diffrence?
Sent from my Desire HD using Tapatalk
Click to expand...
Click to collapse
Simply assign each number a letter. Same difference.
Android uses Java which is not a million miles from C#, although there are some subtle differences.
This is the Java code for a console application that takes length, repeat and string as command line arguments, in that order. Note that there is zero error handling; get the parameters wrong and it will just throw an exception.
Code:
import java.util.Random;
public class Test
{
public static void main(String []args)
{
int i,j;
Random rnd = new Random();
for(j=0;j<Integer.parseInt(args[1]);j++)
{
for(i=0;i<Integer.parseInt(args[0]);i++)
{
System.out.print(args[2].charAt(rnd.nextInt(args[2].length())));
}
System.out.println();
}
}
}
As per the following:
Code:
C:\PROGRA~1\Java\JDK16~1.0_2\bin>java Test 20 5 abcdefghijklmnopqrstuvwxyz
zfwnnkheqmeyzkcvrdhj
ybuejlavzixstmmqxkxp
aylyjxheonkxhxjtayxg
iefcxuurhvgclpsgisvb
dfncfxueajbvhscderhr
Somehow you will have to fit some code similar to the above into a "Hello World" Android java program, and wire it up to Android textboxes, buttons, labels, etc. and their associated events. This is where my Android development knowledge ends, (at present), so it is over to the Android Development gurus.

When is CM7 coming out?

Well, now that I have your attention, my REAL question is this: Is there a way to make apps like the Amazon marketplace think they're on wifi so I don't get that stupid "you can't download this because it's too big for a cellular network"?
***** please, I pay for unlimited data and I plan to use it.
Sent from my Droid Charge running Infinity Beta
HAHAHA I like your tactics for getting attention.
A while back I made a remark that the only way to get peoples attention in these forums is to ask if CM7 is coming out in the title and then ask the real question in the body.
Well played
Also no, there's no way to trick Amazon
I've actually been working on figuring out a way to do this.
Any app that tries to figure out how it's connected queries the same class in the system called NetworkInfo.class.
There are two methods within NetworkInfo.class that report the network type: getType() and getTypeName(). getType() returns a machine-readable answer, while getTypeName() is human-readable.
Code:
public int getType() {
return mNetworkType;
}
Code:
public String getTypeName() {
switch (mNetworkType) {
case ConnectivityManager.TYPE_WIFI:
return "WIFI";
case ConnectivityManager.TYPE_MOBILE:
return "MOBILE";
default:
return "<invalid>";
}
}
I haven't had the resources (primarily time) to dig that far into things, but if we could figure out a way to inject something between Amazon and the getType() or getTypeName() calls, we could report to it that we're on WiFi regardless of how we're actually connected.
AlexDeGruven said:
I've actually been working on figuring out a way to do this.
Any app that tries to figure out how it's connected queries the same class in the system called NetworkInfo.class.
There are two methods within NetworkInfo.class that report the network type: getType() and getTypeName(). getType() returns a machine-readable answer, while getTypeName() is human-readable.
Code:
public int getType() {
return mNetworkType;
}
Code:
public String getTypeName() {
switch (mNetworkType) {
case ConnectivityManager.TYPE_WIFI:
return "WIFI";
case ConnectivityManager.TYPE_MOBILE:
return "MOBILE";
default:
return "";
}
}
I haven't had the resources (primarily time) to dig that far into things, but if we could figure out a way to inject something between Amazon and the getType() or getTypeName() calls, we could report to it that we're on WiFi regardless of how we're actually connected.
Click to expand...
Click to collapse
Wow, Computer Science II is actually helping me be able to read this. So, what type of object is mNetworkType and where is it defined? We could get it to just return that its on wifi all the time. Also, do you know what Amazon calls? GetType or GetTypeName?
Sent from my Droid Charge running Infinity Beta
Lol. Nicely done with the thread title.
Sent from my mobile office.
AlexDeGruven said:
I've actually been working on figuring out a way to do this.
Any app that tries to figure out how it's connected queries the same class in the system called NetworkInfo.class.
There are two methods within NetworkInfo.class that report the network type: getType() and getTypeName(). getType() returns a machine-readable answer, while getTypeName() is human-readable.
Code:
public int getType() {
return mNetworkType;
}
Code:
public String getTypeName() {
switch (mNetworkType) {
case ConnectivityManager.TYPE_WIFI:
return "WIFI";
case ConnectivityManager.TYPE_MOBILE:
return "MOBILE";
default:
return "<invalid>";
}
}
I haven't had the resources (primarily time) to dig that far into things, but if we could figure out a way to inject something between Amazon and the getType() or getTypeName() calls, we could report to it that we're on WiFi regardless of how we're actually connected.
Click to expand...
Click to collapse
kvswim said:
Wow, Computer Science II is actually helping me be able to read this. So, what type of object is mNetworkType and where is it defined? We could get it to just return that its on wifi all the time. Also, do you know what Amazon calls? GetType or GetTypeName?
Sent from my Droid Charge running Infinity Beta
Click to expand...
Click to collapse
Interesting stuff. There's an iPhone app for jailbroken phones that performs this function on an app-by-app basis. With this code identified, something similar might be possible on Android. I haven't done any Android dev yet, so I don't know how much help I might be. Is there a way to easily (and cheaply) intercept method calls on Android? If so, there might be a way to intercept the getType and getTypeName calls and then modify them on a case-by-case basis so that the call can be diverted to a different function. I'm talking completely theoretical here...I don't know what is offered by the Android SDK.
shrike1978 said:
Interesting stuff. There's an iPhone app for jailbroken phones that performs this function on an app-by-app basis. With this code identified, something similar might be possible on Android. I haven't done any Android dev yet, so I don't know how much help I might be. Is there a way to easily (and cheaply) intercept method calls on Android? If so, there might be a way to intercept the getType and getTypeName calls and then modify them on a case-by-case basis so that the call can be diverted to a different function. I'm talking completely theoretical here...I don't know what is offered by the Android SDK.
Click to expand...
Click to collapse
That was exactly where my investigation has hit the wall at the moment (and then I got busy finishing my basement).
There are a couple of ways to do it, really. Someone could modify the appstore apk to wrap any calls to getType() and getTypeName(), but that would only be on that particular apk. IIRC, the market does it for large apk downloads as well.
Other apps also look at what your network type is.
I'd love to have something that allows me to toggle what the applications see, regardless of the actual state (I'm thinking of things like Verizon's Skype, etc).
The problem with all of this is that NetworkInfo.class is deep in the core OS, so intercepting any calls to it's methods might be rather difficult at best.
Edit: Also - Can we change the thread title now that we know what it's really all about?
ROTFLMFAO! Awesome thread title!
Sent from my SCH-I510 using xda premium
rofl you got me!!! hahahaha... and to answer your question I don't think there is but it'd be nice to know for sure
blazing through on my 4G Droid Charge
In the Amazon Appstore apk, com.amazon.mas.client.framework.net contains a class called NetworkStateManager whose source is:
Code:
package com.amazon.mas.client.framework.net;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class NetworkStateManager
{
private static final int DELAY_DROP_DETECTION = 5000;
private static final String TAG = "NetworkStateManager";
private static final Map<String, WifiManager.WifiLock> wifiLocks = new ConcurrentHashMap();
private final ConnectivityManager connectivityManager;
private final WeakReference<Context> context;
private final Handler delayHandler;
private final List<NetworkStateListener> listeners = new ArrayList();
private boolean networkDropDetected = false;
private NetworkStateReceiver receiver = null;
private boolean wasConnected = false;
private final WifiManager wifiManager;
public NetworkStateManager(Context paramContext)
{
this.context = new WeakReference(paramContext);
this.wifiManager = ((WifiManager)paramContext.getSystemService("wifi"));
this.connectivityManager = ((ConnectivityManager)paramContext.getSystemService("connectivity"));
this.delayHandler = new NetworkStateHandler(null);
if (isNetworkConnected());
for (boolean bool = false; ; bool = true)
{
this.networkDropDetected = bool;
return;
}
}
private WifiManager.WifiLock getWifiLock(String paramString)
{
if (wifiLocks.containsKey(paramString));
for (WifiManager.WifiLock localWifiLock = (WifiManager.WifiLock)wifiLocks.get(paramString); ; localWifiLock = this.wifiManager.createWifiLock(paramString))
return localWifiLock;
}
public boolean acquireWifiLock(String paramString)
{
WifiManager.WifiLock localWifiLock = getWifiLock(paramString);
if (localWifiLock.isHeld())
Log.w("NetworkStateManager", "Wifi lock identified by " + paramString + " already acquired");
for (int i = 0; ; i = 1)
{
return i;
localWifiLock.acquire();
wifiLocks.put(paramString, localWifiLock);
}
}
public void addListener(NetworkStateListener paramNetworkStateListener)
{
if (!this.listeners.contains(paramNetworkStateListener))
this.listeners.add(paramNetworkStateListener);
}
public void clearListeners()
{
this.listeners.clear();
}
public boolean isNetworkConnected()
{
NetworkInfo localNetworkInfo = this.connectivityManager.getActiveNetworkInfo();
if ((localNetworkInfo == null) || (!localNetworkInfo.isConnected()));
for (int i = 0; ; i = 1)
return i;
}
public boolean isNetworkWifi()
{
return this.connectivityManager.getNetworkInfo(1).isConnected();
}
public boolean isWifiLockAcquired(String paramString)
{
WifiManager.WifiLock localWifiLock = getWifiLock(paramString);
if ((localWifiLock != null) && (localWifiLock.isHeld()));
for (int i = 1; ; i = 0)
return i;
}
public void releaseWifiLock(String paramString)
{
WifiManager.WifiLock localWifiLock = getWifiLock(paramString);
if (localWifiLock.isHeld())
{
localWifiLock.release();
if (wifiLocks.containsKey(paramString))
wifiLocks.remove(paramString);
}
while (true)
{
return;
Log.w("NetworkStateManager", "Wifi lock identified by " + paramString + " is not acquired");
}
}
public void removeListener(NetworkStateListener paramNetworkStateListener)
{
this.listeners.remove(paramNetworkStateListener);
}
public void startListening()
{
Context localContext = (Context)this.context.get();
if (this.receiver != null)
Log.w("NetworkStateManager", "Already listening, duplicate call to NetworkStateManager#startListening");
while (true)
{
return;
if (localContext == null)
{
Log.w("NetworkStateManager", "Call to NetworkStateManager#startListening on null context");
continue;
}
this.wasConnected = isNetworkConnected();
IntentFilter localIntentFilter = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
this.receiver = new NetworkStateReceiver(null);
localContext.registerReceiver(this.receiver, localIntentFilter);
}
}
public void stopListening()
{
Context localContext = (Context)this.context.get();
if (this.receiver == null)
Log.w("NetworkStateManager", "Not listening, invalid call to NetworkStateManager#stopListening");
while (true)
{
return;
if (localContext == null)
{
Log.w("NetworkStateManager", "Call to NetworkStateManager#stopListening on null context");
continue;
}
localContext.unregisterReceiver(this.receiver);
this.receiver = null;
this.delayHandler.removeMessages(65536);
}
}
private class NetworkStateHandler extends Handler
{
public static final int MSG_NETWORK_DROP = 65536;
private NetworkStateHandler()
{
}
public void handleMessage(Message paramMessage)
{
switch (paramMessage.what)
{
default:
super.handleMessage(paramMessage);
case 65536:
}
while (true)
{
return;
NetworkStateManager.this.wasConnected = false;
NetworkStateManager.this.networkDropDetected = true;
Iterator localIterator = NetworkStateManager.this.listeners.iterator();
while (localIterator.hasNext())
((NetworkStateManager.NetworkStateListener)localIterator.next()).onConnectivityLost();
}
}
}
public static abstract interface NetworkStateListener
{
public abstract void onConnectivityLost();
public abstract void onConnectivityRestored();
}
private class NetworkStateReceiver extends BroadcastReceiver
{
private NetworkStateReceiver()
{
}
public void onReceive(Context paramContext, Intent paramIntent)
{
if ((paramContext == null) || (paramIntent == null) || (!"android.net.conn.CONNECTIVITY_CHANGE".equals(paramIntent.getAction())));
while (true)
{
return;
if (NetworkStateManager.this.isNetworkConnected());
for (int i = 0; ; i = 1)
{
boolean bool = paramIntent.getBooleanExtra("isFailover", false);
if ((i == 0) || (bool) || (!NetworkStateManager.this.wasConnected))
break label99;
Message localMessage = NetworkStateManager.this.delayHandler.obtainMessage(65536);
NetworkStateManager.this.delayHandler.sendMessageDelayed(localMessage, 5000L);
break;
}
label99: if (i != 0)
continue;
if (NetworkStateManager.this.delayHandler.hasMessages(65536))
NetworkStateManager.this.delayHandler.removeMessages(65536);
if (!NetworkStateManager.this.networkDropDetected)
continue;
NetworkStateManager.this.wasConnected = true;
Iterator localIterator = NetworkStateManager.this.listeners.iterator();
while (localIterator.hasNext())
((NetworkStateManager.NetworkStateListener)localIterator.next()).onConnectivityRestored();
}
}
}
}
I'm guessing that making isNetworkWifi() return true would allow for downloads of large files over the cell network. I might repack the APK and post it here if I find the time.
All right, I decompiled the dex file into smali class files, made the change, recompiled, and produced an APK that does not have the wifi restriction, but I'm having problems with signing. I ran a signing tool on the APK, but even after that my phone still fails to install the app (I do have the previous version of the app uninstalled). Has anyone else had experience with this?
substanceD said:
All right, I decompiled the dex file into smali class files, made the change, recompiled, and produced an APK that does not have the wifi restriction, but I'm having problems with signing. I ran a signing tool on the APK, but even after that my phone still fails to install the app (I do have the previous version of the app uninstalled). Has anyone else had experience with this?
Click to expand...
Click to collapse
Care to post it?
Sent from my Droid Charge running Infinity Beta
kvswim said:
Care to post it?
Sent from my Droid Charge running Infinity Beta
Click to expand...
Click to collapse
Yeah, sure. (For anyone else attempting to download this, it will not install in its current form).
Anyone have any luck with the signing?
AlexDeGruven said:
Anyone have any luck with the signing?
Click to expand...
Click to collapse
I'm having troubles too. Is there any way to bypass the sign check? I assume its similar to a CRC or MD5 check.
EDIT: http://developer.android.com/guide/publishing/app-signing.html
What if you saved & signed as a different app name?
Sent from my Droid Charge running Infinity Beta
Bumping
Sent from my Droid Charge running Infinity Beta
Just had an idea. What if we packed it into a ROM as a system APK?
Sent from my Droid Charge running Infinity Beta
Screw CM7. Why was CM8 skipped?! >:[
Sent from my SCH-I510 using xda premium
DirgeExtinction said:
Screw CM7. Why was CM8 skipped?! >:[
Sent from my SCH-I510 using xda premium
Click to expand...
Click to collapse
Great job reading the thread and making a relevant comment.
Aside from that: CM8 would be Honeycomb-based if it were to ever be made, which is unlikely, since it's the one version of Android that's closed-source. ICS will give rise to CM9
AlexDeGruven said:
Great job reading the thread and making a relevant comment.
Aside from that: CM8 would be Honeycomb-based if it were to ever be made, which is unlikely, since it's the one version of Android that's closed-source. ICS will give rise to CM9
Click to expand...
Click to collapse
Why, thank you.
I was bored and just posted that. I knew this thread was about the Amazon appstore(had read some posts from the first page a few days ago).
Sent from my SCH-I510 using xda premium

[Q] WP7 facebook application, posting blank status updates only

Hi ive written a simple application for windows phone 7 that posts a status update to the users wall. This is all working correctly except for the fact that when the status update is done it is always empty. I am trying to make it so that the user can enter what they would like to say in a text box, but obviously so far this isnt working and all that is being sent is an empty status update. I am connecting to the facebook api and the authentication all works correctly or the post would not be sent at all. Ive searched all over the web and havent found anyone with the same issue as of yet.
Here is the status update code that I am working on:
Code:
private void PostStatusUpdate(string status, Action<bool, Exception> callback)
{
var request = HttpWebRequest.Create("https://graph.facebook.com/me/feed");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.BeginGetRequestStream((reqResult) =>
{
using (var strm = request.EndGetRequestStream(reqResult))
using (var writer = new StreamWriter(strm))
{
writer.Write("access_token=" + _accessToken);
writer.Write("&message=" + HttpUtility.UrlEncode(status));
}
request.BeginGetResponse((result) =>
{
try
{
var response = request.EndGetResponse(result);
using (var rstrm = response.GetResponseStream())
{
var serializer = new DataContractJsonSerializer(typeof(FacebookPostResponse));
var postResponse = serializer.ReadObject(rstrm) as FacebookPostResponse;
callback(true, null);
}
}
catch (Exception ex)
{
callback(false, ex);
}
}, null);
}, null);
}
[DataContract]
public class FacebookPostResponse
{
[DataMember(Name = "id")]
public string Id
{
get;
set;
}
}
private void PostUpdate_Click(object sender, RoutedEventArgs e)
{
PostStatusUpdate(this.StatusText.Text, (success, ex) =>
{
this.Dispatcher.BeginInvoke(() =>
{
if (success && ex == null)
{
MessageBox.Show("Status updated");
NavigationService.Navigate(new Uri("/Views/MainPage.xaml", UriKind.Relative));
}
else
{
MessageBox.Show("Unable to update status");
}
});
});
}
Has anyone encountered this before / know any solution to this problem?
Any insights into this would be much appreciated
You are using the asyncronous method with no callback function
Looks like you should be using a callback function - See examples here
http://msdn.microsoft.com/en-us/lib...est.begingetrequeststream(v=vs.90).aspx#Y1760
http://msdn.microsoft.com/en-us/lib...brequest.begingetrequeststream(v=vs.100).aspx
Also, did the same code work at one point?
It could be as simple as not closing your connections. I ran into this in the Weather City Editor that I wrote for Windows Mobile.
When I added code to hit accuweathers site to look up the code, I had forgotten to close the connection. I would need to wait until the connection timed out before it would work again.
I think yours is differnt though, since it is updating blank.
But, you could just use GetRequestStream, which does not need the callback function, synce it is not asyncronous. See example code: http://msdn.microsoft.com/en-us/library/d4cek6cc.aspx
Thanks for the reply
Thanks for the reply, the code has never worked so far it has only posted blank facebook statuses, I will see if adding an asynchronous call back makes a difference.
Thanks

[GUIDE] Create “deathless” Android application: Protected from removal and stop

Author: Apriorit (@andruwik777, Driver Development Team)
Some types of applications require that the end users can not be able to remove or at least stop the application. For example, all types of Parental Controls, Data Leak Prevention, and applications with similar concepts should work on devices regardless of the user’s intentions. On the other hand, when trying to search proven solutions for implementing such applications, we cannot find some comprehensive answers in the Internet. This article describes one of the possible solutions.
Intro
Though, there are individual solutions for the "Disable force stop and uninstall button on Android" tasks, but in order to activate these buttons, you simply need to perform the user’s actions in reverse order.
As for the task of creation of an unkillable application, there are opinions that it cannot be supported by the concept of Android (1, 2, 3), because the basic idea of this OS is to give the user permission to work with his device as he wishes.
However, we are going to consider one of the ways to create an application that can be stopped or removed only by the user (Admin), who installed it.
The task
Appearance of the application
Task: Create the TryStopOrUninstallMe application.
After the application start and security policy acceptance, within a 10 seconds timeout, application displays the information that it successfully works (Toast with the “Ooops! Try to kill me ” text).
If you stop the service, it will be restarted no later than in 2 seconds (by timeout).
The ForceStop and Uninstall buttons are inactive in the application menu. When you try to activate these buttons by disabling DeviceAdministrator for the application, phone is locked. At the same time the previous user password is deleted and further calls can be made only after unlocking the phone by administrator, who knows the password.
Used technologies
Programming language: Java.
Used libraries and technologies: Android SDK.
Minimum supported version of Android: 2.2
Maximum supported version of Android: 5.0.2 (the newest one for today)
ROOT-permissions requirements on the device: not required
Testing: the application was tested on Nexus 5 with Android 5.0.1.
Pending issues
In order to keep this article short and because of the triviality of the problem, we do not consider:
1. Creation of start Activity, in which the administrator would set a master password. Instead, we have simply hardcoded it (e.g., "12345");
2. Application startup at system startup.
The general principles of the mechanism
The following approaches will be used to implement this idea:
1. Disabling the application forced stop and uninstall will be implemented using Device Administration API. Although it is designed for a little bit different purposes (some of which will be shown later), we’ll use it as a "deactivator" of the ForceStop and Uninstall buttons for our application (a side effect is actually what we need):
To uninstall an existing device admin application, users need to first unregister the application as an administrator.
2. There is no standard mechanism to disable the DeviceAdmin mode unlocking for user. However, we can sign up to receive event alerts on removing our application from the list of administered ones. And in this case we can:
1. Reset the current password for device locking (one of the DeviceAdmin API purposes);
2. Lock the phone (another great DeviceAdmin API feature).
3. Our application will use the service to run in the background. For the cases when user tries to stop our service (Settings -> Application -> RunningServices) we will implement auto-start using the AlarmManager system mechanism.
4. If user stop the service and have enough time to go to the application menu until the system restarts the service, then the application (not the service) stop button will be available for him.
After application is stopped, nothing can be restarted by itself. Thus, to deprive user of this chance, we will redirect him to his desktop and lock the device. While user is returning to the target Activity, system has enough time to restart the service (during my testing, it always takes 1-2 seconds).
Graphical representation
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Implementation of the mechanism
Activation of the mechanism for self-protection against the application stop and uninstall, and the service launch (MainActivity.java)
Code:
public class MainActivity extends Activity {
private static final int REQUEST_CODE = 0;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
// Initiate DevicePolicyManager.
DevicePolicyManager policyMgr = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
// Set DeviceAdminDemo Receiver for active the component with different option
ComponentName componentName = new ComponentName(this, DeviceAdminDemo.class);
if (!policyMgr.isAdminActive(componentName)) {
// try to become active
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, componentName);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
"Click on Activate button to protect your application from uninstalling!");
startActivity(intent);
}
} catch (Exception e) {
e.printStackTrace();
}
startService(new Intent(this, BackgroundService.class));
}
}
Everything that is done in the main (and only one) Activity is DeviceAdmin activation and service launch. It is expected that the device administrator activates the protection by pressing Activate.
Otherwise, the user can stop or remove the application in a standard way.
The service launch and its running (BackgroundService.java)
Code:
public class BackgroundService extends Service {
private static final int FIRST_RUN_TIMEOUT_MILISEC = 5 * 1000;
private static final int SERVICE_STARTER_INTERVAL_MILISEC = 1 * 1000;
private static final int SERVICE_TASK_TIMEOUT_SEC = 10;
private final int REQUEST_CODE = 1;
private AlarmManager serviceStarterAlarmManager = null;
private MyTask asyncTask = null;
@override
public IBinder onBind(Intent intent) {
return null;
}
@override
public void onCreate() {
super.onCreate();
// Start of timeout-autostarter for our service (watchdog)
startServiceStarter();
// Start performing service task
serviceTask();
Toast.makeText(this, "Service Started!", Toast.LENGTH_LONG).show();
}
private void StopPerformingServiceTask() {
asyncTask.cancel(true);
}
private void GoToDesktop() {
Intent homeIntent= new Intent(Intent.ACTION_MAIN);
homeIntent.addCategory(Intent.CATEGORY_HOME);
homeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(homeIntent);
}
private void LockTheScreen() {
ComponentName localComponentName = new ComponentName(this, DeviceAdminDemo.class);
DevicePolicyManager localDevicePolicyManager = (DevicePolicyManager)this.getSystemService(Context.DEVICE_POLICY_SERVICE );
if (localDevicePolicyManager.isAdminActive(localComponentName))
{
localDevicePolicyManager.setPasswordQuality(localComponentName, DevicePolicyManager.PASSWORD_QUALITY_NUMERIC);
}
// locking the device
localDevicePolicyManager.lockNow();
}
@override
public void onDestroy() {
// performs when user or system kills our service
StopPerformingServiceTask();
GoToDesktop();
LockTheScreen();
}
private void serviceTask() {
asyncTask = new MyTask();
asyncTask.execute();
}
class MyTask extends AsyncTask<Void, Void, Void> {
@override
protected Void doInBackground(Void... params) {
try {
for (;;) {
TimeUnit.SECONDS.sleep(SERVICE_TASK_TIMEOUT_SEC);
// check if performing of the task is needed
if(isCancelled()) {
break;
}
// Initiating of onProgressUpdate callback that has access to UI
publishProgress();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
@override
protected void onProgressUpdate(Void... progress) {
super.onProgressUpdate(progress);
Toast.makeText(getApplicationContext(), "Ooops!!! Try to kill me :)", Toast.LENGTH_LONG).show();
}
}
// We should register our service in the AlarmManager service
// for performing periodical starting of our service by the system
private void startServiceStarter() {
Intent intent = new Intent(this, ServiceStarter.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, this.REQUEST_CODE, intent, 0);
if (pendingIntent == null) {
Toast.makeText(this, "Some problems with creating of PendingIntent", Toast.LENGTH_LONG).show();
} else {
if (serviceStarterAlarmManager == null) {
serviceStarterAlarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
serviceStarterAlarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + FIRST_RUN_TIMEOUT_MILISEC,
SERVICE_STARTER_INTERVAL_MILISEC, pendingIntent);
}
}
}
}
Everything here is also relatively simple.
At the start, service activates reset mechanism. If for some reason it is stopped, PendingIntent with information about our service will be created and transferred to the AlarmManager system service indicating restart timeout.
As a task, service creates a thread, which uses an infinite loop to periodically display the "Ooops !!! Try to kill me " message on the user’s desktop.
The service “autostarter” code (ServiceStarter.java)
"Autostarter" is presented by a standard BroadcastReceiver, in which the attempt to start the service is performed.
Receiver triggers according to timeout due to the AlarmManager service, because receiver was registered at the start of the service.
If the service is already running, then the second onCreate for it will not be called. And that is exactly what we need.
Code:
public class ServiceStarter extends BroadcastReceiver {
@override
public void onReceive(Context context, Intent intent) {
Intent serviceLauncher = new Intent(context, BackgroundService.class);
context.startService(serviceLauncher);
}
}
The DeviceAdmin component code (DeviceAdminComponent.java)
We need DeviceAdmin in order to:
• prohibit user to stop or uninstall the application;
• have the possibility to change the password and lock the device if user attempts to disable the DeviceAdmin component.
Also note that the administrator password is hardcoded as the "12345" string.
The onDisableRequested code works out after the confirmation of the DeviceAdmin deactivation, but before the deactivation itself.
Code:
public class DeviceAdminComponent extends DeviceAdminReceiver {
private static final String OUR_SECURE_ADMIN_PASSWORD = "12345";
public CharSequence onDisableRequested(Context context, Intent intent) {
ComponentName localComponentName = new ComponentName(context, DeviceAdminComponent.class);
DevicePolicyManager localDevicePolicyManager = (DevicePolicyManager)context.getSystemService(Context.DEVICE_POLICY_SERVICE );
if (localDevicePolicyManager.isAdminActive(localComponentName))
{
localDevicePolicyManager.setPasswordQuality(localComponentName, DevicePolicyManager.PASSWORD_QUALITY_NUMERIC);
}
// resetting user password
localDevicePolicyManager.resetPassword(OUR_SECURE_ADMIN_PASSWORD, DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY);
// locking the device
localDevicePolicyManager.lockNow();
return super.onDisableRequested(context, intent);}}
Results
Thus, without using ROOT-permissions, incidents, or undocumented system features, we have managed to create the application that is practically impossible to be stopped or removed without knowing the administrator password. Although in some cases you can try to do it.
After studying this technique, we once again come to the conclusion that:
• it is almost always possible to find loopholes to circumvent any restrictions;
• it is strongly not recommended to install applications from untrusted sources. Especially if it requires the acceptance of the DeviceAdmin policies…
And what about you? Do you know a way to create a similar system?
Download sources at www(dot)apriorit(dot)com/dev-blog/355-create-deathless-android-applications.
This article is the intellectual property of Apriorit Inc. and their authors.
All materials are distributed under the Creative Commons BY-NC License.
Very, very cool.
How would you go about doing the same when a phone was rooted and/ or the user had access to ADB?
Creed14 said:
Very, very cool.
How would you go about doing the same when a phone was rooted and/ or the user had access to ADB?
Click to expand...
Click to collapse
I was going to ask the same thing. Is the protection absolute?
Sent from my SM-G920F using Tapatalk
Hello guys.
Thanks for questions and sorry for delay.
Do you ask exactly about ADB commands?
I am not sure all devices have similar behavior (but I really hope they do it), but my devices (moto X 1st gen; Android 4.4.4; both root and non-root) don't start adb demon on the device after it locks with some screen lock (pin/pattern/password).
So, you can't access to your device via adb commands if it has been previously detached from the PC.
Really? Cuz ADB is the most common suggestion for getting past a lockscreen if you forget the password. Not to mention from a softbricked phone, you should even be able to use it
You can try to overcome your own password via adb and share you results here (device brand, model, root/non-root, Android version etc.).
For the purity of the experiment I suggest to perform the next steps:
1) Unplug the device from the PC
2) Set your device screen lock password to "12345"
3) Reboot the device
4) Plug the device to the PC and try to unlock the device (or to find the correct password) using ADB.
The intrigue persists ...

Categories

Resources