Security Exception accessing Content Provider in another application - General Questions and Answers

Hello everybody!
I'm trying to create a content provider usable only by the applications that are signed by the same certificate. I've declared the content provider like this
<provider
android:name=".MyProvider"
android:authorities="com.example.provider"
androidermission="com.example.permissions.USER_PERMISSION"
android:readPermission="com.example.permissions.USER_PERMISSION_READ"
android:writePermission="com.example.permissions.USER_PERMISSION_WRITE"
android:exported="true">
</provider>
I have declared the permissions with signature protection level.
All good but when I try to access the provider from the other application like this:
//Create an URI that will be used to check the status of the content provider
Uri myURI = Uri.parse("content://com.example.provider");
ContentResolver contentResolver = getContentResolver();
try {
contentResolver.insert(prototypeURI,null);
} catch (Exception e) {
e.printStackTrace();
}
I get a SecurityException: Permission Denial: opening provide ... requires com.example.permissions.USER_PERMISSION_READ.
Any ideas?

Solution
I have found the issue.
The main project was configured to create debug builds with a custom signing configuration.

Related

C#: Make program run even though it's minimized

I'm programming an application (WM 6.1) that should do things regardless if the program is active or minimized (user pressed the X button). This is where my problem occurs, my program is set on "pause" when the program is minimized. I need it to run even though it's in the background. How to solve this?
threads
Hi Pytagoras,
I haven´t made a lot of C# programs, but I think that only the main thread is pause when the program is minimized, but the additional threads don´t. So if you need something running on background you need to implement it on an additional thread...
See you
Pytagoras said:
I'm programming an application (WM 6.1) that should do things regardless if the program is active or minimized (user pressed the X button). This is where my problem occurs, my program is set on "pause" when the program is minimized. I need it to run even though it's in the background. How to solve this?
Click to expand...
Click to collapse
Thanks for your reply
I'm new to threads, haven't really needed them before. So I found some examples:
Code:
class ThreadTest {
private void frmProgram_Load(object sender, EventArgs e)
{
Thread t = new Thread (WriteY);
t.Start(); // Run WriteY on the new thread
}
static void WriteY() {
while (true) Console.Write ("y"); // Write 'y' forever
}
}
Of course I loaded my own method instead of the WriteY example method described here. The thread get started in the Load event of the main form, so it should execute. However, it doesn't work when the program is minimized, and with this thread way of doing it, it doesn't work when it's opened either. (the program should notice a sms ticking in, and do something based on it).
Any help would be greatly appreciated (there should be a dedicated forum on xda for this kind of things / different programming languages..just a comment)
Try something like this... should work...
Code:
class ThreadTest {
private Thread t;
private void frmProgram_Load(object sender, EventArgs e)
{
t = new Thread(new ThreadStart(WriteY));
t.IsBackGround = true;
t.Start();
}
static void WriteY() {
while (true) Console.Write ("y"); // Write 'y' forever
}
}
Strange, it still don't work. I even tried with the code you posted without changing any of it, and still it don't run. It won't even write to the console
The issue is that the console.write is not showing on "Output Window"... see the code below... that it keeping update the file even if minimized...
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;
namespace ThreadTest
{
public partial class Form1 : Form
{
private Thread t;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
t = new Thread(new ThreadStart(WriteY));
t.IsBackground = true;
t.Start();
}
private void WriteY()
{
while (true)
{
FileStream fs = new FileStream("\\test.txt", FileMode.Create);
StreamWriter w = new StreamWriter(fs, Encoding.UTF8);
w.WriteLine(DateTime.Now.ToString());
w.Flush();
w.Close();
fs.Close();
}
}
}
}
Thank you for your help, but I get this when I run your code:
System.IO.IOException:
"The process can not access the file '\\test.txt' because it is being used by another process."
The possibility for that is that you are running the example more than once...
Pytagoras said:
Thank you for your help, but I get this when I run your code:
System.IO.IOException:
"The process can not access the file '\\test.txt' because it is being used by another process."
Click to expand...
Click to collapse
Ok, I don't know that went wrong, but I've created a new project, and here it worked.
However, it doesn't work with the sms detection I try to implement.
I'll post the code hoping anyone have some hints:
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using Microsoft.WindowsMobile.PocketOutlook;
using Microsoft.WindowsMobile.PocketOutlook.MessageInterception;
namespace BackgroundTestApp
{
public partial class Form1 : Form
{
private Thread t;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Start a new thread hoping that this will detect sms even if it's minimized
t = new Thread(new ThreadStart(startMessageDetection));
t.IsBackground = true;
t.Start();
// This works, but only when the program isn't minimized
//startMessageDetection();
}
/// <summary>
/// Load the message detection (sms)
/// </summary>
private void startMessageDetection()
{
MessageInterceptor messageInterceptor = new MessageInterceptor();
messageInterceptor.InterceptionAction = InterceptionAction.NotifyAndDelete;
messageInterceptor.MessageReceived += new MessageInterceptorEventHandler(messageRecieved);
}
void messageRecieved(object sender, MessageInterceptorEventArgs e)
{
if (e.Message is SmsMessage)
{
MessageBox.Show("Message recieved!");
}
}
}
}
Hi Pytagoras,
Sorry, with this part I can´t help you... never coded using this class...
See you,
Pytagoras said:
Ok, I don't know that went wrong, but I've created a new project, and here it worked.
However, it doesn't work with the sms detection I try to implement.
I'll post the code hoping anyone have some hints:
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using Microsoft.WindowsMobile.PocketOutlook;
using Microsoft.WindowsMobile.PocketOutlook.MessageInterception;
namespace BackgroundTestApp
{
public partial class Form1 : Form
{
private Thread t;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Start a new thread hoping that this will detect sms even if it's minimized
t = new Thread(new ThreadStart(startMessageDetection));
t.IsBackground = true;
t.Start();
// This works, but only when the program isn't minimized
//startMessageDetection();
}
/// <summary>
/// Load the message detection (sms)
/// </summary>
private void startMessageDetection()
{
MessageInterceptor messageInterceptor = new MessageInterceptor();
messageInterceptor.InterceptionAction = InterceptionAction.NotifyAndDelete;
messageInterceptor.MessageReceived += new MessageInterceptorEventHandler(messageRecieved);
}
void messageRecieved(object sender, MessageInterceptorEventArgs e)
{
if (e.Message is SmsMessage)
{
MessageBox.Show("Message recieved!");
}
}
}
}
Click to expand...
Click to collapse
I don't know what's happening, but I don't like the fact that messageInterceptor is local to startMessageDetection(). The thread will not continue forever, since it is not looping... the three operations in startMessageDetection() will be performed and the thread will cease. I would make messageInterceptor a member of the form, assign it in startMessageDetection(), and try it without the thread. Does this work?
try making it a process instead of an application. Processes are ment to be running in the background.

