Title bar mod


putting this inthe onCreate bundle will alow you to change the colour and text colour of the title bar

//title bar color
View titleView = getWindow().findViewById(android.R.id.title);
if (titleView != null) {
ViewParent parent1 = titleView.getParent();
if (parent1 != null && (parent1 instanceof View)) {
View parentView = (View)parent1;
parentView.setBackgroundColor(Color.GRAY);
}
}
this.setTitleColor(Color.CYAN);//text color

Button


This is how to set a simple onClickListener to a buttn, image or linearLayout.

//for a button

//Button = this identifise the object and tells us what it is.

Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}});

//for a linearLayout

linearLayout linearLayout 1 = (linearLayout) findViewById(R.id.linearLayout);
linearLayout 1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}});

this can be change to adapt to any type of object by changing what the object is identified as.

E-Mail


this is how to structure an intent to choose an e-mail client, and start to perpare an e-mail to send.

Intent i = new Intent(Intent.ACTION_SEND);
i.setType(“text/plain”);
i.putExtra(Intent.EXTRA_EMAIL  , new String[]{“me@gmail.com”}); // here you put the e-mail address you want to sent the e-mail to.
i.putExtra(Intent.EXTRA_SUBJECT, “this is were you put the title”);
i.putExtra(Intent.EXTRA_TEXT   , “this is the place you nput the text”);
try {
startActivity(Intent.createChooser(i, “Send mail…”));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(contactme.this, getString(R.string.Emails_Not_Found), Toast.LENGTH_SHORT).show();
}

to send an e-mail to multiple e-mail addresses replace

“me@gmail.com”

with

“me@gmail.com”, “me2@gmail.com”

or how ever many e-mail addresses you want to send the email to. also to create a new line add “\n” to you text

Option Menu


this show how a simple option menu can be displayed. the next bits of code need to be put in the main activity but not in the onCreate method, this is because they are use as soon as the activity is started anyway.

@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.exit:             finish();
break;
case R.id.view_in_market:    Intent browserIntent = new Intent(“android.intent.action.VIEW”,
Uri.parse(“market://details?id=com.android.example”));
startActivity(browserIntent);
break;
}
return true;
}

and the xml file for them menu needs to look like this. the order of the menu items changes the location of the buttons in the menu.

<menu xmlns:android=”http://schemas.android.com/apk/res/android”&gt;
<item android:id=”@+id/view_in_market”
android:title=”View In Market”
android:icon=”@drawable/view_in_market”/> // these images i use can be found in framework.apk, they are called different names though.
<item android:id=”@+id/exit”
android:title=”Exit”
android:icon=”@drawable/exit”/>
</menu>

Update Script


this can be used by adding this to you splash screen or anyother of your activitys

if (mWifi.isConnected()) {
Intent i3 = new Intent(splashscreen.this, Update.class);
startService(i3);
}

 

this is what checks for the update.

package com.lukemovement.roottoolbox.pro;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;

/**
* @author rac
*
*/
public class Update extends Service {

private static final String EXTRA_NOTIFY = “EXTRA_NOTIFY”;
private static final String DOWNLOAD_URL = “DOWNLOAD_URL”;
/** Constants **/
private static String urlLatestVersion = “http://dl.dropbox.com/u/22618820/open%20source/Toolbox/update/latest_version.txt&#8221;;
private static String urlLatestUrl = “http://dl.dropbox.com/u/22618820/open%20source/Toolbox/update/latest_url_pro.txt&#8221;;
private static String logName = “App update”;
private static int UPDATE_NOTIFICATION_ID = 1;

/** Variables **/
private int latestVersion = 0;
private int actualVersion = 0;
private String latestUrl = “”;

/** managers **/
@SuppressWarnings(“unused”)
private static SharedPreferences settings;

@Override
public void onStart(Intent intent, int startId) {
// check if the intent contains notification data 🙂
if (intent.getBooleanExtra(EXTRA_NOTIFY, false) && intent.hasExtra(DOWNLOAD_URL)) {
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

notificationManager.cancel(UPDATE_NOTIFICATION_ID);

//launching the browser
Intent downloadIntent = new Intent(             android.content.Intent.ACTION_VIEW      , Uri.parse(intent.getStringExtra(DOWNLOAD_URL)));
downloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.startActivity(downloadIntent);
this.stopSelf();
return;
}
/** get me my preferences **/
settings = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
/** which version am I running? **/
try {
PackageInfo pi = getPackageManager().getPackageInfo(
getPackageName(), 0);
actualVersion = pi.versionCode;
} catch (PackageManager.NameNotFoundException e) {
}
/** does a update exist? **/
if (checkForUpdate()) {
// Update exists
Log.i(logName, “App ” + latestVersion
+ ” is available!”);
updateNotify();
} else {
// no update needed
Log.i(logName,
“you have the latest version of App running”);
}
this.stopSelf();
}

/* (non-Javadoc)
* @see android.app.Service#onBind(android.content.Intent)
*/
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}

