Search Wikipedia

Search results

May 6, 2014

Adjust Screen Brightness in Android with example

Screen Brightness in Android can be controlled programmatically in simple way. This tutorial explains the process with an example. Native brightness control in Android device has a Seekbar that adjust the screen brightness. The below tutorial has UI in a similar way.You take a look at SeekBar tutorial here if needed. 

android.provider.Settings.System - This class contains miscellaneous system preferences. There are convenience functions for accessing individual system settings. android.provider.

Settings.System.getInt - Convenience function for retrieving a single system settings value as an integer. Note that internally setting values are always stored as strings; this function converts the string to an integer for you. The default value will be returned if the setting is not defined or not an integer. 

android.provider.Settings.System.SCREEN_BRIGHTNESS - String that holds Screen Brightness value ranging from 0 to 255.

May 4, 2014

Drawing with Canvas in Android

Before starting this tutorial please check this site https://developer.mozilla.org/enUS/docs/Web/HTML/Canvas/Drawing_graphics_with_canvas and see that you must use paths (2nd example, beginPath) rather than drawing point by point.

On your Activity
private ArrayList _graphics = new ArrayList();
private Paint mPaint;
@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(new DrawingPanel(this));
  mPaint = new Paint();
  mPaint.setDither(true);
  mPaint.setColor(0xFFFFFF00);
  mPaint.setStyle(Paint.Style.STROKE);
  mPaint.setStrokeJoin(Paint.Join.ROUND);
  mPaint.setStrokeCap(Paint.Cap.ROUND);
  mPaint.setStrokeWidth(3);
  }
On your SurfaceView
@Override
public boolean onTouchEvent(MotionEvent event) {
  synchronized (_thread.getSurfaceHolder()) {
    if(event.getAction() == MotionEvent.ACTION_DOWN){
      path = new Path();
      path.moveTo(event.getX(), event.getY());
      path.lineTo(event.getX(), event.getY());
    }else if(event.getAction() == MotionEvent.ACTION_MOVE){
      path.lineTo(event.getX(), event.getY());
    }else if(event.getAction() == MotionEvent.ACTION_UP){
      path.lineTo(event.getX(), event.getY());
      _graphics.add(path);
    }
    return true;
  }
}
@Override
public void onDraw(Canvas canvas) {
  for (Path path : _graphics) {
    //canvas.drawPoint(graphic.x, graphic.y, mPaint);
    canvas.drawPath(path, mPaint);
  }
}

Explanation

We create a path and start that path when the MotionEvent is down, or when the user first touch the screen, then add a lineTo, the x and y when the user moves his fingers.

Then stop and push the path we had build to our array of Paths.
 public boolean onTouchEvent(MotionEvent event) { .... }

 Then during the draw function we loop through the array and print them on our canvas.
 public void onDraw(Canvas canvas) { ... }

How to Generate random number in Android

Generating Random Number in Android

To generate random number in Android, class java.util.Random can be used.

This class java.util.Random provides methods that generates pseudo-random numbers of different types, such as int, long, double, and float.

It support two public constructor:
Random() - Construct a random generator with the current time of day in milliseconds as the initial state.
Random(long seed) - Construct a random generator with the given seed as the initial state.


A simple example of Alarm Service, using AlarmManager

Alarm Service in Android

AlarmManager class provides access to the system alarm services. These allow you to schedule your application to be run at some point in the future. When an alarm goes off, the Intent that had been registered for it is broadcast by the system, automatically starting the target application if it is not already running. 

In this exercise, a scheduled alarm of 10 seconds will start a service, MyAlarmService. 

Modify main.xml to have two button to start and cancel the alarm.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:id="@+id/startalarm"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Start"
/>

<Button
android:id="@+id/cancelalarm"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Cancel"
/>

</LinearLayout>

ProgressBar running in AsyncTask

ProgressBar in Android

It's a exercise of a Horizontal ProgressBar which running in a background AsyncTask.

Modify main.xml to have a button to start the progress, and the ProgressBar.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 >
<TextView
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="@string/hello"
 />
<Button
android:id="@+id/playvideoplayer"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="- PLAY Video -"
 />
<Button
android:id="@+id/pausevideoplayer"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="- PAUSE Video -"
 />
<SurfaceView
android:id="@+id/surfaceview"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 />
</LinearLayout>

May 2, 2014

AndroidSpeech: Android can speak!

A new feature, Text-To-Speech (TTS), have been introduced in version 1.6 of the Android platform. Also known as 'speech synthesis', TTS enables Android device to 'speak' text of different languages.

it's a very simple code to make Android speech. It can speech only.

Create a Android Application, with Target platform 1.6, API Level 4. Modify the code as following.

AndroidSpeech.java


package com.kais.AndroidSpeech;

import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;

public class AndroidSpeech extends Activity implements OnInitListener{

TextToSpeech myTTS;

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.main);
  
     myTTS = new TextToSpeech(this, this);
 }

@Override
public void onInit(int status) {
// TODO Auto-generated method stub

String myText1 = "Hello Android!";
       String myText2 = "I can speech.";
       myTTS.speak(myText1, TextToSpeech.QUEUE_FLUSH, null);
       myTTS.speak(myText2, TextToSpeech.QUEUE_ADD, null);
}

@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
myTTS.shutdown();
}
}