Socket Programming on HTC Magic

Hi, I have made an application on the phone which collects the data from the built-in sensors, and now I'm trying to use socket programming to send the data to my laptop. Basically, I put the following socketing code in my application code and wrote another server program on my laptop to set up the connection between the cellphone and the laptop. But it doesnt seem to work....my phone shows a debug message "No I/O"...meaning, I guess, the phone is actually not sucessfully connected to the laptop. Could anybody pls teach me the right way to do this? communication either through wifi (my laptop and phone both already logged onto the campus network), or usb(the phone is directly connected to the laptop by a usb cable). Thank you!
Client code on the phone:
public void listenSocket(){
//Create socket connection
try{
socket = new Socket("localhost", 4444);
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream())), true);
} catch (UnknownHostException e) {
socketMsg.setText("Unknown host: localhost");
} catch (IOException e) {
socketMsg.setText("No I/O");
}
}
Server code on the laptop:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
class SocketServer1 {
public static void main(String[] args){
ServerSocket server = null;
Socket client = null;
BufferedReader in = null;
PrintWriter out = null;
try{
server = new ServerSocket(4444);
} catch (IOException e) {
System.out.println("Could not listen on port 4444");
System.exit(-1);
}
System.out.println("Server is ready");
try{
client = server.accept();
System.out.println("Server is not accepting data");
} catch (IOException e) {
System.out.println("Accept failed: 4444");
System.exit(-1);
}
try{
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
out = new PrintWriter(client.getOutputStream(), true);
} catch (IOException e) {
System.out.println("Accept failed: 4444");
System.exit(-1);
}
//Clean up
try{
in.close();
out.close();
server.close();
} catch (IOException e) {
System.out.println("Could not close.");
System.exit(-1);
}
}
}
PS. I guess the problem may be the server_name and port_number set on my phone are not correct....
After a quick look, and please take into consideration I never did Android programming, in the client, instead of trying to connect to the server you are trying to connect to localhost, wich means, you are trying to connect to your phone. You need to replace localhost with the ip of your server. The port seems to be ok since you are opening a server socket in your server in the port 4444
helderp said:
After a quick look, and please take into consideration I never did Android programming, in the client, instead of trying to connect to the server you are trying to connect to localhost, wich means, you are trying to connect to your phone. You need to replace localhost with the ip of your server. The port seems to be ok since you are opening a server socket in your server in the port 4444
Click to expand...
Click to collapse
Hi thank you helderp! I think I've figuired it out. what you suggested is one of the reasons.
just for your info, the other BIG reason, which is actually about android programming, is that in "AndroidManifest.xml" file should add in "<uses-permission android:name="android.permission.INTERNET">"....

