I'm new to programming, and I'm creating an app with texttospeech and I wanna be able to share the tts output as an audio file to other apps like whatsapp for example. I have heard about synthesizetofile() but I don't know anything about it.
Here's my code:
Main Activity class
package com.example.texttospeech;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
import java.io.File;
import java.util.HashMap;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
EditText etInput;
Button btDone, btShare;
MediaPlayer mMediaPlayer;
TextToSpeech textToSpeech;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etInput = findViewById(R.id.et_input);
btDone = findViewById(R.id.bt_done);
btShare = findViewById(R.id.btn_share);
textToSpeech = new TextToSpeech(getApplicationContext()
, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int i) {
if (i == TextToSpeech.SUCCESS) {
int lang = textToSpeech.setLanguage(Locale.ENGLISH);
}
}
});
btDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//String s = etInput.getText().toString();
//int speech = textToSpeech.speak(s, TextToSpeech.QUEUE_FLUSH, null);
HashMap<String, String> map = new HashMap<>();
map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "speak");
File myDir = getApplicationContext().getFilesDir();
String documents = "documents/data";
File documentsFolder = new File(myDir, documents);
documentsFolder.mkdir();
String path = "/"+documents+"/"+"test.mp3";
textToSpeech.synthesizeToFile("text to speech to audio", map, path);
mMediaPlayer = new MediaPlayer();
try{
mMediaPlayer.setDataSource(path);
mMediaPlayer.prepare();
}
catch (Exception e) {
Log.d("ROYs", e.toString());
e.printStackTrace();
}
mMediaPlayer.start();
}
});
btShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle bundle = new Bundle();
Intent intent = new Intent( Intent.ACTION_SEND );
intent.setType("audio/mp3");
startActivity( intent );
}
});
}
private void shareAudio()
{
Bundle bundle = new Bundle();
Intent intent = new Intent( Intent.ACTION_SEND );
intent.setType("audio/mp3");
startActivity( intent );
}
}
Anyone who helps, would be appreciated very much!
Related
I have a project, controlling a jetski from a far with a android application using Bluetooth.
I have made 2 files:
Here is the "Peripherique.java" (the Bluetooth thing):
package com.example.btjetski;
import androidx.appcompat.app.AppCompatActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Set;
public class Peripherique extends AppCompatActivity {
Button btnPaired;
ListView devicelist;
private BluetoothAdapter myBluetooth;
private Set<BluetoothDevice> pairedDevices;
public static String EXTRA_ADDRESS = "device_address";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnPaired = findViewById(R.id.button);
devicelist = findViewById(R.id.listView);
myBluetooth = BluetoothAdapter.getDefaultAdapter();
if (myBluetooth == null) {
Toast.makeText(getApplicationContext(), "Périphérique Bluetooth non disponible", Toast.LENGTH_LONG).show();
finish();
} else if (!myBluetooth.isEnabled()) {
Intent turnBTon = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnBTon, 1);
}
btnPaired.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
list();
}
});
}
private void list() { // écouter les périphériques BT
pairedDevices = myBluetooth.getBondedDevices();
ArrayList list = new ArrayList();
if (pairedDevices.size() > 0) {
for (BluetoothDevice bt : pairedDevices) {
list.add(bt.getName() + "\n" + bt.getAddress());
}
} else {
Toast.makeText(getApplicationContext(), "Aucun des appareils trouvés", Toast.LENGTH_LONG).show();
}
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, list);
devicelist.setAdapter(adapter);
}
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3)
{
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
Intent i = new Intent(Peripherique.this, jetControl.class);
i.putExtra(EXTRA_ADDRESS, address);
startActivity(i);
}
}
Here is jetControl.java
package com.example.btjetski;
import android.app.ProgressDialog;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import java.io.IOException;
import java.util.UUID;
public class jetControl extends AppCompatActivity {
Button buttonON1, buttonOFF1;
String address = null;
private ProgressDialog progress;
BluetoothAdapter myBluetooth = null;
BluetoothSocket btSocket = null;
private boolean isBtConnected = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent newint = getIntent();
address = newint.getStringExtra(Peripherique.EXTRA_ADDRESS); //recevoir l'adresse du périphérique BT
setContentView(R.layout.activity_jet_control);
//WIDGETS
Button buttonON1 = findViewById(R.id.buttonON1);
Button buttonOFF1 = findViewById(R.id.buttonOFF1);
setOnClickListener();
}
private void setOnClickListener() {
buttonON1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AllumerJetski1();
}
});
buttonOFF1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EteindreJetski1();
}
});
}
private void AllumerJetski1() {
if (btSocket != null) {
try {
btSocket.getOutputStream().write("A".toString().getBytes());
} catch (IOException e) {
}
}
}
private void EteindreJetski1() {
if (btSocket != null) {
try {
btSocket.getOutputStream().write("a".toString().getBytes());
} catch (IOException e) {
}
}
}
}
When the app starts, i can connect to my ESP32 but nothing happens, i should have an overlay that shows up with two buttons "ON/OFF" but nothing seems to work properly.
I thank you so much for your help.
I'm really confused on how to add from another activity I keep getting an error in this part of the code:
Emails a = new Emails(intent.getStringExtra("inputEmail"), intent.getStringExtra("inputBody"), intent.getStringExtra("inputSubject"));
So the error says "actual and formal argument lists differ in length". if anyone could help me out it would be such a huge help thank you :)
this my code:
main activity:
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private Button newEmail;
private ListView listView;
private EmailAdapter emailAdapter;
private ArrayList<Emails> emailsArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
emailAdapter = new EmailAdapter(this, emailsArrayList);
listView.setAdapter(emailAdapter);
updateList();
newEmail.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SendActivity.class);
startActivity(intent);
}
});
}
private void init(){
newEmail = (Button) findViewById(R.id.newBtn);
listView = (ListView) findViewById(R.id.list);
emailsArrayList = new ArrayList<>();
Emails emails = new Emails ();
emails.setEmails("josemari#yahey.com");
emails.setSubject("Sample Data");
emails.setBody("this is the sample data");
emailsArrayList.add(emails);
}
private void updateList()
{
Bundle bundle = getIntent().getExtras();
Intent intent = getIntent();
if(bundle != null)
{
Emails a = new Emails(intent.getStringExtra("inputEmail"), intent.getStringExtra("inputBody"), intent.getStringExtra("inputSubject"));
emailAdapter.add(a);
emailAdapter.notifyDataSetChanged();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent)
{
super.onActivityResult(requestCode, resultCode, intent);
if(requestCode == 1 && resultCode == RESULT_OK)
{
Emails a = new Emails(intent.getStringExtra("inputEmail"), intent.getStringExtra("inputBody"), intent.getStringExtra("inputSubject"));
emailAdapter.add(a);
emailAdapter.notifyDataSetChanged();
}
}
#Override
protected void onStart() {
super.onStart();
Log.d("MainActivity","onStart invoked");
}
#Override
protected void onResume() {
super.onResume();
Log.d("MainActivity","onResume invoked");
}
#Override
protected void onPause() {
super.onPause();
Log.d("MainActivity","onPause invoked");
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onRestart() {
super.onRestart();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
this is the add item activity:
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class SendActivity extends AppCompatActivity {
private Button send;
private Button discard;
private EditText email;
private EditText subject;
private EditText body;
private ArrayList<Emails> emailsArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send);
send = (Button) findViewById(R.id.sendBtn);
discard = (Button) findViewById(R.id.discardBtn);
email = (EditText) findViewById(R.id.inputEmail);
subject = (EditText) findViewById(R.id.inputSubject);
body = (EditText) findViewById(R.id.inputBody);
discard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SendActivity.this, MainActivity.class);
startActivity(intent);
}
});
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String inputEmail = email.getText().toString();
String inputSubject = subject.getText().toString();
String inputBody = body.getText().toString();
if (inputBody.isEmpty() || inputEmail.isEmpty() || inputEmail.isEmpty()){
Toast.makeText(SendActivity.this, "Please enter the following data", Toast.LENGTH_SHORT).show();
}
else {
emailsArrayList = new ArrayList<>();
Emails newEmails = new Emails ();
newEmails.setEmails(inputEmail);
newEmails.setSubject(inputSubject);
newEmails.setBody(inputBody);
emailsArrayList.add(newEmails);
Intent intent = new Intent();
getIntent().putExtra("inputEmail", inputEmail);
getIntent().putExtra("inputSubject", inputSubject);
getIntent().putExtra("inputBody", inputBody);
setResult(RESULT_OK, intent);
finish();
}
}
});
}
}
I would also change the following as well:
private void updateList()
{
Bundle bundle = getIntent().getExtras();
Intent intent = getIntent();
if(bundle != null)
{
Emails a = new Emails(intent.getStringExtra("inputEmail"), intent.getStringExtra("inputBody"), intent.getStringExtra("inputSubject"));
emailAdapter.add(a);
emailAdapter.notifyDataSetChanged();
}
}
to
private void updateList()
{
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if(bundle != null)
{
Emails a = new Emails(String)bundle.get("inputEmail"), (String)bundle.get("inputBody"), (String)bundle.get("inputSubject"));
emailAdapter.add(a);
emailAdapter.notifyDataSetChanged();
}
}
I would try this absolutley first: You may beable to use what you have and just change the Bundle bundle and Intent intent lines around in your updateList(). Again no expert but try that first and then above that second. I hope it works for you.
Here is my main file where i get u_id and other data but i pass u_id text to other activity
Mainactivity.java
package com.desktop.app;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.desktop.app.Stitle.EXTRA_TITLE;
public class MainActivity extends AppCompatActivity {
Button signup,login,learnmore ;
EditText ed1,ed2,u_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signup = (Button) findViewById(R.id.signupbutton);
learnmore = (Button) findViewById(R.id.learnmore);
login = (Button) findViewById(R.id.loginbutton);
ed1 = (EditText) findViewById(R.id.emailedittext);
u_id = (EditText) findViewById(R.id.uid);
ed2 = (EditText) findViewById(R.id.passwordedittext);
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent in = new Intent(MainActivity.this,Activity2.class);
startActivity(in);
}
});
learnmore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent in = new Intent(MainActivity.this,Activity1.class);
startActivity(in);
}
});
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = ed1.getText().toString().trim();
String password = ed2.getText().toString().trim();
final String log_id = u_id.getText().toString();
if(email.isEmpty()){
ed1.setError("Fill this field");
ed1.requestFocus();
return;
}
if(password.isEmpty()){
ed2.setError("Fill this field");
ed2.requestFocus();
return;
}
if(log_id.isEmpty()){
u_id.setError("Fill this field");
u_id.requestFocus();
return;
}
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
login();
Intent i = new Intent (MainActivity.this,fullview.class);
Bundle b =new Bundle();
b.putString("text", String.valueOf(u_id));
i.putExtras(b);
startActivity(i);
}
});
}
private void login(){
String url= "http://192.168.0.136/fyp/andr_log.php";
final RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.trim().equals("Login Successfull")){
Toast.makeText(getApplicationContext(), "Login Successfull",Toast.LENGTH_LONG).show();
Intent in = new Intent(MainActivity.this,Search.class);
startActivity(in);
}
else {
Toast.makeText(getApplicationContext(), "Login Unsuccessfull",Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "error:" +error.toString() ,Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Email", ed1.getText().toString().trim() );
params.put("uid", u_id.getText().toString().trim() );
params.put("Password", ed2.getText().toString().trim() );
return params;
}
};
requestQueue.add(stringRequest);
}});
}
}
fullview.java
package com.desktop.app;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static android.support.v7.app.AlertDialog.*;
import static com.desktop.app.Stitle.EXTRA_AUTHOR;
import static com.desktop.app.Stitle.EXTRA_HR;
import static com.desktop.app.Stitle.EXTRA_PUBLISHER;
import static com.desktop.app.Stitle.EXTRA_PUBY;
import static com.desktop.app.Stitle.EXTRA_ACC;
import static com.desktop.app.Stitle.EXTRA_RAK;
import static com.desktop.app.Stitle.EXTRA_STATUS;
import static com.desktop.app.Stitle.EXTRA_TITLE;
import static com.desktop.app.Stitle.EXTRA_VR;
public class fullview extends AppCompatActivity {
Button location, avail, request;
TextView textviewtitle, textviewauthors, textviewpublisher, textviewpubyear,textviewacc,u_id;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fullview);
Intent intent = getIntent();
Bundle b = getIntent().getExtras();
String id= b.getString("text");
u_id= findViewById(R.id.uid);
String title = intent.getStringExtra(EXTRA_TITLE);
String author = intent.getStringExtra(EXTRA_AUTHOR);
String publisher = intent.getStringExtra(EXTRA_PUBLISHER);
int puby = intent.getIntExtra(EXTRA_PUBY,0);
int accc = intent.getIntExtra(EXTRA_ACC,0);
final int rak = intent.getIntExtra(EXTRA_RAK,0);
final int hr = intent.getIntExtra(EXTRA_HR,0);
final int vr = intent.getIntExtra(EXTRA_VR,0);
final String status = intent.getStringExtra(EXTRA_STATUS);
textviewtitle = findViewById(R.id.textviewtitle);
textviewauthors = findViewById(R.id.textviewauthors);
textviewpublisher = findViewById(R.id.textviewpublisher);
textviewpubyear = findViewById(R.id.textviewpubyear);
textviewacc = findViewById(R.id.textviewacc);
textviewtitle.setText(title);
textviewauthors.setText(author);
textviewpublisher.setText(publisher);
textviewpubyear.setText(String.valueOf(puby));
textviewacc.setText(String.valueOf(accc));
location = findViewById(R.id.loc);
location.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
{
AlertDialog.Builder builder=new AlertDialog.Builder(fullview.this);
builder.setTitle("Location");
builder.setMessage("Rak-No :: " + rak + "\nColumn :: " + hr +"\nRow :: " + vr);
AlertDialog alertDialog=null;
builder.setPositiveButton("Close", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(fullview.this,"Closed",Toast.LENGTH_SHORT).show();
}
});
alertDialog=builder.create();
alertDialog.show();
}
}
});
avail = findViewById(R.id.avail);
avail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
AlertDialog.Builder builder=new AlertDialog.Builder(fullview.this);
{
if (status.equals("yes")) {
builder.setTitle("Availablity");
builder.setMessage("Available");
} else {
builder.setTitle("Availablity");
builder.setMessage("Not Available");
}
}
AlertDialog alertDialog=null;
builder.setPositiveButton("Close", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(fullview.this,"Closed",Toast.LENGTH_SHORT).show();
}
});
alertDialog=builder.create();
alertDialog.show();
}
});
request= findViewById(R.id.request);
request.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
request();
}
});
}
private void request(){
String url= "http://192.168.0.136/fyp/bookreq.php";
final RequestQueue requestQueue = Volley.newRequestQueue(fullview.this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.trim().equals("successfull")){
Toast.makeText(getApplicationContext(), "Go to Admin For Approval",Toast.LENGTH_LONG).show();
Intent in = new Intent(fullview.this,Search.class);
startActivity(in);
}
else {
Toast.makeText(getApplicationContext(), "Already Requested",Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "error:" +error.toString() ,Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Title", textviewtitle.getText().toString().trim());
params.put("Author", textviewauthors.getText().toString().trim());
params.put("Publisher", textviewpublisher.getText().toString().trim());
params.put("Acc", textviewacc.getText().toString().trim());
params.put("Puby", textviewpubyear.getText().toString().trim());
Log.i("Info",textviewtitle.getText().toString().trim());
return params;
}
};
requestQueue.add(stringRequest);
}
}
Here is my second file above where i want to shoe u_id text but i done with this to pass u_id text to other activity
Intent i = new Intent (MainActivity.this,fullview.class);
Bundle b =new Bundle();
b.putString("text", String.valueOf(u_id));
i.putExtras(b);
startActivity(i);
this code i use to pass u_id text and next activity code i use below code
Bundle b = getIntent().getExtras();
String id= b.getString("text");
u_id= findViewById(R.id.uid);
This is what your problem is.
Intent i = new Intent (MainActivity.this,fullview.class);
Bundle b =new Bundle();
b.putString("text", String.valueOf(u_id));
i.putExtras(b);
startActivity(i);
Change this line
b.putString("text", String.valueOf(u_id));
to
b.putString("text", u_id.getText().toString().trim());
EDIT:
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = ed1.getText().toString().trim();
String password = ed2.getText().toString().trim();
final String log_id = u_id.getText().toString();
if(email.isEmpty()){
ed1.setError("Fill this field");
ed1.requestFocus();
}else if(password.isEmpty()){
ed2.setError("Fill this field");
ed2.requestFocus();
} else if(log_id.isEmpty()){
u_id.setError("Fill this field");
u_id.requestFocus();
} else {
login();
Intent i = new Intent(MainActivity.this,fullview.class);
Bundle b =new Bundle();
b.putString("text", u_id.getText().toString().trim());
i.putExtras(b);
startActivity(i);
}
}
I have this code that initializes text to speech. However, text to speech takes around ten seconds to load so I would like it to be done in async. How can I do this without changing the functionality of my code?
import java.util.Locale;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.content.res.Resources;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Button;
import java.lang.String;
import java.util.Random;
public class MainActivity extends Activity implements TextToSpeech.OnInitListener{
TextToSpeech tts;
private static final Random r_generator = new Random();
String textViewString;
int MY_DATA_CHECK_CODE = 1234;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
Resources res = getResources();
TextView tv = (TextView) findViewById(R.id.animal_text);
String loadingString = res.getString(R.string.Loading);
tv.setText(loadingString);
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
}
protected void onActivityResult(
int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
// success, create the TTS instance
tts = new TextToSpeech(this, this);
} else {
// missing data, install it
Intent installIntent = new Intent();
installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
}
}
}
#Override
public void onInit(int status) {
int result=tts.setLanguage(Locale.US);
if(result==TextToSpeech.LANG_MISSING_DATA ||
result==TextToSpeech.LANG_NOT_SUPPORTED){
Log.e("error", "This Language is not supported");
}
Resources res = getResources();
TextView tv = (TextView) findViewById(R.id.animal_text);
String[] myString = res.getStringArray(R.array.englishAnimalArray);
String q = myString[r_generator.nextInt(myString.length)];
tv.setText(q);
textViewString = tv.getText().toString();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
tts.speak(textViewString, TextToSpeech.QUEUE_FLUSH, null);
} else {
tts.speak(textViewString, TextToSpeech.QUEUE_FLUSH, null, null);
}
}
I'd suggest you can take this by using AsyncTask.
An AsyncTask works as follows:
private ProgressDialog pDialog; // Progress Dialog to load during the AsyncTask
private class InitializeSpeechEngine extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute(Void aVoid){
// Initialization code goes inside onPreExecute
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setTitle("Loading Speech to Text Engine");
pDialog.setMessage("Please Wait...");
pDialog.setCancellable(false);
pDialog.show();
}
#Override
protected void doInBackground(Void... params){
// Perform the speech to text initialization here
}
#Override
protected void onPostExecute(Void aVoid){
// Display Toast that the engine is ready for use.
pDialog.dismiss();
Toast.makeText(MainActivity.this, "Speech to text engine initialization complete", Toast.LENGTH_SHORT).show();
}
#Override
protected void onProgressUpdate(Void... params){
}
You can start executing the AsyncTask by making the following call.
new InitialiazeSpeechEngine().execute();
I have a simple app that has an unlock feature in it. When a user purchases this they can unlock more content in the app.
When I debug the app I don't get any errors, but I am unable to retrieve a list of products using the google billing services.
On my main activity I would like to check if the user has all ready purchased the "upgrade" if they have do something with that information.
I have been following the api documentation but its not really helping.
In App Billing Reference
Implementation
Testing
I have 1 item in my In-app products, I have followed the testing document and added an apk to my Alpha testing. The problem here is that apk cant have debugging enabled, so when I use the debugger in android studio the app may perform differently??
I think my code is OK,but any help or guidance in how to test this would be great.
MainActivity.java
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import com.android.vending.billing.IInAppBillingService;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
IInAppBillingService mService;
ServiceConnection connection;
Intent serviceIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
Button start = (Button) findViewById(R.id.startgame);
Button settings = (Button) findViewById(R.id.about);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), StartGame.class);
startActivity(i);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
}
});
settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), Settings.class);
startActivity(i);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
}
});
/// check for pro unlock
serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
serviceIntent.setPackage("com.android.vending");
// first this
connection = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.d("BILLING", "Connected");
//purchse info
mService = IInAppBillingService.Stub.asInterface(service);
checkPurchaseInfo();
}
};
bindService(serviceIntent, connection, Context.BIND_AUTO_CREATE);
}
private void checkPurchaseInfo() {
try {
Bundle ownedItems = mService.getPurchases(3, getPackageName(), "inapp", null);
int responseCode = ownedItems.getInt("RESPONSE_CODE");
Log.d("BILLING","Request Code: " + responseCode);
if(responseCode == 0){
ArrayList<String> ownedSkus = ownedItems.getStringArrayList("INAPP_PURCHASE_ITEM_LIST");
ArrayList<String> purchaseDataList = ownedItems.getStringArrayList("INAPP_PURCHASE_DATA_LIST");
ArrayList<String> signatureList = ownedItems.getStringArrayList("INAPP_DATA_SIGNATURE_LIST");
String continuationToken = ownedItems.getString("INAPP_CONTINUATION_TOKEN");
Log.d("OWNED",ownedSkus.toString());
Log.d("purcahseList",purchaseDataList.toString());
Log.d("SIGNLIST",signatureList.toString());
/////////
//all of these arrays come back as empty []
////////
}
} catch (RemoteException e) {
e.printStackTrace();
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (connection != null) {
unbindService(connection);
}
}
}