Payday Loan Payday Loan

Archive for March, 2011

Work with services in Android

Today, i want to show you how services works. They can be used to make some things at regular intervals of time. You can check for updates of data, gps location, and other.

A service must be declared in .Manifest like an Activity.

<service android:name=".MyService"/>

Code must contain a Timer and class MyService must extends Service like in the example:

public class MyService extends Service {
 
private Timer t1 = new Timer();
 
protected void onCreate() {
 
super.onCreate();
 
startingservice();
 
}
 
}

Now i will show you the method startingservice().

private void startingservice() {
 
t1.scheduleAtFixedRate( new TimerTask() {
 
public void run() {
 
//Your task repeated at "INTERVAL"
 
}
 
}, 0, INTERVAL);
 
; }

At every INTERVAL(that is expressed in seconds) your task is executed by this service that runs in background once the service is started.
If you want to kill this service you will need the following method.
You can call this method on the click of a button, or after certain time when you don’t need the service anymore.
You can call it also at onDestroy() method, that means the service will stop once the app will be closed.
I will just show you the method stopingservice()

private void stopservice() {
if (t1 != null){
t1.cancel();
}
}
||||| 0 I Like It! |||||

Use TextToSpeach in your Android App

Hi, I wanna show you how you can use the capability of Android phones to speach any text.
You don’t need to be an engineer of sound or something like this. This can be done VERY easy using Android API classes.
So you need just to give users an EditText widget. You grab the text inputed like this:

String myText= edittext.getText().toString();

Now you have in variable string the inputed user text and you need to “speak it”.
You create a new project in android and in the main class will look like this:

package com.androidgenuine.texttospeach;
 
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
 
public class Main extends Activity implements OnInitListener
{
 
	private TextToSpeech mytts;
 
 
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 
        mytts = new TextToSpeech(this, this);
    }
 
	@Override
	public void onInit(int init) {
String myText="My first String speach";//here you can replace this example with the text grabbed from 
//an EditText		
if (init == TextToSpeech.SUCCESS)
		{
			mytts.speak(myText, TextToSpeech.QUEUE_FLUSH, null);
		}
	}

Do not forget that users must have installed TextToSpeach library from Market.

||||| 0 I Like It! |||||

I have searched a lot through the internet, to find and put together a method to make apps working on all devices.
In fact i have managed to resolve this for only 3 screen sizes: 320×480 at 160dpi…
480×854 or 480×800 at 240 dpi and Galaxy tab resolution 640×1024 360dpi.
For this to work, first you will need to put in the manifest the following code, that will allow supporting
of multiple screens:

After you’ve done this, you will need the following folders created on your res folder.

In drawable-mdpi, you will put the graphics for 320×480 sized devices.
In drawable-hdpi, you will put graphics for 480×854 or 480×800 or 640×1024.
Graphics must be optimized for 640×1024, because for 480×854, you can resize it in the folder layout-normal-hdpi, where you can control the size of the graphics.
Now in layout-normal-mdpi will be main.xml let’s say.
This will be the layout for the 320×480 devices. Here you can customize it as you wish. Nothing that you make here will not happen for other devices.
In layout-normal-hdpi will be same a main.xml
But now this screen is for 480×854 devices.
You can do here your layout as you wish. Even is called main.xml(same as above), all you make here will be displayed only on 480×854 screens.
In layout-large-hdmi you can modify and adapt the layout for the Samsung Galaxy Tab.(640×1024)

I think this is clear and helped you. If you have questions, please register and ask.

||||| 0 I Like It! |||||

I have found this software that seems to be a very helpfull tool in developing any kind of apps. Android, iPhone, or Windows apps you can do all of that without knowledge of programming with this very helpfull tool.
There are lots of tutorials and projects ready-made just to show you how easy you can develop Android apps, and publish them.

Welcome to Appcelerator from Appcelerator Video Channel on Vimeo.

||||| 0 I Like It! |||||

Use GPS to get coordinates in Android

I will show you how you can get coordinates from GPS sensor of the android device.
First you need to add permission to use gps to the Manifest file .
This is the permission:

<uses-permission android:name=“android.permission.ACCESS_FINE_LOCATION></uses-permission>

Now i will show you class UseGps.java.
1. You need to create a project called UseGps, then set Main class UseGps.java, package name:
androidgenuine.Tutorial.Gps

package androidgenuine.Tutorial.Gps;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;
public class UseGps extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/* Use the LocationManager class to obtain GPS locations */
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
}
/* Class My Location Listener */
public class MyLocationListener implements LocationListener
{
@Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
String Text = “My current location is:+
“Latitud =+ loc.getLatitude() +
“Longitud =+ loc.getLongitude();
Toast.makeText( getApplicationContext(),
Text,
Toast.LENGTH_SHORT).show();
}
 
