In My application, I am using thread to show the splash screen. . .
But i have also given the Android Licensing to My Application. Which also uses the thread. . .
But While i am installing the Application it runs once..
if i again open it then it got crash. where is the problem ???
the code is as below :
package com.EMTPrep.Paramedic.app;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings.Secure;
import android.view.Window;
import com.android.vending.licensing.AESObfuscator;
import com.android.vending.licensing.LicenseChecker;
import com.android.vending.licensing.LicenseCheckerCallback;
import com.android.vending.licensing.ServerManagedPolicy;
import com.EMTPrep.Paramedic.app.R;
public class SplashActivity extends Activity
{
private static boolean DEBUG = false;
private static int DURATION;
private Handler splashHandler;
private Runnable launcherRunnable;
private LicenseCheckerCallback mLicenseCheckerCallback;// for the License
private LicenseChecker mChecker;// for the License
// === A handler on the UI thread.
private Handler mHandler;
private static final String BASE64_PUBLIC_KEY = "I have puted the Licensing code here";//// for the License
// === Generate your own 20 random bytes, and put them here.
private static final byte[] SALT = new byte[]
{
-46, 65, 90, -128, -13, -57, 74, -64, 51, 66, -85, -67, 89, -114, -36, 113, 77, 32, -64,
89
}; // for the License
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.splash);
mHandler = new Handler();
// Try to use more data here. ANDROID_ID is a single point of attack.
String deviceId = Secure.getString(getContentResolver(), Secure.ANDROID_ID);// for the License
// === Library calls this when it's done.
mLicenseCheckerCallback = new MyLicenseCheckerCallback();// for the License
// === Construct the LicenseChecker with a policy.
mChecker = new LicenseChecker(this, new ServerManagedPolicy(this,new AESObfuscator(SALT, getPackageName(), deviceId)),// for the License
BASE64_PUBLIC_KEY);// for the License
doCheck();// for the License
DURATION = Integer.valueOf(getString(R.string.splash_duration));
splashHandler = new Handler();
// ================ Main Code of the Application
// launcherRunnable = new Runnable() {
// #Override
// public void run() {
// Intent i = new Intent(SplashActivity.this, MainMenuActivity.class);
// i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// startActivity(i);
// SplashActivity.this.finish();
// }
// };
// if (DEBUG)
// {
// splashHandler.post(launcherRunnable);
// }
// else
// splashHandler.postDelayed(launcherRunnable, DURATION);
//
}
protected Dialog onCreateDialog(int id) //// for the License
{
// 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=" + getPackageName()));
startActivity(marketIntent);
}
})
.setNegativeButton(R.string.quit_button, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.create();
}
private void displayResult(final String result) { // for the License
mHandler.post(new Runnable() {
public void run() {
// mStatusText.setText(result);
setProgressBarIndeterminateVisibility(false);
//mCheckLicenseButton.setEnabled(true);
}
});
}
private class MyLicenseCheckerCallback implements LicenseCheckerCallback // for the License
{
public void allow()
{
if (isFinishing())
{
// Don't update UI if Activity is finishing.
return;
}
// Should allow user access.
launcherRunnable = new Runnable()
{
#Override
public void run()
{
Intent i = new Intent(SplashActivity.this, MainMenuActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
SplashActivity.this.finish();
}
};
if (DEBUG)
{
splashHandler.post(launcherRunnable);
}
else
splashHandler.postDelayed(launcherRunnable, DURATION);
displayResult(getString(R.string.allow));
}
public void dontAllow()
{
if (isFinishing())
{
// Don't update UI if Activity is finishing.
return;
}
displayResult(getString(R.string.dont_allow));
// Should not allow access. An app can handle as needed,
// typically by informing the user that the app is not licensed
// and then shutting down the app or limiting the user to a
// restricted set of features.
// In this example, we show a dialog that takes the user to Market.
showDialog(0);
}
public void applicationError(ApplicationErrorCode errorCode)
{
if (isFinishing())
{
// Don't update UI if Activity is finishing.
return;
}
// 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.
String result = String.format(getString(R.string.application_error), errorCode);
displayResult(result);
}
}
private void doCheck()// for the License
{
//mCheckLicenseButton.setEnabled(false);
setProgressBarIndeterminateVisibility(true);
//mStatusText.setText(R.string.checking_license);
mChecker.checkAccess(mLicenseCheckerCallback);
}
#Override // for the License
protected void onDestroy() {
super.onDestroy();
mChecker.onDestroy();
}
}
I think there might be the problem in thread. . . Please help me to solve it. . Thanks
Please help me in this. . .
And let me tell while i am able to run the application only at once. . .
Thanks in advance.
Can you try splashHandler.postDelayed(new Runnable(), DURATION); ?
and put it up to fields private Handler splashHandler = new Handler();
Related
i am trying out below code everything works fine when net is connected
here is the workflow
there is a main activity from where on button click this activity should open
it would do the parsing part and then go to next list activity.in case there is a back press or this activity is closed the asynctask should stop using
loader.cancel(true);
this would work perfectly if net is available and tested the issue happens when dont have internet connection
the alert box shows and it goes to the first activity then it crashes
i want the alert box to show and app should not crash and go back to first -->mainactivity
i have refereed this
http://techiedreams.com/android-simple-rss-reader/
How to end AsyncTask onBackPress()
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import com.parser.DOMParser;
import com.parser.RSSFeed;
public class SplashActivity extends Activity {
//private String RSSFEEDURL = "http://www.mobilenations.com/rss/mb.xml";
RSSFeed feed;
private AsyncLoadXMLFeed loader;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Intent i = getIntent();
int position = i.getExtras().getInt("position");
String[] country = i.getStringArrayExtra("country");
//Toast.makeText(getApplicationContext(), country[position], Toast.LENGTH_SHORT).show();
//Toast.makeText(getApplicationContext(), country[position], Toast.LENGTH_SHORT).show();
String name = i.getStringExtra("name");
//Toast.makeText(getApplicationContext(), name, Toast.LENGTH_SHORT).show();
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() == null) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
"Unable to reach server, \nPlease check your connectivity.")
.setTitle("TD RSS Reader")
.setCancelable(false)
.setPositiveButton("Exit",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id) {
//loader.cancel(true);
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
// Connected - Start parsing
loader = new AsyncLoadXMLFeed();
loader.execute();
//new AsyncLoadXMLFeed().execute();
}
}
private class AsyncLoadXMLFeed extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
// Obtain feed
DOMParser myParser = new DOMParser();
Intent i = getIntent();
int position = i.getExtras().getInt("position");
String[] country = i.getStringArrayExtra("country");
String name = i.getStringExtra("name");
//feed = myParser.parseXml(RSSFEEDURL);
feed = myParser.parseXml("http://"+name+".blogspot.com//feeds/posts/default/-/" + country[position] + "?alt=rss");
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Bundle bundle = new Bundle();
bundle.putSerializable("feed", feed);
// launch List activity
Intent intent = new Intent(SplashActivity.this, ListActivity.class);
intent.putExtras(bundle);
startActivity(intent);
// kill this activity
finish();
}
}
#Override
public void onBackPressed() {
finish();
}
#Override
public void onDestroy(){
super.onDestroy();
// Cancel the task
loader.cancel(true);
}
My guess it crashes with NullPointerException.
It is because if you don't have network connectivity you don't create AsyncLoadXMLFeed instance.
So when onDestroy() happened and you call loader.cancel(true); it throws this Exception.
finally did this
thanks anatol needed to check loader != null
#Override
public void onDestroy(){
super.onDestroy();
// Cancel the task
if(loader != null && loader.getStatus() != AsyncTask.Status.FINISHED) {
loader.cancel(true);
}
//loader.cancel(true);
}
The best and simplest solution for handle this issue is that use try catch block in your onPost execute() in async task. like this
#Override
protected void onPostExecute(String s) {
try {
super.onPostExecute(s);
loading.dismiss();
}catch (Exception ex){
Toast.makeText(UserLogin.this, "Something is going wrong, please try again!", Toast.LENGTH_LONG).show();
}
}
simply this will prevent your app from crash.
Here is my code:
Some time I get Application error :3 or :6 and some time I get application not licensed dialog.
public class MainActivity extends Activity {
private static final String BASE64_PUBLIC_KEY = "my public key";
// Generate your own 20 random bytes, and put them here.
private static final byte[] SALT = new byte[] {
-43, 12, 76, -124, -101, -57, 74, -64, 51, 88, -95, -45, 77, -117, -36, -113, -11, 32, -64,
89
};
private TextView mStatusText;
private Button mCheckLicenseButton;
private LicenseCheckerCallback mLicenseCheckerCallback;
private LicenseChecker mChecker;
// A handler on the UI thread.
private Handler mHandler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.main);
mStatusText = (TextView) findViewById(R.id.status_text);
mCheckLicenseButton = (Button) findViewById(R.id.check_license_button);
mCheckLicenseButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
doCheck();
}
});
mHandler = new Handler();
// Try to use more data here. ANDROID_ID is a single point of attack.
String deviceId = Secure.getString(getContentResolver(), 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);
doCheck();
}
protected Dialog onCreateDialog(int id) {
final boolean bRetry = id == 1;
return new AlertDialog.Builder(this)
.setTitle(R.string.unlicensed_dialog_title)
.setMessage(bRetry ? R.string.unlicensed_dialog_retry_body : R.string.unlicensed_dialog_body)
.setPositiveButton(bRetry ? R.string.retry_button : R.string.buy_button, new DialogInterface.OnClickListener() {
boolean mRetry = bRetry;
public void onClick(DialogInterface dialog, int which) {
if ( mRetry ) {
doCheck();
} else {
Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(
"http://play.google.com/store/apps/details?id=com.android.SendEmail"));
startActivity(marketIntent);
}
}
})
.setNegativeButton(R.string.quit_button, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
}).create();
}
private void doCheck() {
mCheckLicenseButton.setEnabled(false);
setProgressBarIndeterminateVisibility(true);
mStatusText.setText(R.string.checking_license);
mChecker.checkAccess(mLicenseCheckerCallback);
}
private void displayResult(final String result) {
mHandler.post(new Runnable() {
public void run() {
mStatusText.setText(result);
setProgressBarIndeterminateVisibility(false);
mCheckLicenseButton.setEnabled(true);
}
});
}
private void displayDialog(final boolean showRetry) {
mHandler.post(new Runnable() {
public void run() {
setProgressBarIndeterminateVisibility(false);
showDialog(showRetry ? 1 : 0);
mCheckLicenseButton.setEnabled(true);
}
});
}
private class MyLicenseCheckerCallback implements LicenseCheckerCallback {
public void allow(int policyReason) {
if (isFinishing()) {
// Don't update UI if Activity is finishing.
return;
}
// Should allow user access.
displayResult(getString(R.string.allow));
}
public void dontAllow(int policyReason) {
if (isFinishing()) {
// Don't update UI if Activity is finishing.
return;
}
displayResult(getString(R.string.dont_allow));
// Should not allow access. In most cases, the app should assume
// the user has access unless it encounters this. If it does,
// the app should inform the user of their unlicensed ways
// and then either shut down the app or limit the user to a
// restricted set of features.
// In this example, we show a dialog that takes the user to Market.
// If the reason for the lack of license is that the service is
// unavailable or there is another problem, we display a
// retry button on the dialog and a different message.
displayDialog(policyReason == Policy.RETRY);
}
public void applicationError(int errorCode) {
if (isFinishing()) {
// Don't update UI if Activity is finishing.
return;
}
// 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.
String result = String.format(getString(R.string.application_error), errorCode);
displayResult(result);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
mChecker.onDestroy();
}
Error Code 6 means your missing the permission to check for licensing from your application manifest.
<uses-permission android:name="com.android.vending.CHECK_LICENSE" />
Error Code 3 means that the app isn't on the Google marketplace so their license server can't determine if they are supposed to have a license or not yet.
I am having trouble implementing Licensing using the licensing lib. My code alway seems to go to the "check network access" part or the "don't allow" part. I am testing using the method mentioned in the Setting Up for Licensing article (http://developer.android.com/google/play/licensing/setting-up.html). I have the licencing bits of my code below, let me know if you need to see anything else.
Note: most of this code is from the sample app that comes with the library.
public class Reminder_list extends ListActivity {
Global variables ....
private static final String BASE64_PUBLIC_KEY = "bla,bla,bla";
// Generate your own 20 random bytes, and put them here.
private static final byte[] SALT = new byte[] {
-46, 65, 30, -118, -103, -57, 74, -14, 51, 88, -95, -45, 77, -17, -36, -113, -11, 32, -64,
19
};
private LicenseCheckerCallback mLicenseCheckerCallback;
private LicenseChecker mChecker;
// A handler on the UI thread.
private Handler mHandler;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHandler = new Handler();
String deviceId = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
// LicencingLibrary calls this when it's done.
mLicenseCheckerCallback = new MyLicenseCheckerCallback();
mChecker = new LicenseChecker(
this, new ServerManagedPolicy(this,
new AESObfuscator(SALT, getPackageName(), deviceId)),
BASE64_PUBLIC_KEY);
doCheck();
...
the rest of the stuff in the onCreate.
...
}
// this dialog is for the licence check.
protected Dialog onCreateDialog(int id) {
final boolean bRetry = id == 1;
return new AlertDialog.Builder(this)
.setTitle(R.string.unlicensed_dialog_title)
.setMessage(bRetry ? R.string.unlicensed_dialog_retry_body : R.string.unlicensed_dialog_body)
.setPositiveButton(bRetry ? R.string.retry_button : R.string.buy_button, new DialogInterface.OnClickListener() {
boolean mRetry = bRetry;
public void onClick(DialogInterface dialog, int which) {
if ( mRetry ) {
doCheck();
} else {
Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(
"market:///details?id=" + getPackageName()));
startActivity(marketIntent);
}
}
})
.setNegativeButton(R.string.quit_button, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
}).create();
}
// this is the actual method that called for the licence check.
private void doCheck() {
mChecker.checkAccess(mLicenseCheckerCallback);
}
// this is used to display the result of he licence check
private void displayResult(final String result) {
mHandler.post(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), result ,Toast.LENGTH_SHORT).show();
}
});
}
// this shows the dialog if the licence check came back with a problem. Either the user did not pay for it or we did an error.
private void displayDialog(final boolean showRetry) {
mHandler.post(new Runnable() {
#SuppressWarnings("deprecation")
public void run() {
showDialog(showRetry ? 1 : 0);//calls the dialog
}
});
}
...
...
the rest of the class
The LicenseCheckerCallback class in the main class:
// this is an internal class that should be inside the main activity that is used for license checking. The licensing lib call this when
// it is done with checking the license
private class MyLicenseCheckerCallback implements LicenseCheckerCallback {
public void allow(int policyReason) {
if (isFinishing()) {
// Don't update UI if Activity is finishing.
return;
}
// Should allow user access.
displayResult(getString(R.string.allow));
}
public void dontAllow(int policyReason) {
if (isFinishing()) {
// Don't update UI if Activity is finishing.
return;
}
displayResult(getString(R.string.dont_allow));
// Should not allow access. In most cases, the app should assume
// the user has access unless it encounters this. If it does,
// the app should inform the user of their unlicensed ways
// and then either shut down the app or limit the user to a
// restricted set of features.
// In this example, we show a dialog that takes the user to Market.
// If the reason for the lack of license is that the service is
// unavailable or there is another problem, we display a
// retry button on the dialog and a different message.
displayDialog(policyReason == Policy.RETRY);
}
public void applicationError(int errorCode) {
if (isFinishing()) {
// Don't update UI if Activity is finishing.
return;
}
// 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.
String result = String.format(getString(R.string.application_error), errorCode);
displayResult(result);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
mChecker.onDestroy();
}
}
I am using the ServerManagedPolicy . So I have not changed anything in the library files(I don't have to do I?). And I do have the in the manifest.
<uses-permission android:name="com.android.vending.CHECK_LICENSE" />
I cant work out what I am doing wrong. All of this is entirely based on the sample app.
My question is : how do I get the Licence check to work properly?
Note : If you plan on downvoting , pls tell me why.
Thanks for taking the time to read this and for any help that you can give.
Cheers.
i uploded my app with google license with correct key but when i download the app from store it gives
"This application is not licensed. Please purchase it from Android Market."
here is the code:
public class MainActivity extends Activity {
private static final String BASE64_PUBLIC_KEY = my_app_key;
// Generate your own 20 random bytes, and put them here.
private static final byte[] SALT = new byte[] {
-46, 35, 30, -128, -103, -57, 74, -64, 51, 88, -95, -45, 67, -117, -36, -113, -11, 82, -44,
29
};
private TextView mStatusText;
private LicenseCheckerCallback mLicenseCheckerCallback;
private LicenseChecker mChecker;
// A handler on the UI thread.
private Handler mHandler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.license);
mStatusText = (TextView) findViewById(R.id.status_text);
mHandler = new Handler();
// Try to use more data here. ANDROID_ID is a single point of attack.
String deviceId = Secure.getString(getContentResolver(), 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);
doCheck();
}
protected Dialog onCreateDialog(int id) {
final boolean bRetry = id == 1;
return new AlertDialog.Builder(this)
.setTitle(R.string.unlicensed_dialog_title)
.setMessage(bRetry ? R.string.unlicensed_dialog_retry_body : R.string.unlicensed_dialog_body)
.setPositiveButton(bRetry ? R.string.retry_button : R.string.buy_button, new DialogInterface.OnClickListener() {
boolean mRetry = bRetry;
public void onClick(DialogInterface dialog, int which) {
if ( mRetry ) {
doCheck();
} else {
Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(
"http://market.android.com/details?id=" + getPackageName()));
startActivity(marketIntent);
}
}
})
.setNegativeButton(R.string.quit_button, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
}).create();
}
private void doCheck() {
setProgressBarIndeterminateVisibility(true);
mStatusText.setText(R.string.checking_license);
mChecker.checkAccess(mLicenseCheckerCallback);
}
private void displayResult(final String result) {
mHandler.post(new Runnable() {
public void run() {
mStatusText.setText(result);
setProgressBarIndeterminateVisibility(false);
}
});
}
private void displayDialog(final boolean showRetry) {
mHandler.post(new Runnable() {
public void run() {
setProgressBarIndeterminateVisibility(false);
showDialog(showRetry ? 1 : 0);
}
});
}
private class MyLicenseCheckerCallback implements LicenseCheckerCallback {
public void allow(int policyReason) {
if (isFinishing()) {
// Don't update UI if Activity is finishing.
return;
}
// Should allow user access.
finish();
startActivity(new Intent(MainActivity.this,first.class));
}
public void dontAllow(int policyReason) {
if (isFinishing()) {
// Don't update UI if Activity is finishing.
return;
}
displayResult(getString(R.string.dont_allow));
// Should not allow access. In most cases, the app should assume
// the user has access unless it encounters this. If it does,
// the app should inform the user of their unlicensed ways
// and then either shut down the app or limit the user to a
// restricted set of features.
// In this example, we show a dialog that takes the user to Market.
// If the reason for the lack of license is that the service is
// unavailable or there is another problem, we display a
// retry button on the dialog and a different message.
displayDialog(policyReason == Policy.RETRY);
}
public void applicationError(int errorCode) {
if (isFinishing()) {
// Don't update UI if Activity is finishing.
return;
}
// 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.
String result = String.format(getString(R.string.application_error), errorCode);
displayResult(result);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
mChecker.onDestroy();
}
}
Are you using the same id that you uploaded it with?
I'm new to Android development, Eclipse and Java (done mostly .Net and IVR programming up till now), so when I tried to compile and run a sample app I found for TTS on the Droid, I wasn't surprised that I got a runtime error right away. The error is:
dalvikvm Failed resolving com/sample/TTSapp/AndroidTTSapp; interface 4 'android/speech/tts/TextToSpeech$OnInitListner;'
I suppose the OnInitListner method must be in one of the classes that was installed when I installed the Android SDK (release 1.6 R1 I believe), but I'm not sure how to import the associated class module into the current program. I can't find a speech/tts/TextToSpeech directory anywhere on my system. Do I need to download this directory from somewhere? Following is the Java source code for the demo TTS program I'm trying to run:
package com.sample.TTSApp;
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.sample.TTSApp.R;
import java.util.Locale;
import java.util.Random;
public class AndroidTTSapp extends Activity implements
TextToSpeech.OnInitListener
{
private static final String TAG = "TextToSpeechDemo";
private TextToSpeech mTts;
private Button mAgainButton;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Initialize text-to-speech. This is an asynchronous operation.
// The OnInitListener (second argument) is called after initialization completes.
// Instantiate TextToSpeech.OnInitListener
mTts = new TextToSpeech(this, this);
mAgainButton = (Button) findViewById(R.id.again_button);
mAgainButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
sayHello();
}
});
}
#Override
public void onDestroy()
{ // Don't forget to shutdown!
if (mTts != null)
{
mTts.stop();
mTts.shutdown();
}
super.onDestroy();
}
// Implements TextToSpeech.OnInitListener.
public void onInit(int status)
{
// status can be either TextToSpeech.SUCCESS or TextToSpeech.ERROR.
if (status == TextToSpeech.SUCCESS)
{
int result = mTts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED)
{
// Language data is missing or the language is not supported.
Log.e(TAG, "Language is not available.");
}
else
{
// Check the documentation for other possible result codes. For example, the language may be available for the locale
// but not for the specified country and variant.
// The TTS engine has been successfully initialized. Allow the user to press the button for the app to speak again.
mAgainButton.setEnabled(true);
// Greet the user
sayHello();
}
}
else
{
// Initialization failed.
Log.e(TAG, "Could not initialize TextToSpeech.");
}
};
private static final Random RANDOM = new Random();
private static final String[] HELLOS =
{
"Hello World", "This is Text to speech demo by Zahid Shaikh"
};
private void sayHello()
{
// Select a random hello.
int i =0;
int helloLength = HELLOS.length;
String hello = HELLOS[i];
i++;
if(i == helloLength) i =0;
mTts.speak(hello,TextToSpeech.QUEUE_FLUSH,null);
}
}
Thanks in advance for any assitance anyone can give a beginner like myself.
Don Tilley
On device or emulator in */system/tts/lang_pico/* must be tts-lang-files (*.bin).
It's init TTS example:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
........
........
initTTS();
}
private void initTTS() {
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == MY_DATA_CHECK_CODE) {
if(resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
mTts = new TextToSpeech(this, this);
} else {
Intent installIntent = new Intent();
installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
}
}
}
public void onInit(int status) {
if(status == TextToSpeech.SUCCESS) {
int result = mTts.setLanguage(Locale.US);
if(result == TextToSpeech.LANG_AVAILABLE
|| result == TextToSpeech.LANG_COUNTRY_AVAILABLE) {
mTts.speak("Start system", TextToSpeech.QUEUE_FLUSH, null);
}
}
}