[APP] Zune software remote control

Instructions + download: http://forum.xda-developers.com/showpost.php?p=17254652&postcount=7
I have finally found a way to control the Zune software running on Windows. The Zune API is horrible so there are few(if any) programs that interface with the software externally. Today I came across the SendMessage method. The idea is your Android device is a big remote control for the Zune software. If you already have a media remote then this application isn't needed. I only have a remote on my laptop, not desktop so that's why I'm bothering to write it. I thought I would share it on XDA for free.
http://pastebin.com/C85isGsW - that was my test program. When I opened it my music paused(yay!).
Anyways this will be a 2-part system. The Windows app will run in the background(either as a service or in the system tray) and listen on some random TCP port for a connection. It will be relatively small, using less than 50MB RAM. This one uses 27MB right now(yes, C# is bloated).
The Android app will simply connect over the wifis or even over the internet(just remember to forward ports) and after a quick handshake it will be able to send and receive data from the service/app in tray. First I'll start with simple play/pause buttons and a volume slider and eventually I'll add all the interfaces listed here: http://msdn.microsoft.com/en-us/library/ms646275(v=vs.85).aspx
Step 1: install service or open the Windows program
Step 2: type computer IP in android app
Step 3: press play/pause or control volume etc. It will save the IP so you don't have to keep typing it in. In fact I will have a dropdown list so you can select different computers(HTPC, basement computer etc.)
I just started writing the program so it will by done by the end of the weekend. Figured I would create the thread since I know it will work.
inb4 zune sucks
Interested in seeing this.
Sent from my Transformer TF101 using XDA Premium App
yes dude yes!!! imso amped for this! thanks so much.
OK I got the windows side app 95% done... started the Android version and well.. I'm a noob. Looks like honeycomb makes you interface with TCP in a separate thread...
Windows server code:
Code:
hile (stop != 1)
{
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
data = null;
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
int i;
// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
//Console.WriteLine("Received: {0}", data);
if (Convert.ToString(data).CompareTo("PP") == 0) SendMessageW(hwnd, WM_APPCOMMAND, hwnd, (IntPtr)APPCOMMAND_MEDIA_PLAY_PAUSE);
if (Convert.ToString(data).CompareTo("UP") == 0) SendMessageW(hwnd, WM_APPCOMMAND, hwnd, (IntPtr)APPCOMMAND_VOLUME_UP);
if (Convert.ToString(data).CompareTo("DN") == 0) SendMessageW(hwnd, WM_APPCOMMAND, hwnd, (IntPtr)APPCOMMAND_VOLUME_DOWN);
if (Convert.ToString(data).CompareTo("PR") == 0) SendMessageW(hwnd, WM_APPCOMMAND, hwnd, (IntPtr)APPCOMMAND_MEDIA_PREVIOUSTRACK);
if (Convert.ToString(data).CompareTo("NE") == 0) SendMessageW(hwnd, WM_APPCOMMAND, hwnd, (IntPtr)APPCOMMAND_MEDIA_NEXTTRACK);
// Process the data sent by the client.
//device.AudioEndpointVolume.MasterVolumeLevelScalar = (Convert.ToInt64(data) / 100.0f);
//byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
//byte[] msg = System.Text.Encoding.ASCII.GetBytes("Successfully set to " + data);
// Send back a response.
//stream.Write(msg, 0, msg.Length);
//Console.WriteLine("Sent: {0}", data);
}
// Shutdown and end connection
client.Close();
}
}
What needs to happen to connect to the server(client code)
Code:
static void Connect(String server, String message)
{
try
{
// Create a TcpClient.
// Note, for this client to work you need to have a TcpServer
// connected to the same address as specified by the server, port
// combination.
Int32 port = 13000;
TcpClient client = new TcpClient(server, port);
// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
NetworkStream stream = client.GetStream();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);
// Close everything.
stream.Close();
client.Close();
}
catch (ArgumentNullException e)
{
MessageBox.Show("ArgumentNullException: " + e.ToString());
}
catch (SocketException e)
{
MessageBox.Show("SocketException: " + e.ToString());
}
}
So I would call Connect("192.168.1.40", "PP"); to pause/play the server(desktop running Zune)
Code:
package com.pwn.control;
import android.app.Activity;
import java.io.*;
import java.net.*;
import android.widget.*;
import android.os.Bundle;
import android.os.StrictMode;
public class ControlActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tv = new TextView(this);
tv.setText("HELLO WORLD");
setContentView(tv);
run();
}
TextView tv;
public void run()
{
new Thread(new Runnable() { public void run() {
Socket socket;
try
{
InetAddress serverAddr = InetAddress.getByName("192.168.1.40");
socket = new Socket("192.168.1.40", 13000);
//socket.connect();
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
out.writeBytes("PP");
//PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
//out.println("PP");
socket.close();
}
catch (Exception e)
{
tv.setText(e.toString());
//setContentView(R.layout.main);
}
}
} ).start();
}
}
Unfortunately the above code doesn't work. Kinda stuck lol... maybe someone knows more about writing android apps than I do.
http://www.youtube.com/watch?v=PMjNrd1d4FM
Got it working with an ASP site...
now the annoying part... I tried setting it up with a default IIS instance and it doesn't have permissions to use the user32.dll!!! I tried forced impersonation and tons of different tricks but for some reason it isn't getting as high permissions as the ASP.NET debugging server.
So I need to either fix the android app so it will communicate with the service, or I need to find a way to get the IIS instance enough permissions to interact with the desktop. I did set the IIS Admin service to "interact with desktop" but nothing happened.
I also tried setting up Apache 2.2 with mod_asp installed but it has the same result... blocked from interacting.
Ok I got it working but it's really really makeshift right now...
ASP website --> loopback on port 13000 --> C# app(that will actually interface with the Zune software)
I couldn't make the API call from the C# code in the ASP site because IIS doesn't have enough permissions. So since my only drawback before was that I couldn't communicate between .NET TcpListener and Java, I can just use the ASP site to make the TcpClient connection.
The good thing is you can access this interface from anything with a web browser. Just make http://computer-ip:port/ZuneControl a favorite on any device and you can control Zune from it.
http://www.youtube.com/watch?v=haVLCOY0l6U
If you're really eager to try the alpha build with IIS that's fine...
Just set up IIS like I do in the video and add port 13000 to your inbound and outbound firewall rule. I'll work on the UI when I get some time next weekend.
Here is the code for the C# app. http://pastebin.com/08kCjKQW
The web code is in the RAR file. I just copied and pasted out of that pastebin with some extra buttons.
http://tunerspotter.com/\dropbox\misc\ZuneControl.rar
In that ZuneControl folder, ZuneControl.exe is the app. Click start, then minimize it after you set up IIS. It will work for Apache installations also. I have Apache on port 82. http://sourceforge.net/projects/mod-aspdotnet/
Instruction video: http://www.youtube.com/watch?v=ClCQhmQxC7Q
Well i've been using the web interface for a few days and it kicks ass. Does exactly what i want. I can be in bed and change songs/volume from another tab in Opera.
Next weekend Ill see if i can get the program to listen on port 81 as a web service so instead of setting up IIS or apache all you have to do is open the app and click start(then minimize it)
{
"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"
}
hey are you still working on this? I would really love something like this!
well i gave up on the app and just turned it into a ASP site + windows application. so yeah i've been using it for a few months. works great, i can pull up on any web capable device and adjust my music. Whether it's my zune, tablet, computer, or phone, i can adjust volume, go back/next, and pause/play from any device. i set up port forwarding with dyndns.org so it works over 3G