@Override
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(),
“Gps Disabled”,
Toast.LENGTH_SHORT ).show();
}
 
@Override
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(),
“Gps Enabled”,
Toast.LENGTH_SHORT).show();
}
 
@Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
 
}
 
}/* End of Class MyLocationListener */
}/* End of UseGps Activity */

You should get something like this:

||||| 0 I Like It! |||||

How to save apps to sdcard in Android

I will show you how you can save data of your app in the external SDCARD.
This feature is brought with the API 8. So if you make apps for minimum API version 8, you can use the following
code for saving large content of apps to SDCARD.
Below API Level 8 such dedicated directory is not available, only the sdcard directory can be queried by the getExternalStorageDirectory() method. It is recommended to store files in the /Android/data/
/files/ directory under the sd card, because for users with a 2.2 system this directory will be still deleted on uninstall.

Environment.getExternalStorageDirectory().toString()+”/data/”+getPackageName()+”/files/”;

||||| 0 I Like It! |||||

How to make a countdown Timer in Android.

The following code will show you how to make a countdown Timer in Android:
We create class MyCount in The Main class called Counting.
We instantiate MyCount class and tell it how many seconds to countdown.
In the method onThick of the MyCount class we update a TextView that is
in the layout counting.xml with id TextView01.
The layout looks like this:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout  xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"  android:background="#000000" android:layout_height="fill_parent">
<TextView android:id="@+id/TextView01" android:layout_width="wrap_content"
 android:layout_height="wrap_content" android:text="0" android:textColor="#ffff00" 
android:textStyle="bold" android:textSize="15dip"></TextView> </RelativeLayout>


Main class called Counting.java looks like this:

public class Counting extends Activity{
final MyCount counter = new MyCount(12000,1000);//this means that we count from 12.000 to 0 with 1000ms
per second...so it will be displayed...12...11...10...etc
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.counting);
MyCount counter = new MyCount(12000,1000);//instantiate counter
counter.start();//counter start as soon as app is opened...you can put this in a OnClickListener also.
}
 
public class MyCount extends CountDownTimer{
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onFinish() {
TextView scor = (TextView)findViewById(R.id.TextView01);
 
scor.setText("0");//this is the message displayed at the finish of the counting...can be Game Over ..etc..
 
}
@Override
public void onTick(long millisUntilFinished) {
TextView scor = (TextView)findViewById(R.id.TextView01);
scor.setText(String.valueOf(millisUntilFinished/1000));
//here we update the text with seconds until 0.
}}

 

||||| 0 I Like It! |||||

You can use our Forum for any problems that you may have.

||||| 0 I Like It! |||||

How to record sound in Android!

You can record sounds using a helper class called AudioRecorder.java.
This class must be copied as is in your project and you need to modify the package name according to your
project.

package com.customsounds;
 
import java.io.File;
import java.io.IOException;
 
import android.media.MediaRecorder;
import android.os.Environment;
 
public class AudioRecorder {
 
final MediaRecorder recorder = new MediaRecorder();
final String path;
 
/**
* Creates a new audio recording at the given path (relative to root of SD card).
*/
public AudioRecorder(String path) {
this.path = sanitizePath(path);
}
 
private String sanitizePath(String path) {
if (!path.startsWith("/")) {
path = "/" + path;
}
if (!path.contains(".")) {
path += ".3gp";
}
return Environment.getExternalStorageDirectory().getAbsolutePath() + path;
}
 
/**
* Starts a new recording.
*/
public void start() throws IOException {
String state = android.os.Environment.getExternalStorageState();
if(!state.equals(android.os.Environment.MEDIA_MOUNTED))  {
throw new IOException("SD Card is not mounted.  It is " + state + ".");
}
 
// make sure the directory we plan to store the recording in exists
File directory = new File(path).getParentFile();
if (!directory.exists() &amp;&amp; !directory.mkdirs()) {
throw new IOException("Path to file could not be created.");
}
 
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(path);
recorder.prepare();
recorder.start();
}
 
/**
* Stops a recording that has been previously started.
*/
public void stop() throws IOException {
recorder.stop();
recorder.release();
}
 }

You can use this class by instantiation of the class. So please pay attention to the Main Class in which we will record a sound. Main.java:

public class Main extends Activity {
MediaPlayer mp=new MediaPlayer();
 
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
 
setContentView(R.layout.recordingstudio);
ImageButton mic=(ImageButton)findViewById(R.id.ImageButton02);
final ImageButton play=(ImageButton)findViewById(R.id.ImageButton03);
final ImageButton stop=(ImageButton)findViewById(R.id.ImageButton04);
final AudioRecorder recorder = new AudioRecorder("/audiometer/sound1");//here is the path
to sdcard where we will save the recording
mic.setOnClickListener(new OnClickListener(){
 
@Override
public void onClick(View v) {
 
Toast.makeText(RecordingStudio.this,"Recording started...",Toast.LENGTH_LONG).show();
try {
recorder.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
 
}});
play.setOnClickListener(new OnClickListener(){
 
@Override
public void onClick(View v) {
 
try {
recorder.stop();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
playSound("/sdcard/audiometer/sound1.3gp");
Toast.makeText(RecordingStudio.this,"Playing...",Toast.LENGTH_LONG).show();
}});
stop.setOnClickListener(new OnClickListener(){
 
@Override
public void onClick(View v) {
Toast.makeText(RecordingStudio.this,"Recording stopped...",Toast.LENGTH_LONG).show();
mp.reset();
 
}});
}
}

IMPORTANT!!! Please do not forget to add the following permission on the Manifest file so that you can
have acces to record feature of the device.

<uses-permission android:name=”android.permission.RECORD_AUDIO” />This must be placed below the </application> tag</h3>

||||| 0 I Like It! |||||

The following function will show you how to set a sound as ringtone on android.
You need the following permissions set on Manifest file:

<uses-permission android:name="android.permission.WRITE_SETTINGS" ></uses-permission>

The xml below contains a button. On pressing this button will call the function to save
the sound on sdcard and set it as ringtone. Code for ringtone.xml

<?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"    android:background="@drawable/bg">
<ImageButton android:id="@+id/ImageButton01" 
android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:background="@drawable/transparent" 
android:layout_marginLeft="180dip" 
android:layout_marginTop="200dip"></ImageButton>
<TableLayout android:id="@+id/TableLayout01" 
android:layout_height="wrap_content" android:layout_marginTop="20dip" 
android:layout_width="fill_parent"><TableRow android:id="@+id/TableRow01" 
android:layout_height="wrap_content" 
android:layout_width="fill_parent">
<Button android:id="@+id/Button01" 
android:layout_height="wrap_content"
 android:layout_gravity="center"
 android:layout_width="fill_parent" android:layout_marginLeft="65dip"
 android:text="Set as Ringtone!"></Button></TableRow>
</TableLayout></LinearLayout>

The following code is the function and the Ringtone class

package com.airhorn;
 
import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
 
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
 
public class Ringtone extends Activity {
MediaPlayer mp=new MediaPlayer();
 
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ringtone);
Button a=(Button)findViewById(R.id.Button01);
 
a.setOnClickListener(new OnClickListener(){
 
@Override
public void onClick(View v) {
if(saveas(R.raw.sound)){
Toast.makeText(Ringtone.this, "The sound was set as ringtone!", Toast.LENGTH_LONG).show();
};
 
}});
ImageButton w=(ImageButton)findViewById(R.id.ImageButton01);
w.setOnClickListener(new OnClickListener(){
 
@Override
public void onClick(View arg0) {
 
playSound(R.raw.sound);
}});
}
 
public void playSound(int fileId) {
MediaPlayer mp;
 
try {
mp = MediaPlayer.create(this, fileId);
mp.start();
mp.setOnCompletionListener(new OnCompletionListener() {
 
@Override
public void onCompletion(MediaPlayer mp) {
mp.release();
mp = null;
 
}
});
} catch (Exception exception) {
}
 
}
public boolean saveas(int ressound){
byte[] buffer=null;
InputStream fIn = getBaseContext().getResources().openRawResource(ressound);
int size=0;
 
try {
size = fIn.available();
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
 
String path="/sdcard/sounds/";
String filename="mysound"+".mp3";
 
boolean exists = (new File(path)).exists();
if (!exists){new File(path).mkdirs();}
 
FileOutputStream save;
try {
save = new FileOutputStream(path+filename);
save.write(buffer);
save.flush();
save.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
 
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+filename)));
 
File k = new File(path, filename);
 
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "exampletitle");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
values.put(MediaStore.Audio.Media.ARTIST, "cssounds ");
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);
values.put(MediaStore.Audio.Media.IS_ALARM, false);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
 
//Insert it into the database
Uri newUri= this.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()), values);
 
RingtoneManager.setActualDefaultRingtoneUri(
this,
RingtoneManager.TYPE_RINGTONE,
newUri
);
return true;
}
 
 
 
}

I hope this can help you, so that you can set as ringtone any sound that you want in Android. If you see in this code, there are two buttons, one for playing the sound, and one for setting the sound as ringtone, so use both of functions for whatever you need.

||||| 1 I Like It! |||||

Search

Popular

Sponsors