Language:EN
Pages: 35
Rating : ⭐⭐⭐⭐⭐
Price: $10.99
Page 1 Preview
cellidwriter class continues here publicvoid write

Cellidwriter class continues here publicvoid write cid

Using files

Reading files from resources
Raw files are processed by aapt and must be referenced from the application using a resource identifier in the R class
Asset files are compiled into the .apk file as-is and you can navigate this directory in the same way as a typical file system

privatestatic CharSequence readResourceOrAsset(Activity activity /* Context ctx */) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(activity.getAssets().open("EULA.txt")));
reader = new BufferedReader(new InputStreamReader(activity.getResources().openRawResource(R.raw.instructions))); String line;
StringBuilder buffer = new StringBuilder();
while ((line = reader.readLine()) != null)
buffer.append(line).append('\n');
return buffer;
} catch (IOException e) {
return"";
} finally {
closeStream(reader);
}
}

• Every application can read and write from/to the SD card (external memory) but needs permissions in AndroidManifest

– Write needs the WRITE_EXTERNAL_STORAGE permission

irectory

Context.getFilesDir();
// Create or access a directory

Helper methods for the private storage area

worked, false otherwise
ion’s private area in a String array java.io.FileInputStream
java.io.FileOutputStream
;

privatevoid writeFileToInternalStorage() {
String eol = System.getProperty("line.separator"); BufferedWriter writer = null;
try {
writer = new BufferedWriter(
new OutputStreamWriter(
openFileOutput("myfile",
MODE_WORLD_WRITEABLE)));
writer.write("This is a test1." + eol);
writer.write("This is a test2." + eol);
} catch (Exception e) {
e.printStackTrace();
}
finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

privatevoid readFileFromInternalStorage() {
String eol = System.getProperty("line.separator"); BufferedReader input = null;
try {
input = new BufferedReader(
new InputStreamReader(
openFileInput("myfile"))); String line;
StringBuffer buffer = new StringBuffer(); while ((line = input.readLine()) != null) { buffer.append(line + eol);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

– Use with DIRECTORY_*** to
get the standard directory
locations

• getExternalStorageDirectory()

storage system (it can be unmounted, removed, unformatted etc.)

– Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)

= null) {

} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();

• Example of EULA, about dialog and recent changes

– Reading files with html tags from res/raw

publicclass MainActivity extends Activity {
privatestaticfinalbooleanLIGHT_THEME = false;
@Override
protectedvoid onCreate(Bundle savedInstanceState) {
// must read theme from settings then recreate(); if i

t should pr opagate at once after change

if(LIGHT_THEME)
setTheme(R.style.CustomThemeLight); else
setTheme(R.style.CustomThemeDark);

// http://stackoverflow.com/questions/9286822/how-to-f
// in combination with: http://www.intertech.com/Blog/
try {
ViewConfiguration config = ViewConfiguration.get(this); Field menuKeyField = ViewConfiguration.class.g
if(menuKeyField != null) {
menuKeyField.setAccessible(true);
menuKeyField.setBoolean(config, false);
}
}
catch (Exception ex) {
// Ignore
}

orce-use-of Post/Androi

setContentView(R.layout.activity_main);
// Set up the action bar to show a drop down list final ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(R.string.app_name);

// only shows once
Eula.show(this);
}

}

erride
publicboolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, s // as you specify a parent activity in AndroidManifest.xml.

publicclass AboutDialog extends Dialog{

privatestatic Context mContext = null;

tv = (TextView) findViewById(R.id.whatsnew_text); ss = Html.fromHtml(readRawTextFile(R.raw.whatsnew)); tv.setText(ss);

neer/a-reusable-about-dialog-for-your-android-apps/ s-supported-by-textview.html */

Linkify.addLinks(tv, Linkify.WEB_URLS); }

publicstatic String readRawTextFile(int id) {
InputStream inputStream = mContext.getResources().openRawR

statistics about network status and telephone information

– See the PhoneStateSampleActivity

Wi-Fi

int lac = location.getLac();

// and LAC (Location Area Code)

privatefinal String fname = "/cellid.txt"; private String mCID, mLAC, mMCC, mMNC;

publicvoid run()
{
try{

}

// append at end of file

fw.append(sb.toString());

// android does flush() in close()
System.err.println(e.toString() +

e.printStackTrace();

}

File I/O (byte) streams

• FileInputStream, FileOutputStream, InputStream and OutputStream

// How to inflate the object back from the file: FileInputStream fis = context.openFileInput(SAVENAME); ObjectInputStream ois = new ObjectInputStream(is); Flow f = (Flow) ois.readObject();

//the file has not yet been written
}

any user interface

 When Android needs to kill applications to save resources, Services has high priority, only second to foreground Activities
 Other components can start and stop the service, it can also stop itself While it is running other components can bind to it (if implemented) Consider using a Service when the application
– performs a lengthy or intensive processing, not requiring user interaction – performs certain tasks at regular intervals, e.g. downloading updates of some content
– performs lengthy operations that shouldn’t be canceled if the application exits, e.g. downloading a large file
– needs to provide data or information services to other applications (without an user interface)

Service 2

 A service runs in the main thread of its hosting process

– Any CPU intensive work or blocking operations should be performed by spawning a worker thread!

– Started (or unbound) - when
an application component
starts it by calling
startService() - runs until it
stops itself with stopSelf() or

Creating a simple service
 Declare the service in your Androidmanifest inside the application tag

publicclass SimpleService extends Service
{
int[] notes =
{R.raw.c5, R.raw.b4, R.raw.a4, R.raw.g4}; intNOTE_DURATION = 500; //millisec
MediaPlayer m_mediaPlayer;
booleanpaused = false;

@Override
public IBinder onBind(Intent intent) { returnnull;
}

m_mediaPlayer =
MediaPlayer.create(this, notes[i%4]); m_mediaPlayer.start();

try {
Thread.sleep(NOTE_DURATION); }
catch (InterruptedException e) { e.printStackTrace();
}
i++;
}
}
}
} // end SimpleService class

• Subclass of Service that uses a worker thread to handle all

start requests, one at a time

long endTime = System.currentTimeMillis() + 5*1000;
while (System.currentTimeMillis() < endTime) {
synchronized (this) {
try {
wait(endTime - System.currentTimeMillis()); } catch (Exception e) {

}

} } }
See the example
NotificationActivityService

You are viewing 1/3rd of the document.Purchase the document to get full access instantly

Immediately available after payment
Both online and downloadable
No strings attached
How It Works
Login account
Login Your Account
Place in cart
Add to Cart
send in the money
Make payment
Document download
Download File
img

Uploaded by : Caroline Greer

PageId: DOCF012A78