For more details of Android Text-To-Speech, refer to:
Android Developers Blog: An introduction to Text-To-Speech in Android: "We've introduced a new feature in version 1.6 of the Android platform: Text-To-Speech (TTS). Also known as 'speech synthesis', TTS enables your Android device to 'speak' text of different languages."

Uses Tabs to navigate between different views, TabWidget

Using TabWidget in Android

A TabWidget offers the ability to easily draw an interface that uses tabs to navigate between different views.



Start a new Android Application, named AndrodTab extends TabActivity and modify the xml file as below.


May 1, 2014

Implement Android MP3 Player using MediaPlayer

MediaPlayer in Android

MediaPlayer class can be used to control playback of audio/video files and streams. It is a example to implement MP3 Player using MediaPlayer. Please note that you have to keep follow the State Diagram, otherwise IIlegalStateException will be thrown.


Create a new Android Project in Eclipse, using the auto-generated code extend from ActionBarActivity.
The mp3 file is stored in /res/raw/vespers.mp3. Filename match with the following code in initMediaPlayer().

Working With Android Contacts (Part 2)

Gluing together (API 2.0 and API 1.6 & Before)

To put this together into an application there are a few glue pieces that need to be setup along with creating classes to manage accessing the data. First we need to create a set of classes to hold the data. Also we'll create a class to handle 2.0 API calls and a class to handle 1.6 and earlier API calls. There's also a wrapper class that determines and loads the proper class.
Contact Data Classes
The contact classes are a series of classes to hold a list of contacts. The list is stored in the class ContactList that maintains an ArrayList of Contacts. The Contact objects are represented in the Contact class. The contact class stores all the data from the Android contact record. In addition to the ContactList and Contact classes there are specialized classes to represent some of the record data.
We will create classes to represent the address and email. Most of these classes are mere data storage classes with variables and getter/setters.

ContactList
The ContactList class is a very basic class designed to hold an ArrayList of instances of the Contact class below. We've left this class very plain and ready to be expanded to suit your needs. 

package com.kais.android.ContactAPI.objects;
import java.util.ArrayList;
 public class ContactList {
 private ArrayList<Contact> contacts = new ArrayList<Contact>();
 public ArrayList<Contact> getContacts() {
   return contacts;
  }
 public void setContacts(ArrayList<Contact> contacts) {
   this.contacts = contacts;
  }
  public void addContact(Contact contact) {
   this.contacts.add(contact);
  }
   public ContactList() {
   }
  }

Working With Android Contacts (Part 1)

Introduction To Android Contacts

Learn to work with the Android contacts database. Basic knowledge of accessing SQLite in Android along with using Cursors is expected. See the Android SQLite and Cursor Article for more information. Google changed the contacts database moving from 1.x to 2.0 versions of Android. This tutorial will be broken into 2 sections. First covering accessing contacts in Android 2.0 and  Android 1.6 & before. Third we'll glue it all together with a class that abstracts specific classes for each version and a set of classes to manage the data from the contact records for that tutorial click here.

API For 1.6 and Before

Granting Access
Before an application can query the contact records access must be granted through the AndroidManifest.xml file stored in the root of the project. Add the following uses-permission belows the uses-sdk statement. 
<uses-permission android:name="android.permission.READ_CONTACTS" />
Querying the contact database
Retrieving Contact Details
Basic contact information stored in Contacts table with detailed information stored in individual tables for normalization. In Android 1.x to query the base contact records the URI to query is stored in People.CONTENT_URI. 
package com.kais.TestContacts;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.Contacts;
import android.provider.Contacts.People;

public class TestContacts extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ContentResolver cr = getContentResolver();
        Cursor cur = cr.query(People.CONTENT_URI, 
   null, null, null, null);
        if (cur.getCount() > 0) {
      while (cur.moveToNext()) {
          String id = cur.getString(cur.getColumnIndex(People._ID));
          String name = cur.getString(cur.getColumnIndex(People.DISPLAY_NAME));
      }
        }
    }
}
Start off with the standard view loading. Then we create a ContentResolver instance that will be used to query the SQLite database that stores the contacts. The ContentResolver query returns a Cursor instance that holds the contact records queried from the database. Then take the ID field from the contact record and store it in the string id and take the DISPLAY_NAME field and place it in the string name. For more information about cursors see the Android Cursor Tutorial.

Accessing Data with Android Cursors (Part 2)

Retrieving Data

Retrieving data from SQLite databases in Android is done using Cursors. The Android SQLite query method returns a Cursor object containing the results of the query. To use Cursors android.database.Cursor must be imported.

About Cursor

Cursors store query result records in rows and grant many methods to access and iterate through the records. Cursors should be closed when no longer used, and will be deactivated with a call to Cursor.deactivate() when the application pauses or exists. On resume the Cursor.requery() statement is executed to re-enable the Cursor with fresh data. These functions can be managed by the parent Activity by calling startManagingCursor(). 

package com.kais.TestingData;

import java.util.Locale;

import android.app.Activity;
import android.os.Bundle;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class TestingData extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        SQLiteDatabase db;
        
        db = openOrCreateDatabase(
         "TestingData.db"
         , SQLiteDatabase.CREATE_IF_NECESSARY
         , null
         );
        db.setVersion(1);
        db.setLocale(Locale.getDefault());
        db.setLockingEnabled(true);
        
        Cursor cur = db.query("tbl_countries", 
         null, null, null, null, null, null);
        
        cur.close();
    }
}

Open the database as before. The query performed will return all records from the table tbl_countries. Next we'll look at how to access the data returned.

}