I have created an android app which has the activity of a music player which I have created but I want that when there is music play then there is a notification show of a media player which has pause / stop and an image show.
Like This:-
But I do not know how to do it! Please Someone Help Me😢
My Codes:-
player_ui.java
package com.musicwala.djaman;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.SeekBar;
import android.widget.Button;
import android.media.MediaPlayer;
import android.net.Uri;
import java.io.IOException;
import android.widget.SearchView.OnCloseListener;
import java.util.Timer;
import java.util.TimerTask;
import android.media.PlaybackParams;
import android.graphics.PorterDuff;
import android.view.View;
import android.support.v4.app.NotificationCompat;
import android.content.ContentResolver;
import android.app.NotificationManager;
import android.content.Context;
//import wseemann.media.FFmpegMediaMetadataRetriever;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.media.Image;
import android.widget.ImageView;
public class play_ui extends Activity
{
static MediaPlayer mp;
TextView songtext;
String path;
SeekBar sb;
Button pause;
Button previous;
Button next;
Thread updateSeekBar;
#Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO: Implement this method
super.onCreate(savedInstanceState);
setContentView(R.layout.music_player_ui);
songtext = (TextView) findViewById(R.id.txtSongLabel);
songtext.setSelected(true);
String name = getIntent().getStringExtra("file");
path = (String) getIntent().getStringExtra("path");
songtext.setText(name);
pause = (Button) findViewById(R.id.pause);
previous = (Button)findViewById(R.id.previous);
next = (Button)findViewById(R.id.next);
//final SeekBar seekbar = (SeekBar) findViewById(R.id.seekBar);
sb=(SeekBar)findViewById(R.id.seekBar);
MediaMetadataRetriever mmr = new MediaMetadataRetriever();
byte[] rawArt;
Bitmap art = null;
BitmapFactory.Options bfo=new BitmapFactory.Options();
mmr.setDataSource(path);
rawArt = mmr.getEmbeddedPicture();
final ImageView image = (ImageView) findViewById(R.id.album_art);
// if rawArt is null then no cover art is embedded in the file or is not
// recognized as such.
if (null != rawArt)
art = BitmapFactory.decodeByteArray(rawArt, 0, rawArt.length, bfo);
image.setImageBitmap(art);
// Code that uses the cover art retrieved below.
/* updateSeekBar=new Thread(){
#Override
public void run(){
int totalDuration = mp.getDuration();
int currentPosition = 0;
while(currentPosition < totalDuration){
try{
sleep(500);
currentPosition=mp.getCurrentPosition();
sb.setProgress(currentPosition);
}
catch (InterruptedException e){
}
}
}
};*/
updateSeekBar = new Thread() {
#Override
public void run() {
int runtime = mp.getDuration();
int currentPosition = 0;
int adv = 0;
while ((adv = ((adv = runtime - currentPosition) < 500)?adv:500) > 2) {
try {
currentPosition = mp.getCurrentPosition();
if (sb != null) {
sb.setProgress(currentPosition);
}
sleep(adv);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
sb.setProgress(runtime);
break;
}
}
}
};
if(mp != null){
mp.stop();
mp.release();
}
//int pos = 0;
mp = new MediaPlayer();
try
{
mp.setDataSource(path);
mp.prepare();
//sb=(SeekBar)findViewById(R.id.seekBar);
//sb.setMax(mp.getDuration());
}
catch (IOException e)
{}
catch (IllegalArgumentException e)
{}
catch (SecurityException e)
{}
catch (IllegalStateException e)
{}
mp.start();
//Find the seek bar by Id (which you have to create in layout)
// Set seekBar max with length of audio
// You need a Timer variable to set progress with position of audio
sb.setMax(mp.getDuration());
updateSeekBar.start();
sb.getProgressDrawable().setColorFilter(getResources().getColor(R.color.colorPrimary), PorterDuff.Mode.MULTIPLY);
sb.getThumb().setColorFilter(getResources().getColor(R.color.colorPrimary), PorterDuff.Mode.SRC_IN);
sb.setOnSeekBarChangeListener(new
SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i,
boolean b) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mp.seekTo(seekBar.getProgress());
}
});
pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sb.setMax(mp.getDuration());
if(mp.isPlaying()){
pause.setBackgroundResource(R.drawable.ic_play_arrow_black_24dp);
mp.pause();
}
else {
pause.setBackgroundResource(R.drawable.pause);
mp.start();
}
}
});
}
}
Related
I have successfully built a python server which even works but when java from android studio tries to connect to it fails with whole bunch of errors. I have understood that it fails while creating a new socket object but why that I don't know.
This is Java client, see at the end of the code particularly for the issue where I have created new Socket object:
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.media.Image;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.TextView;
import com.chaquo.python.PyObject;
import com.chaquo.python.Python;
import com.chaquo.python.android.AndroidPlatform;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.ml.vision.FirebaseVision;
import com.google.firebase.ml.vision.common.FirebaseVisionImage;
import com.google.firebase.ml.vision.text.FirebaseVisionText;
import com.google.firebase.ml.vision.text.FirebaseVisionTextDetector;
import org.w3c.dom.Text;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.net.*;
import java.io.*;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;
import static android.Manifest.permission.CAMERA;
import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.RECORD_AUDIO;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private Button btnRecognize;
private SpeechRecognizer speechRecognizer;
static EditText ET_ShowRecognized;
String locality;
private Intent intent;
private String ET_ShowRecognizedText;
private String ProcessingText;
//private FusedLocationProviderClient fusedLocationProviderClient;
//Geocoder geocoder;
Python py;
PyObject pyobj;
PyObject obj;
String currentDate;
String currentTime;
static TextToSpeech tts;
Uri imageURI;
ContentValues contentValues;
Intent cameraIntent;
static final int REQUEST_IMAGE_CAPTURE = 1;
Image mediaImage;
FirebaseVisionImage firebaseVisionImage;
static Bitmap imageBitmap;
FirebaseVisionTextDetector textDetector;
String imgText;
Intent CameraIntent;
static Thread sent;
static Thread receive;
static Socket socket;
InputStreamReader in;
BufferedReader bf;
String ServerOutput;
PrintWriter writer;
String ServerInput;
#SuppressLint({"SetTextI18n", "ClickableViewAccessibility", "MissingPermission"})
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityCompat.requestPermissions(this, new String[]{RECORD_AUDIO, WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE, ACCESS_FINE_LOCATION, CAMERA}, PackageManager.PERMISSION_GRANTED);
ET_ShowRecognized = findViewById(R.id.ET_ShowRecognized);
btnRecognize = findViewById(R.id.btnRecognize);
/*fusedLocationProviderClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
#Override
public void onComplete(#NonNull Task<Location> task) {
Location location = task.getResult();
if(location != null){
geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
try {
List<Address> address = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
locality = address.get(0).getLocality();
} catch (IOException e) {
;
}
}
}
});
if(!Python.isStarted()){
Python.start(new AndroidPlatform(this));
}
py = Python.getInstance();
pyobj = py.getModule("WolframAlpha");
obj = pyobj.callAttr("main", locality);*/
tts = new TextToSpeech(MainActivity.this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int i) {
if (i == TextToSpeech.SUCCESS) {
tts.setLanguage(Locale.ENGLISH);
}
tts.speak("Hi you successfully ran me.", TextToSpeech.QUEUE_FLUSH, null, null);
tts.speak("Seems good to meet you.", TextToSpeech.QUEUE_FLUSH, null, null);
}
});
//currentDate = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date());
//currentTime = new SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(new Date());
//textToSpeech.speak("Hi! I am your personal assistant. Today date is something something ", TextToSpeech.QUEUE_FLUSH, null, null);
//Speak("Today's weather forecast for the current location is " + obj.toString());
intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
speechRecognizer.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle bundle) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float v) {
}
#Override
public void onBufferReceived(byte[] bytes) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int i) {
}
#Override
public void onResults(Bundle bundle) {
ArrayList<String> mathches = bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
if (mathches != null) {
ET_ShowRecognized.setText(mathches.get(0));
process();
}
}
#Override
public void onPartialResults(Bundle bundle) {
}
#Override
public void onEvent(int i, Bundle bundle) {
}
});
btnRecognize.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_UP:
speechRecognizer.stopListening();
break;
case MotionEvent.ACTION_DOWN:
ET_ShowRecognized.setText(null);
ET_ShowRecognized.setText("Listening...");
speechRecognizer.startListening(intent);
break;
default:
break;
}
return false;
}
});
}
public void process() {
ProcessingText = ET_ShowRecognized.getText().toString().toLowerCase();
if(ProcessingText.contains("hello")) {
tts.speak("Hi! I hope all is well.", TextToSpeech.QUEUE_FLUSH, null, null);
}
else if(ProcessingText.contains("hi")){
tts.speak("Hello! Nice to meet you.", TextToSpeech.QUEUE_FLUSH, null, null);
}
else if(ProcessingText.contains("your name")){
tts.speak("My name is assistant.", TextToSpeech.QUEUE_FLUSH, null, null);
}
else if(ProcessingText.contains("recognise text")){
tts.speak("Opening Camera.", TextToSpeech.QUEUE_FLUSH, null, null);
dispatchTakePictureIntent();
}
else if(ProcessingText.contains("bye")){
finish();
System.exit(0);
}
else if(ProcessingText.contains("current temperature")){
/*try {
socket = new Socket("192.168.43.203",12345);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
sent = new Thread(new Runnable(){
#Override
public void run() {
try {
bf = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while(true){
ServerOutput = bf.readLine().toString();
MainActivity.tts.speak(ServerOutput, TextToSpeech.QUEUE_FLUSH, null, null);
MainActivity.ET_ShowRecognized.setText(ServerOutput);
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
sent.start();
try {
sent.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
recieve_data();
}else {
tts.speak(ProcessingText, TextToSpeech.QUEUE_FLUSH, null, null);
}
}
private void dispatchTakePictureIntent() {
CameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try {
startActivityForResult(CameraIntent, REQUEST_IMAGE_CAPTURE);
} catch (ActivityNotFoundException e) {
// display error state to the user
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
imageBitmap = (Bitmap) extras.get("data");
//imageView.setImageBitmap(imageBitmap);
detectTextFromImage();
}
}
private void detectTextFromImage() {
firebaseVisionImage = FirebaseVisionImage.fromBitmap(imageBitmap);
textDetector = FirebaseVision.getInstance().getVisionTextDetector();
textDetector.detectInImage(firebaseVisionImage).addOnSuccessListener(new OnSuccessListener<FirebaseVisionText>() {
#Override
public void onSuccess(FirebaseVisionText firebaseVisionText) {
//speakTextFromImage(firebaseVisionText);
getImgText(firebaseVisionText);
}
}).addOnFailureListener(new OnFailureListener() {
#SuppressLint("SetTextI18n")
#Override
public void onFailure(#NonNull Exception e) {
tts.speak("Something went wrong. Please try again later or try with another image.", TextToSpeech.QUEUE_FLUSH, null, null);
ET_ShowRecognized.setText("Something went wrong. Please try again later or try with another image.");
}
});
}
#SuppressLint("SetTextI18n")
private void getImgText(FirebaseVisionText firebaseVisionText){
List<FirebaseVisionText.Block> blockList = firebaseVisionText.getBlocks();
if(blockList.size() == 0) {
tts.speak("I think this image contains no text.", TextToSpeech.QUEUE_FLUSH, null, null);
ET_ShowRecognized.setText("I think this image contains no text.");
}else{
for(FirebaseVisionText.Block block : firebaseVisionText.getBlocks()){
imgText = block.getText().toString();
tts.speak("The text in the image is as follows : " + imgText, TextToSpeech.QUEUE_FLUSH, null, null);
ET_ShowRecognized.setText("The text in the image is as follows : " + imgText);
}
}
}
public void recieve_data(){
ServerInput = "Java client is successfully connected with the server ";
BackgroundTask bt = new BackgroundTask();
bt.execute(ServerInput);
}
class BackgroundTask extends AsyncTask<String, Void, Void>{
#Override
protected Void doInBackground(String... voids) {
try{
String message = voids[0];
socket = new Socket("myIP", 24224);
writer = new PrintWriter(socket.getOutputStream());
writer.write(message);
writer.flush();
writer.close();
socket.close();
}catch (IOException e){
e.printStackTrace();
}
return null;
}
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
}
This is my python server code:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Socket successfully created")
try:
port = 24224
s.bind(("", port))
print("socket binded to %s" %(port))
except socket.error as err:
print('Bind failed. Error Code : ' .format(err))
s.listen(10)
while True:
conn, addr = s.accept()
print('Got connection from', addr)
message = conn.recv(1024)
print("Client : " + message)
conn.close()
Now the run view in the android studio:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.maitreyastudio.ai, PID: 17690
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.maitreyastudio.ai/com.maitreyastudio.ai.MainActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2724)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2789)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6251)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1318)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:340)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:196)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:356)
at java.net.Socket.connect(Socket.java:616)
at java.net.Socket.connect(Socket.java:548)
at java.net.Socket.<init>(Socket.java:440)
at java.net.Socket.<init>(Socket.java:223)
at com.maitreyastudio.ai.MainActivity.onCreate(MainActivity.java:127)
at android.app.Activity.performCreate(Activity.java:6712)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2677)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2789)Â
at android.app.ActivityThread.-wrap12(ActivityThread.java)Â
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527)Â
at android.os.Handler.dispatchMessage(Handler.java:110)Â
at android.os.Looper.loop(Looper.java:203)Â
at android.app.ActivityThread.main(ActivityThread.java:6251)Â
at java.lang.reflect.Method.invoke(Native Method)Â
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)Â
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)Â
Looking at the stack trace I see that you are trying to connect on the ui thread which
is causing the crash. You need to move the connection logic in to its own thread
Here is a link to the documentation that will help you
https://developer.android.com/guide/components/processes-and-threads#Threads
try this for main activity
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.media.Image;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.TextView;
import com.chaquo.python.PyObject;
import com.chaquo.python.Python;
import com.chaquo.python.android.AndroidPlatform;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.ml.vision.FirebaseVision;
import com.google.firebase.ml.vision.common.FirebaseVisionImage;
import com.google.firebase.ml.vision.text.FirebaseVisionText;
import com.google.firebase.ml.vision.text.FirebaseVisionTextDetector;
import org.w3c.dom.Text;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.net.*;
import java.io.*;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;
import static android.Manifest.permission.CAMERA;
import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.RECORD_AUDIO;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private Button btnRecognize;
private SpeechRecognizer speechRecognizer;
static EditText ET_ShowRecognized;
String locality;
private Intent intent;
private String ET_ShowRecognizedText;
private String ProcessingText;
//private FusedLocationProviderClient fusedLocationProviderClient;
//Geocoder geocoder;
Python py;
PyObject pyobj;
PyObject obj;
String currentDate;
String currentTime;
static TextToSpeech tts;
Uri imageURI;
ContentValues contentValues;
Intent cameraIntent;
static final int REQUEST_IMAGE_CAPTURE = 1;
Image mediaImage;
FirebaseVisionImage firebaseVisionImage;
static Bitmap imageBitmap;
FirebaseVisionTextDetector textDetector;
String imgText;
Intent CameraIntent;
static Thread sent;
static Thread receive;
static Socket socket;
InputStreamReader in;
BufferedReader bf;
String ServerOutput;
PrintWriter writer;
String ServerInput;
#SuppressLint({"SetTextI18n", "ClickableViewAccessibility", "MissingPermission"})
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityCompat.requestPermissions(this, new String[]{RECORD_AUDIO, WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE, ACCESS_FINE_LOCATION, CAMERA}, PackageManager.PERMISSION_GRANTED);
ET_ShowRecognized = findViewById(R.id.ET_ShowRecognized);
btnRecognize = findViewById(R.id.btnRecognize);
/*fusedLocationProviderClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
#Override
public void onComplete(#NonNull Task<Location> task) {
Location location = task.getResult();
if(location != null){
geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
try {
List<Address> address = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
locality = address.get(0).getLocality();
} catch (IOException e) {
;
}
}
}
});
if(!Python.isStarted()){
Python.start(new AndroidPlatform(this));
}
py = Python.getInstance();
pyobj = py.getModule("WolframAlpha");
obj = pyobj.callAttr("main", locality);*/
tts = new TextToSpeech(MainActivity.this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int i) {
if (i == TextToSpeech.SUCCESS) {
tts.setLanguage(Locale.ENGLISH);
}
tts.speak("Hi you successfully ran me.", TextToSpeech.QUEUE_FLUSH, null, null);
tts.speak("Seems good to meet you.", TextToSpeech.QUEUE_FLUSH, null, null);
}
});
//currentDate = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date());
//currentTime = new SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(new Date());
//textToSpeech.speak("Hi! I am your personal assistant. Today date is something something ", TextToSpeech.QUEUE_FLUSH, null, null);
//Speak("Today's weather forecast for the current location is " + obj.toString());
intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
speechRecognizer.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle bundle) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float v) {
}
#Override
public void onBufferReceived(byte[] bytes) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int i) {
}
#Override
public void onResults(Bundle bundle) {
ArrayList<String> mathches = bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
if (mathches != null) {
ET_ShowRecognized.setText(mathches.get(0));
process();
}
}
#Override
public void onPartialResults(Bundle bundle) {
}
#Override
public void onEvent(int i, Bundle bundle) {
}
});
btnRecognize.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_UP:
speechRecognizer.stopListening();
break;
case MotionEvent.ACTION_DOWN:
ET_ShowRecognized.setText(null);
ET_ShowRecognized.setText("Listening...");
speechRecognizer.startListening(intent);
break;
default:
break;
}
return false;
}
});
}
public void process() {
ProcessingText = ET_ShowRecognized.getText().toString().toLowerCase();
if(ProcessingText.contains("hello")) {
tts.speak("Hi! I hope all is well.", TextToSpeech.QUEUE_FLUSH, null, null);
}
else if(ProcessingText.contains("hi")){
tts.speak("Hello! Nice to meet you.", TextToSpeech.QUEUE_FLUSH, null, null);
}
else if(ProcessingText.contains("your name")){
tts.speak("My name is assistant.", TextToSpeech.QUEUE_FLUSH, null, null);
}
else if(ProcessingText.contains("recognise text")){
tts.speak("Opening Camera.", TextToSpeech.QUEUE_FLUSH, null, null);
dispatchTakePictureIntent();
}
else if(ProcessingText.contains("bye")){
finish();
System.exit(0);
}
else if(ProcessingText.contains("current temperature")){
sendTemp();
recieve_data();
}else {
tts.speak(ProcessingText, TextToSpeech.QUEUE_FLUSH, null, null);
}
}
private void dispatchTakePictureIntent() {
CameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try {
startActivityForResult(CameraIntent, REQUEST_IMAGE_CAPTURE);
} catch (ActivityNotFoundException e) {
// display error state to the user
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
imageBitmap = (Bitmap) extras.get("data");
//imageView.setImageBitmap(imageBitmap);
detectTextFromImage();
}
}
private void detectTextFromImage() {
firebaseVisionImage = FirebaseVisionImage.fromBitmap(imageBitmap);
textDetector = FirebaseVision.getInstance().getVisionTextDetector();
textDetector.detectInImage(firebaseVisionImage).addOnSuccessListener(new OnSuccessListener<FirebaseVisionText>() {
#Override
public void onSuccess(FirebaseVisionText firebaseVisionText) {
//speakTextFromImage(firebaseVisionText);
getImgText(firebaseVisionText);
}
}).addOnFailureListener(new OnFailureListener() {
#SuppressLint("SetTextI18n")
#Override
public void onFailure(#NonNull Exception e) {
tts.speak("Something went wrong. Please try again later or try with another image.", TextToSpeech.QUEUE_FLUSH, null, null);
ET_ShowRecognized.setText("Something went wrong. Please try again later or try with another image.");
}
});
}
#SuppressLint("SetTextI18n")
private void getImgText(FirebaseVisionText firebaseVisionText){
List<FirebaseVisionText.Block> blockList = firebaseVisionText.getBlocks();
if(blockList.size() == 0) {
tts.speak("I think this image contains no text.", TextToSpeech.QUEUE_FLUSH, null, null);
ET_ShowRecognized.setText("I think this image contains no text.");
}else{
for(FirebaseVisionText.Block block : firebaseVisionText.getBlocks()){
imgText = block.getText().toString();
tts.speak("The text in the image is as follows : " + imgText, TextToSpeech.QUEUE_FLUSH, null, null);
ET_ShowRecognized.setText("The text in the image is as follows : " + imgText);
}
}
}
public void recieve_data(){
ServerInput = "Java client is successfully connected with the server ";
BackgroundTask bt = new BackgroundTask();
bt.execute(ServerInput);
}
public void sendTemp(){
new TempBackgroundTask().execute();
}
class TempBackgroundTask extends AsyncTask<Void, String, Void>{
#Override
protected Void doInBackground(String... voids) {
try {
socket = new Socket("myIP",12345);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
sent = new Thread(new Runnable(){
#Override
public void run() {
try {
bf = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while(true){
ServerOutput = bf.readLine().toString();
publishProgress(ServerOutput);
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
sent.start();
try {
sent.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#SuppressWarnings("unchecked")
#Override
protected void onProgressUpdate(String... text) {
MainActivity.tts.speak(text[0], TextToSpeech.QUEUE_FLUSH, null, null);
MainActivity.ET_ShowRecognized.setText(text[0]);
}
}
class BackgroundTask extends AsyncTask<String, Void, Void>{
#Override
protected Void doInBackground(String... voids) {
try{
String message = voids[0];
socket = new Socket("192.168.43.203", 24224);
writer = new PrintWriter(socket.getOutputStream());
writer.write(message);
writer.flush();
writer.close();
socket.close();
}catch (IOException e){
e.printStackTrace();
}
return null;
}
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
}
I am currently working on my finals project on android.
the project is about a SimonSays game:
in my Simon Says game a have a section where the application is supposed to sleep
but it does , i think its because my teacher added all of these try and catch
functions, how do i fix it?
package com.gabie212.simonsays;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
public class GameActivity extends AppCompatActivity implements View.OnClickListener,View.OnLongClickListener {
private int i = 0, pNum = 0, pIndex = 0,score;
private Thread t = new Thread();
private Thread bt = new Thread();
private Button greenButton;
private Button redButton;
private Button blueButton;
private Button yellowButton;
private Button startButton;
private TextView Score;
private boolean startActivated = false;
private MediaPlayer greenBeep;
private MediaPlayer redBeep;
private MediaPlayer blueBeep;
private MediaPlayer yellowBeep;
private ArrayList<Integer> userColors = new ArrayList<Integer>();
// change backgroud
final String imagefile = "savedImageLocation";//for background
private ImageButton btPhoto; // for background
private android.support.constraint.ConstraintLayout background; // for background
private int yellowish = Color.rgb(0, 191, 255);// for background
private Handler handler = new Handler();
final int SECOND_ACTIVITY = 10;
// game manager
private GameManger gm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
Score = (TextView) findViewById(R.id.ScoreNum);
greenButton = (Button) findViewById(R.id.btnGreen);
redButton = (Button) findViewById(R.id.btnRed);
blueButton = (Button) findViewById(R.id.btnBlue);
yellowButton = (Button) findViewById(R.id.btnYellow);
startButton = (Button) findViewById(R.id.btnStart);
greenButton.setOnClickListener(this);
redButton.setOnClickListener(this);
blueButton.setOnClickListener(this);
yellowButton.setOnClickListener(this);
startButton.setOnClickListener(this);
greenBeep = MediaPlayer.create(this, R.raw.greenbeep);
redBeep = MediaPlayer.create(this, R.raw.redbeep);
blueBeep = MediaPlayer.create(this, R.raw.bluebeep);
yellowBeep = MediaPlayer.create(this, R.raw.yellowbeep);
greenButton.setOnLongClickListener(this);
redButton.setOnLongClickListener(this);
blueButton.setOnClickListener(this);
yellowButton.setOnClickListener(this);
/*
SharedPreferences sp = getSharedPreferences("score", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.clear();
editor.apply();
*/
// for change background
btPhoto = (ImageButton) findViewById(R.id.btPhoto);
btPhoto.setOnLongClickListener(this);
background = (android.support.constraint.ConstraintLayout) findViewById(R.id.background);
}
public void start() {
startActivated=true;
gm = new GameManger(this);
Score.setText("0");
lightUp(0);
}
public void beepStop(){
greenBeep.stop();
redBeep.stop();
blueBeep.stop();
yellowBeep.stop();
}
public void lightUp(final int i) {
android.os.Handler handler = new android.os.Handler();
if (i < gm.getRandomColors().size()) //light up code
{
switch (gm.getRandomColors().get(i)) {
case 1:
greenButton.setBackgroundResource(R.drawable.greenlightup);
greenBeep.start();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
greenButton.setBackgroundResource(R.drawable.green);
lightUp(i+1);
}
}, 500);
break;
case 2:
redButton.setBackgroundResource(R.drawable.redlightup);
redBeep.start();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
redButton.setBackgroundResource(R.drawable.red);
lightUp(i+1);
}
}, 500);
break;
case 3:
blueButton.setBackgroundResource(R.drawable.bluelightup);
blueBeep.start();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
blueButton.setBackgroundResource(R.drawable.blue);
lightUp(i+1);
}
}, 500);
break;
case 4:
yellowButton.setBackgroundResource(R.drawable.yellowlightup);
yellowBeep.start();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
yellowButton.setBackgroundResource(R.drawable.yellow);
lightUp(i+1);
}
}, 500);
break;
}
}
pIndex = 0;
}
#Override
public void onClick(View v) {
if (v.getId() == startButton.getId()) {
start();
} else {
if (startActivated) {
if (v.getId() == greenButton.getId()) {
greenBeep.start();
pNum = 1;
}
if (v.getId() == redButton.getId()) {
redBeep.start();
pNum = 2;
}
if (v.getId() == blueButton.getId()) {
blueBeep.start();
pNum = 3;
}
if (v.getId() == yellowButton.getId()) {
yellowBeep.start();
pNum = 4;
}
if (!gm.check(pNum, pIndex)) {
beepStop();
SharedPreferences sp = getSharedPreferences("score", Context.MODE_PRIVATE);
Intent i = null;
score = gm.getRandomColors().size()-1;
if(score > sp.getInt("scoreP3",0)) {
i = new Intent(GameActivity.this, InsertScoreActivity.class);
i.putExtra("score", gm.getRandomColors().size() - 1);
startActivity(i);
}
else {
i = new Intent(GameActivity.this, GameOverActivity.class);
i.putExtra("score", gm.getRandomColors().size() - 1);
startActivity(i);
}
}
pIndex++;
if (pIndex == gm.getRandomColors().size()) {
Score.setText("" + gm.getRandomColors().size() + "");
gm.addColor();
//this is the sleep that doesn't work
try {
t.sleep(500);
// Do some stuff
} catch (Exception e) {
e.getLocalizedMessage();
}
//this is the sleep that doesn't work
lightUp(0);
}
}
}
}
// for background
public void getPhoto(View v)
{
//brings user to gallery to select image for background of screen
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),0);
}
//for background
#Override
public boolean onLongClick(View view)
{
AlertDialog.Builder info = new AlertDialog.Builder(this);
info.setTitle("Remove Background Image?");
info.setMessage("Are you sure you wish to revert to the default background?");
info.setCancelable(true);
info.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{ //erases current background image location
try {
FileOutputStream fos = openFileOutput(imagefile, Context.MODE_PRIVATE);
OutputStreamWriter osw = new OutputStreamWriter(fos);
BufferedWriter writer = new BufferedWriter(osw);
writer.close();
osw.close();
fos.close();
background.setBackgroundColor(yellowish);
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
info.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
dialog.cancel();
}
});
info.show();
return false;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(requestCode == 0 && resultCode == RESULT_OK)
{
try
{
Uri selectedImage = data.getData();
grantUriPermission("com.example.memorygame", selectedImage,
Intent.FLAG_GRANT_READ_URI_PERMISSION);
InputStream imageStream;
imageStream = getContentResolver().openInputStream(selectedImage);
Bitmap bitmap = BitmapFactory.decodeStream(imageStream);
Drawable image = new BitmapDrawable(getResources(), bitmap);
background.setBackground(image);
//saves location of background image
try
{
FileOutputStream fos = openFileOutput(imagefile, Context.MODE_PRIVATE);
OutputStreamWriter osw = new OutputStreamWriter(fos);
BufferedWriter writer = new BufferedWriter(osw);
String imageUri = selectedImage.toString();
writer.append(imageUri);
writer.close();
osw.close();
fos.close();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
so this is my code and the i will put two notes on the thread.sleep that doesn't work for me.
basically i have this function that lights up a series of buttons (switches their color in a certain order) ,
then i have a function which receives the user input ( what buttons the user pressed and in what order).
what i want to do by that sleep is to put a little break between the end of the color input(when the user finishes to press stuff), and the beginning of the light up ( when the buttons lightup/change their color).
i think the problem comes with all of the these try and catch functions or however they're called (sorry i am a beginner) however i don't know hwo to overcome this.
You should avoid Thread.sleep(). Use handler for doing UI related operation.
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
//Do something here
}
}, 5000);
If you get some time please go through the below link. This will give an idea of handler and thread.
Android, Handler is running in main thread or other thread?
In android, you can use Handler to wait for as much as you want, here's an example of 2 seconds (2000 milliseconds) delay:
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// this code will run after 2 seconds
}
}, 2000);
Just insert this code anywhere you need to wait/sleep your thread.
It's better to use Handler instead to Thread.sleep();
Just Replace this
//this is the sleep that doesn't work
try {
t.sleep(500);
// Do some stuff
} catch (Exception e) {
e.getLocalizedMessage();
}
//this is the sleep that doesn't work
With
Handler handler1=new Handler();
handler1.postDelayed(new Runnable() {
#Override
public void run() {
lightUp(0);
}
},500);
I have been trying to implement next song button in my audio player app. I copied some code from a tutorial but its not working.The button for next song is btnNext and the method is cde(), its the last method in the code. The button gets clicked but next song is not played, current song keeps playing.How do I fix this ?
package com.example.dell_1.myapp3;
import android.app.Activity;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static android.R.attr.path;
public class PlayListActivity extends Activity {
private String[] mAudioPath;
private MediaPlayer mMediaPlayer;
private String[] mMusicList;
int currentPosition = 0;
private List<String> songs = new ArrayList<>();
MediaMetadataRetriever metaRetriver;
byte[] art;
ImageView album_art;
TextView album;
TextView artist;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_list);
mMediaPlayer = new MediaPlayer();
ListView mListView = (ListView) findViewById(R.id.list);
mMusicList = getAudioList();
ArrayAdapter<String> mAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, mMusicList);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
try {
playSong(mAudioPath[arg2]);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
private String[] getAudioList() {
final Cursor mCursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Audio.Media.DISPLAY_NAME, MediaStore.Audio.Media.DATA}, null, null,
"LOWER(" + MediaStore.Audio.Media.TITLE + ") ASC");
int count = mCursor.getCount();
String[] songs = new String[count];
mAudioPath = new String[count];
int i = 0;
if (mCursor.moveToFirst()) {
do {
songs[i] = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME));
mAudioPath[i] = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
i++;
} while (mCursor.moveToNext());
}
mCursor.close();
return songs;
}
private void playSong(String path) throws IllegalArgumentException,
IllegalStateException, IOException {
setContentView(R.layout.activity_android_building_music_player);
Log.d("ringtone", "playSong :: " + path);
mMediaPlayer.reset();
mMediaPlayer.setDataSource(path);
//mMediaPlayer.setLooping(true);
mMediaPlayer.prepare();
mMediaPlayer.start();
acv(path);
abc();
cde();
}
public void acv(String path) {
getInit();
metaRetriver = new MediaMetadataRetriever();
metaRetriver.setDataSource(path);
try {
art = metaRetriver.getEmbeddedPicture();
Bitmap songImage = BitmapFactory.decodeByteArray(art, 0, art.length);
album_art.setImageBitmap(songImage);
album.setText(metaRetriver
.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM));
artist.setText(metaRetriver
.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST));
} catch (Exception e) {
album_art.setBackgroundColor(Color.GRAY);
album.setText("Unknown Album");
artist.setText("Unknown Artist");
}
}
public void getInit() {
album_art = (ImageView) findViewById(R.id.coverart1);
album = (TextView) findViewById(R.id.Album);
artist = (TextView) findViewById(R.id.artist_name);
}
public void abc() {
ImageButton btnPlay1 = (ImageButton) findViewById(R.id.btnPlay1);
btnPlay1.setBackgroundColor(Color.TRANSPARENT);
btnPlay1.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
} else {
mMediaPlayer.start();
}
}
});
}
public void cde() {
ImageButton btnNext = (ImageButton) findViewById(R.id.btnNext); //this is the button for playing next song.
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
try {
currentPosition=currentPosition+1;
playSong(path + songs.get(currentPosition));
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
}
Add this in onCreate method:
Bundle bundle = getIntent().getExtras();
position = bundle.getInt("position");
And change next button listener to
btnNext.setOnClickListener(new View.OnClickListener() //this is the button
#Override
public void onClick(View arg0) {
if (mMediaPlayer!= null && mMediaPlayer.isPlaying()) {
mMediaPlayer.stop();
}
uri = Uri.parse(mAudioPath[position + 1]);
mMediaPlayer.setDataSource(getApplicationContext(), uri);
mMediaPlayer.prepare();
mMediaPlayer.start();
}
});
int currentPosition = 0;
if (++currentPosition >= songs.size()) {
currentPosition = 0;
} else
try {
playSong(path + songs.get(currentPosition));
} catch (IOException ex) {
ex.printStackTrace();
}
}
The above code is your code from the onClick method.
As you can see, you are initializing the currentPosition inside onClick.
So to show you what this implies:
onClick -> position = 0 -> position++ (position = 1) -> playSong(songUri)
When you want:
onClick -> position++ -> playSong(songUri)
So, before setting the onCLickListener, you add:
currentPosition = 0;
currentPosition is declared in the class now, so make sure you add it. It should look like this:
int currentPosition;
..other code
public void cde(){
..code here
currentPosition = 0;
... set onClickListener
}
Remove int currentPosition = 0; from the onClick method.
I assume there is a position 0 as well. Here is the refactored code that would handle that:
try {
playSong(path + songs.get(currentPosition));
if (++currentPosition >= songs.size()) {
currentPosition = 0;
}
} catch (IOException ex) {
ex.printStackTrace();
}
The above code is addressing another issue you would be likely to meet. Song 0 would never play on the first round.
Another thing you want to check for (not giving you the code for it as it is easy) is to not play or allow next song if there are no songs. If songs.size == 0 it would never play but set the position to 0 over and over.
Currently I am facing three issues:
Getting the MediaRecorder to reset instead of release.
I think i need to create a new instance of the MediaRecorder and release() it as well, but I do not know where.
I want it to keep recording audio until the phone dies and even when the user changes to a different screen (i.e. going to a new class).
I have tried to google this but do not know how to achieve it.
Edit - I figured out how to use SimpleDateFormat!
Edit 2 - Realised I need to create a started service for my 2nd issue.
My code is as follows
Class:
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Drugs extends AppCompatActivity {
WebView myBrowser;
MediaRecorder mRecorder;
private static String audioFilePath;
public boolean isRecording = false;
MediaPlayer mediaPlayer;
public boolean isPlaying = false;
SimpleDateFormat simpledate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drugs);
myBrowser = (WebView) findViewById(R.id.mybrowser);
myBrowser.loadUrl("file:///android_asset/drugs.html");
myBrowser.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
Button btndrugslaw = (Button) findViewById(R.id.drugslaw);
btndrugslaw.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intentdruglaw = new Intent(Drugs.this, DrugLaw.class);
startActivity(intentdruglaw);
}
});}
public void RecordButton (View view) {
if(mRecorder == null){
audioFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + simpledate
+ "/myaudio.3gp";
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(audioFilePath);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
}
if (isRecording) {
try{
stopRecording();
isRecording = false;
((Button)view).setText("Start Recording");
}catch(Exception e){
e.printStackTrace();
}
} else {
try{
startRecording();
isRecording = true;
((Button)view).setText("Stop Recording");
}catch(Exception e){
e.printStackTrace();
}
}
}
public void startRecording() throws IllegalStateException, IOException{
mRecorder.prepare();
MediaRecorder mRecorder = new MediaRecorder();
mRecorder.start();
}
public void stopRecording() throws IllegalStateException, IOException{
mRecorder.stop();
mRecorder.reset();
}
public void StartPlaying(View view) throws IllegalStateException, IOException {
if (mediaPlayer == null) {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(audioFilePath);
}
if (isPlaying) {
try {
stopPlaying();
isPlaying = false;
((Button)view).setText("Play Audio");
} catch (Exception e) {
e.printStackTrace();
}
} else {
try{
startPlaying();
isPlaying = true;
((Button)view).setText("Stop Audio");
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void startPlaying() throws IllegalStateException, IOException {
mediaPlayer.prepare();
mediaPlayer.start();
}
public void stopPlaying () throws IllegalStateException, IOException {
mediaPlayer.release();
}
}
This is the MainActivity.java
package com.test.webservertest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.support.v7.app.ActionBarActivity;
import android.util.AndroidRuntimeException;
import android.util.Xml;
import android.view.Menu;
import android.view.MenuItem;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.content.Context;
import android.view.View.OnClickListener;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.util.EncodingUtils;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.io.DataOutputStream;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Locale;
import java.net.URLConnection;
import java.net.HttpURLConnection;
import java.io.*;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Logger;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity
{
private static final int MY_DATA_CHECK_CODE = 0;
public static MainActivity currentActivity;
TextToSpeech mTts;
private String targetURL;
private String urlParameters;
private Button btnClick;
private String clicking = "clicked";
private final String[] ipaddresses = new String[2];
private final Integer[] ipports = new Integer[2];
private TextView text;
private Socket socket;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setContentView(new SingleTouchEventView(this, null));
/*ipaddresses[0] = "10.0.0.3";
ipaddresses[1] = "10.0.0.2";
ipports[0] = 8098;
ipports[1] = 8088;*/
//addListenerOnButton();
currentActivity = this;
initTTS();
}
public void addListenerOnButton() {
/*btnClick = (Button) findViewById(R.id.checkipbutton);
btnClick.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
text = (TextView) findViewById(R.id.textView2);
try
{
} catch (Exception e)
{
text.setText("Connection Failed");
}
}
});*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings)
{
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Dispatch onStart() to all fragments. Ensure any created loaders are
* now started.
*/
#Override
protected void onStart()
{
super.onStart();
TextToSpeechServer.main(null);
}
#Override
protected void onStop() {
super.onStop();
}
public 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(getApplicationContext(), new OnInitListener() {
#Override
public void onInit(int i) {
if(i == TextToSpeech.SUCCESS) {
int result = mTts.setLanguage(Locale.US);
if(result == TextToSpeech.LANG_AVAILABLE
|| result == TextToSpeech.LANG_COUNTRY_AVAILABLE) {
mTts.setPitch(1);
mTts.speak(textforthespeacch, TextToSpeech.QUEUE_FLUSH, null);
}
}
}
});
} else {
Intent installIntent = new Intent();
installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
}
}
}
public static String textforthespeacch = "";
public static void TextToSpeak(String text) {
textforthespeacch = text;
}
private boolean is_start = true;
public class SingleTouchEventView extends View {
private Paint paint = new Paint();
private Path path = new Path();
private Path circlePath = new Path();
public SingleTouchEventView(Context context, AttributeSet attrs) {
super(context, attrs);
paint.setAntiAlias(true);
paint.setStrokeWidth(6f);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(path, paint);
canvas.drawPath(circlePath, paint);
}
#Override
public boolean onTouchEvent(MotionEvent event)
{
float eventX = event.getX();
float eventY = event.getY();
float lastdownx = 0;
float lastdowny = 0;
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
path.moveTo(eventX, eventY);
circlePath.addCircle(eventX, eventY, 50, Path.Direction.CW);
lastdownx = eventX;
lastdowny = eventY;
Thread t = new Thread(new Runnable()
{
#Override
public void run()
{
byte[] response = null;
if (is_start == true)
{
response = Get("http://10.0.0.2:8098/?cmd=start");
is_start = false;
}
else
{
response = Get("http://10.0.0.2:8098/?cmd=stop");
is_start = true;
}
if (response!=null)
{
String a = null;
try
{
a = new String(response,"UTF-8");
textforthespeacch = a;
MainActivity.currentActivity.initTTS();
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
Logger.getLogger("MainActivity(inside thread)").info(a);
}
}
});
t.start();
return true;
case MotionEvent.ACTION_MOVE:
path.lineTo(eventX, eventY);
break;
case MotionEvent.ACTION_UP:
// nothing to do
circlePath.reset();
break;
default:
return false;
}
// Schedules a repaint.
invalidate();
return true;
}
}
private byte[] Get(String urlIn)
{
URL url = null;
String urlStr = urlIn;
if (urlIn!=null)
urlStr=urlIn;
try
{
url = new URL(urlStr);
} catch (MalformedURLException e)
{
e.printStackTrace();
return null;
}
HttpURLConnection urlConnection = null;
try
{
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
byte[] buf=new byte[10*1024];
int szRead = in.read(buf);
byte[] bufOut;
if (szRead==10*1024)
{
throw new AndroidRuntimeException("the returned data is bigger than 10*1024.. we don't handle it..");
}
else
{
bufOut = Arrays.copyOf(buf, szRead);
}
return bufOut;
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
finally
{
if (urlConnection!=null)
urlConnection.disconnect();
}
}
}
It was working fine. Maybe I need to enable something on my Android device?
My Android device is connected now to the PC via USB and working fine.
When I'm running my program in debug mode and touch the screen it never stop on:
#Override
public boolean onTouchEvent(MotionEvent event)
{
float eventX = event.getX();
I added a break point on the line: float eventX = event.getX();
But touching the screen does nothing.
You are not at all registering the OnTouchListener. First register OnTouchListener using anonymousclass or just implements it in your class
From your code you need the listener for this SingleTouchEventView view. Just add "implements View.OnTouchListenter" for the class. Because you have already overridden onTouch method in your code.
You have to change your style.xml when you remove "Extends ActionbarActivity"!
Check this change appTheme