[Guide} [Basic] App development basics and first android app fully functional

This is basic guide to start to off app development for android..........
This is just a basic guide and not a comprehensive one which covers the whole lot of it but a rather a guide to get a basic simple app of your own running without any issues
Requirements
A bit of java
linux , darwin or a windows 7 machine
internet connection
basic idea of how programming works
sdk with atleast one api installed and configured path
Part 1 setting up everthing and explaining used variables and terms
Now let's get started
[windows}
Download eclipse as any other software and install it by the .exe file and follow the instructions
(linuc macosx )
if you are on a older ditribution of linux the minimum required version of eclipse 3.6 is not supplied via ubuntus main repository ....
so you need to download it from the eclipse official website and install it....
[common}
Installing ADT(Android developer tools) plugin
open up eclipse
Start Eclipse, then select Help > Install New Software.
Click Add, in the top-right corner.
In the Add Repository dialog that appears, enter "ADT Plugin" for the Name and the following URL for the Location:
https://dl-ssl.google.com/android/eclipse/
Click OK.
If you have trouble acquiring the plugin, try using "http" in the Location URL, instead of "https" (https is preferred for security reasons).
In the Available Software dialog, select the checkbox next to Developer Tools and click Next.
In the next window, you'll see a list of the tools to be downloaded. Click Next.
Read and accept the license agreements, then click Finish.
If you get a security warning saying that the authenticity or validity of the software can't be established, click OK.
When the installation completes, restart Eclipse.
Configure the ADT Plugin
Once Eclipse restarts, you must specify the location of your Android SDK directory:
In the "Welcome to Android Development" window that appears, select Use existing SDKs.
Browse and select the location of the Android SDK directory you recently downloaded.
Click Next.
If you haven't encountered any errors, you're done setting up ADT and can continue to Next Steps.
the path to the sdk is case sensitive and absolute so be careful guys....
Now you have virtually everything set up to start building apps
go to file>new>project>android>android application project
something like this will pop up
{
"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"
}
now
the first three fields are yours to choose
now the second part
The build sdk is the sdk that you are targeting in laymans words its like building a building on a certain specific site.....
the minimum required sdk
now if choose this as froyo(api 8) your app will run on froyo os and above and will be compatible with older flavours of android....
once you are done creating a new project hit finish
now you will see something like this
now the calculator is my app name the name that you gave a few minutes ago will be yours...
Now the android is basically divided into three main things
The android manifest
The src folder
The xml
The android manifest basically is a traffic police in lay mans words
it determines which activity comes first when it ends etc...
note:i will be referring the xml to a activty
the src folder contains all of your java
xml's are the skeltel system of android they define the size layout colour or the whole look of your android project....
Note: dont tinker with the gen folder you alone will be responsible for your mistakes
in this tutorial you will be working with only src,res and xml's as i cant dig deeper into it because its a subject too broad to teach....
now lets get started
navigate to res > layout double click on main_activty.xml
below the screen click on activty_main.xml next to graphical layout...
something like this will appear
HTML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world"
tools:context=".MainActivity" />
</RelativeLayout>
this is the text appearing to you
Note this is auto generated....
now i will explain each line of it with my limited knowledge
HTML:
]<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
This is the auto generated refernce by eclipse yours may vary and might not be same as mine
HTML:
android:layout_width="match_parent"
android:layout_height="match_parent"
now you can see that the layout is set to match_parent by deafult
match_parent utilizes the whole screen into your layout...
and observe this guys the
HTML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
the relative layout has started with <relativelayout and ended with > anything code started should be finished up by > or />
both are literally same
now the next junk of code to deal with
HTML:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world"
tools:context=".MainActivity" />
Textview is basically a method by google to display some text on the screen...
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
These two lines suggest that your app has both vertcal and horizontal layout
android:text="@string/hello_world"
this is the text being displayed on your graphical layout
now go to layout > values > strings.xml
double click it
you will see something like this
now basically strings are resource files used to show text on display...
the string name cant have any spaces if it has then u will see errors
but the value of the string can have spaces
Activity
change the text in value field and see the result in graphical layout of the xml
now you basically need to use strings for each and every text that has to be displayed.......
End of part 1
Part 2
Adding of buttons and modifying them
now guys lets add some buttons to our project
navigate to src
in that you will find a java file open it (.java)
you will find something like this
HTML:
package com.exmple.addandsubract;
import android.R;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Layout extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_item);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_layout, menu);
return true;
}
}
now you might be wondering what is this crap code ...
now lets add buttons
navigate into layout open up the xml
your screen will show up this
HTML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world"
tools:context=".MainActivity" />
</RelativeLayout>
now within the closing of relative layout
copy paste this
HTML:
<Button
android:id="@+id/bsub"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="79dp"
android:text="@string/sub" /
every button must have an id for our convenience we have added a bsub as our program is to add and subtract a number
HTML:
android:layout_width="match_parent"
the layout width specifies the size of the width of the button
as i have said before match_parent is to occupy the whole screen..if you want it smaller you can set it in dp(density pixels)
HTML:
android:text="@string/sub"
you cant hard code stuff into the button u need to refernce it to a string i have referred it to the string sub
for this to work it requires you to add a string by the name sub in strings.xml
now do the same code again for button add
after this you will have something like this showing up
now that we have our button's set up we need to make this work (in real add java to it)
to accomplish this we need to link xml's to java
this may sound like greek and latin but guys stick with it u will understand everything
now below
HTML:
public class Layout extends Activity {
type this
HTML:
int counter=0;
Button add,sub;
TextView display;
as u may all know we should define a variable before we use them
as we are working with number (basically integars we use integar to define them
now we basically define display as textview
now coming to the real java part
HTML:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_item);
after this chunk of code
type
HTML:
counter=0;
the counter is the number which should be displayed on the screen for us
i have decided to start with 0 you can set it to any number that you prefer
now type this
HTML:
add = (Button) findViewById(R.id.badd);
sub = (Button) findViewById(R.id.bsub);
what this basically says is that add is a button and its id(in the xml) is badd.. findviewbyid is the method for referencing
now its the same for sub button too
HTML:
display = (TextView) findViewById(R.id.textView1);
this will set our display to textview1 which is our activity.xml this may sound as bloat to you but its handy when working with many xmls
now type
HTML:
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
display.setText("Your total is " + counter );
}
});
sub.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
display.setText("Your total is " + counter );
}
});
i will explain what this does
HTML:
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
display.setText("Your total is " + counter );
}
});
type add. then all lists will popup select onclicklistener(this makes the button clickable)
within the brackets of onclicklistener type new(as its a new button) leave a space type view.onlclicklistener(again you will see popups
now what is between this two brackets is what happens when the button is clicked now add this in between these brackets
HTML:
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
counter=counter+1;
display.setText("Your total is " + counter );
}
});
sub.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter=counter-1;
display.setText("Your total is " + counter );
}
});
HTML:
counter=counter-1;
this decrements the counter value by 1
after the counter is decremented we need to change the display to show the value of it
we do that by typing this
HTML:
counter=counter-1;
display.setText("Your total is " + counter );
now do this for both buttons test the app on emulator
Have doubts comment below
liked the thread rate it that gives me moral confidence and motivation
1st reserved op has plans of increasing
reservation
2nd
one final one for the day... :cyclops:
thanks! :good:
its to the point and very precise!
View attachment HelloWorld.apk
how do i add an icon? mine is the default andy.
And is it possible to open an app (eg launcher pro) in eclipse and mod it as per my wish?
Harryhades said:
thanks! :good:
its to the point and very precise!
View attachment 1401833
how do i add an icon? mine is the default andy.
And is it possible to open an app (eg launcher pro) in eclipse and mod it as per my wish?
Click to expand...
Click to collapse
There are two ways to add icon after giving the package name in the next menu you can change the icon....or go re drawabl-hdpi and replace the icon.png by the one that u want it should be case sensitive and it should be the same text....
For the 2nd question
yes you can mod these apps i have tried adw from cm'r repo but it should work with launhcer pro to btw the app has to deodexed.....
Thanks
Thanks bro i have started developing one :good:
completing the guide this sunday
I realize this is a few years old but I'm new to developing apps and I been trying to get this to work so that I can add a number to a number stored in a database. The number is put in the database via "edittext". When I try this my number gets replaced with "false" when I hit the add button.
Sent from my LG-LS995 using XDA Free mobile app

[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