private boolean checkForUpdate() {
try {
latestVersion = Integer.parseInt(getHttpString(urlLatestVersion));
} catch (IOException e1) {
// TODO Auto-generated catch block
// e1.printStackTrace();
Log.i(logName, e1.getLocalizedMessage());
return false;
} catch (NumberFormatException e2) {
Log.i(logName, e2.getLocalizedMessage());
return false;
}

if (actualVersion < latestVersion) {
try {
latestUrl = getHttpString(urlLatestUrl);
} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
Log.i(logName, e.getLocalizedMessage());
}
return true;
} else
return false;
}

private void updateNotify() {
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
int icon = R.drawable.update;
long when = System.currentTimeMillis();
Notification notification = new Notification(icon,”App update is available”, when);
//Intent notifyIntent = new Intent(             android.content.Intent.ACTION_VIEW      , Uri.parse(latestUrl));
Intent notifyIntent = new Intent(this, Update.class);
notifyIntent.putExtra(Update.EXTRA_NOTIFY, true);
notifyIntent.putExtra(Update.DOWNLOAD_URL, latestUrl);

PendingIntent pendingIntent =  PendingIntent.getService(
this,
0,
notifyIntent,
android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);

notification.setLatestEventInfo(
getApplicationContext(),
“App update is available”, “click to download”,
pendingIntent);

notificationManager.notify(UPDATE_NOTIFICATION_ID, notification);

}

/**
* taken from http://www.devx.com/wireless/Article/39810/1954
*
* @param urlString
* @return InputStream
* @throws IOException
*/
private String getHttpString(String urlString) throws IOException {
InputStream in = null;
int response = -1;

URL url = new URL(urlString);
URLConnection conn = url.openConnection();

if (!(conn instanceof HttpURLConnection))
throw new IOException(“Not an HTTP connection”);

try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod(“GET”);
httpConn.connect();

response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
} catch (Exception ex) {
throw new IOException(“Error connecting”);
}
if (in != null) {
StringBuilder sb = new StringBuilder();
String line;

try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(in, “UTF-8”));
while ((line = reader.readLine()) != null) {
sb.append(line); // .append(“\n”);
}
} finally {
in.close();
}
return sb.toString();
} else
return “”;

}

}

the files mention at the top need to consist of a market link and the app version. enter them into a browser to veiw examples.

E.g market://details?id=com.lukemovement.roottoolbox.pro

E.g 16

Market License Check


i have decided to help other develper by posting source code and examples on how to use it on my blog. this is an example of a simple license check activity.

package com.android.example.license check;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import com.android.vending.licensing.*;

public abstract class LicenseCheckActivity extends Activity {

static boolean licensed = true;
static boolean didCheck = false;
static boolean checkingLicense = false;
static final String BASE64_PUBLIC_KEY = ” ENTER YOU PUBLIC KEY HERE “;

LicenseCheckerCallback mLicenseCheckerCallback;
LicenseChecker mChecker;

Handler mHandler;

SharedPreferences prefs;

// REPLACE WITH YOUR OWN SALT , THIS IS FROM EXAMPLE
private static final byte[] SALT = new byte[]{
-45, 65, 30, -128, -25, -57, 74, -64, 56, 88, -85, -45, 77, -117, -25, -113, -12, 32, -64,
89
};

private void displayResult(final String result) {
mHandler.post(new Runnable() {
public void run() {

setProgressBarIndeterminateVisibility(false);

}
});
}

protected void doCheck() {

didCheck = false;
checkingLicense = true;
setProgressBarIndeterminateVisibility(true);

mChecker.checkAccess(mLicenseCheckerCallback);
}

protected void checkLicense()

Log.i(“LICENSE”, “checkLicense”);
mHandler = new Handler();

// Try to use more data here. ANDROID_ID is a single point of attack.
String deviceId = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);

// Library calls this when it’s done.
mLicenseCheckerCallback = new MyLicenseCheckerCallback();
// Construct the LicenseChecker with a policy.
mChecker = new LicenseChecker(
this, new ServerManagedPolicy(this,
new AESObfuscator(SALT, getPackageName(), deviceId)),
BASE64_PUBLIC_KEY);

//        mChecker = new LicenseChecker(
//                this, new StrictPolicy(),
//                BASE64_PUBLIC_KEY);

doCheck();
}

protected class MyLicenseCheckerCallback implements LicenseCheckerCallback {

public void allow() {
Log.i(“LICENSE”, “allow”);
if (isFinishing()) {
// Don’t update UI if Activity is finishing.
return;
}
// Should allow user access.
displayResult(getString(R.string.allow));
licensed = true;
checkingLicense = false;
didCheck = true;

}

public void dontAllow() {
Log.i(“LICENSE”, “dontAllow”);
if (isFinishing()) {
// Don’t update UI if Activity is finishing.
return;
}
displayResult(getString(R.string.dont_allow));
licensed = false;
checkingLicense = false;
didCheck = true;

showDialog(0);
}

public void applicationError(ApplicationErrorCode errorCode) {
Log.i(“LICENSE”, “error: ” + errorCode);
if (isFinishing()) {
// Don’t update UI if Activity is finishing.
return;
}
licensed = false;
// This is a polite way of saying the developer made a mistake
// while setting up or calling the license checker library.
// Please examine the error code and fix the error.
@SuppressWarnings(“unused”)
String result = String.format(getString(R.string.application_error), errorCode);
checkingLicense = false;
didCheck = true;

//displayResult(result);
showDialog(0);
}
}

protected Dialog onCreateDialog(int id) {
// We have only one dialog.
return new AlertDialog.Builder(this)
.setTitle(R.string.unlicensed_dialog_title)
.setMessage(R.string.unlicensed_dialog_body)
.setPositiveButton(R.string.buy_button, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(
http://market.android.com/details?id=&#8221; + getPackageName()));
startActivity(marketIntent);
finish();
}
})
.setNegativeButton(R.string.quit_button, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
})

.setCancelable(false)
.setOnKeyListener(new DialogInterface.OnKeyListener(){
public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
Log.i(“License”, “Key Listener”);
finish();
return true;
}
})
.create();

}

@Override
protected void onDestroy() {
super.onDestroy();
if (mChecker != null) {
Log.i(“LIcense”, “distroy checker”);
mChecker.onDestroy();
}
}
}

The best way to use this is like so. If this license check activity is used offline it will not be able to check the license and assume the application isn’t licensed. Only wifi can be use because data connection can be extremely slow.

first off your activity need the extend the license check.

public class MainActivity extends LicenseCheckActivity{

this needs to be in the onCreate methor to check the license.

ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

if (mWifi.isConnected()) {
checkLicense();
}

these values need to be added to the strings file.

<!– online license check –>
<string name=”check_license”>Check license</string>
<string name=”checking_license”>Checking license…</string>
<string name=”dont_allow”>Don\’t allow the user access</string>
<string name=”allow”>Allow the user access</string>
<string name=”application_error”>Application error: %1$s</string>
<!– Unlicensed dialog messages –>
<string name=”unlicensed_dialog_title”>Application not licensed</string>
<string name=”unlicensed_dialog_body”>This application is not licensed. Please purchase it from Android Market.</string>
<string name=”buy_button”>Buy app</string>
<string name=”quit_button”>Exit</string>

also the permissions that are needed in the manifest need to look like this.

<uses-permission android:name=”android.permission.INTERNET”></uses-permission>
<uses-permission android:name=”android.permission.ACCESS_WIFI_STATE” />
<uses-permission android:name=”com.android.vending.CHECK_LICENSE” />