So, I want to create a text to speech without the use of textfield and button in Android Studio. For example when I open the app it will say "WELCOME TO MY APP" without text field or any button. How can I do that? Need your help.
You could do like below:
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.speech.tts.TextToSpeech;
import java.util.Locale;
public class MainActivity extends Activity {
TextToSpeech t1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1 = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
t1.setLanguage(Locale.ENGLISH);
}
}
});
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
t1.speak("welcome to my app", TextToSpeech.QUEUE_FLUSH, null);
}
}, 100);
}
public void onPause() {
if (t1 != null) {
t1.stop();
t1.shutdown();
}
super.onPause();
}
}
codes are self explanatory and I tested it with successful result.
Just add this in your onCreate():
myTTS = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
// replace this Locale with whatever you want
Locale localeToUse = new Locale("en","US");
myTTS.setLanguage(localeToUse);
myTTS.speak("Hi, Welcome to my app!", TextToSpeech.QUEUE_FLUSH, null);
}
}
});
Related
When the user captures the image, the device will automatically read aloud the text. for that i have implemented texttospeech method but when this activity stop i want to start another task. how will it can be done?
After reading the captured text, I want to implement another text-to-speech method how can i do this?
package com.example.software2.ocrhy;
import static android.Manifest.permission.CAMERA;
import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.text.TextBlock;
import com.google.android.gms.vision.text.TextRecognizer;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
public class MainActivity2 extends AppCompatActivity {
private static final int REQUEST_SPEECH = 101;
private static final int REQ_CODE_SPEECH_INPUT = 100;
Button buttonCamera;
private Button button;
private TextView mVoiceInputTv;
private TextView textView;
private SurfaceView surfaceView;
private CameraSource cameraSource;
private TextRecognizer textRecognizer;
private static TextToSpeech textToSpeech;
private String stringResult = null;
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
mVoiceInputTv = (TextView) findViewById(R.id.textView);
textView = (TextView) findViewById(R.id.textView);
getWindow().getDecorView().setBackgroundColor(Color.WHITE);
ActivityCompat.requestPermissions(this, new String[]{CAMERA}, PackageManager.PERMISSION_GRANTED);
textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
textToSpeech.setLanguage(Locale.CANADA);
textToSpeech.setSpeechRate(1f);
Toast.makeText(MainActivity2.this, "tap on the screen and say yes for read and no for return to the main menu", Toast.LENGTH_SHORT).show();
textToSpeech.speak("tap on the screen and say yes for read and no for return to the main menu", TextToSpeech.QUEUE_ADD, null);
}
}
});
}
private void textRecognizer() {
Toast.makeText(MainActivity2.this, "Tap on the screen and listen ", Toast.LENGTH_SHORT).show();
textToSpeech.speak(" Tap on the screen take a picture of any text with your device and listen", TextToSpeech.QUEUE_FLUSH, null);
textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
cameraSource = new CameraSource.Builder(getApplicationContext(), textRecognizer)
.setRequestedPreviewSize(1280, 1024)
.setAutoFocusEnabled(true)
.build();
surfaceView = findViewById(R.id.surfaceView);
Context context = this;
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
return;
}
cameraSource.start(surfaceView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
}
private void capture() {
textRecognizer.setProcessor(new Detector.Processor<TextBlock>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<TextBlock> detections) {
SparseArray<TextBlock> sparseArray = detections.getDetectedItems();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < sparseArray.size(); ++i) {
TextBlock textBlock = sparseArray.valueAt(i);
if (textBlock != null && textBlock.getValue() != null) {
stringBuilder.append(textBlock.getValue() + " ");
}
}
final String stringText = stringBuilder.toString();
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
stringResult = stringText;
resultObtained();
}
});
}
});
}
private void resultObtained() {
setContentView(R.layout.activity_main2);
textView = findViewById(R.id.textView);
textView.setText(stringResult);
textToSpeech.speak(stringResult, TextToSpeech.QUEUE_FLUSH, null, null);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startVoiceInput();
}
});
}
private void startVoiceInput() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Hello, How can I help you?");
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
mVoiceInputTv.setText(result.get(0));
}
if (mVoiceInputTv.getText().toString().contentEquals("time and date")) {
Intent intent = new Intent(getApplicationContext(), MainActivity4.class);
startActivity(intent);
}
if (mVoiceInputTv.getText().toString().contentEquals("battery")) {
Intent intent = new Intent(getApplicationContext(), MainActivity6.class);
startActivity(intent);
mVoiceInputTv.setText(null);
}
if (mVoiceInputTv.getText().toString().contentEquals("location")) {
Intent intent = new Intent(getApplicationContext(), MainActivity8.class);
startActivity(intent);
mVoiceInputTv.setText(null);
}
if (mVoiceInputTv.getText().toString().contentEquals("weather")) {
Intent intent = new Intent(getApplicationContext(), MainActivity5.class);
startActivity(intent);
mVoiceInputTv.setText(null);
} else {
textToSpeech.speak( "Do not understand just tap on the screen Say again", TextToSpeech.QUEUE_FLUSH, null);
}
if (mVoiceInputTv.getText().toString().contentEquals("calculator")) {
Intent intent = new Intent(getApplicationContext(), MainActivity3.class);
startActivity(intent);
mVoiceInputTv.setText(null);
}
else if(mVoiceInputTv.getText().toString().contentEquals("exit")) {
finish();
}
else {
textToSpeech.speak("Do not understand just tap on the screen Say again", TextToSpeech.QUEUE_FLUSH, null);
}
if (mVoiceInputTv.getText().toString().contentEquals("yes")) {
setContentView(R.layout.surface);
surfaceView = findViewById(R.id.surfaceView);
surfaceView.setOnClickListener((View v) -> {
capture();
});
textRecognizer();
mVoiceInputTv.setText(null);
} else if (mVoiceInputTv.getText().toString().contentEquals("no")) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
break;
}
}
}
public boolean onKeyDown(int keyCode, #Nullable KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_VOLUME_UP){
textToSpeech.speak("You are in main menu. just swipe right and say what you want", TextToSpeech.QUEUE_FLUSH, null);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
final Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
#Override
public void run() {
textToSpeech.speak("you are in main menu. just swipe right and say what you want", TextToSpeech.QUEUE_FLUSH, null);
}
},1000);
}
return true;
}
public void buttonStart(View view) {
startVoiceInput();
}
public void onPause() {
if (textToSpeech != null) {
textToSpeech.stop();
}
super.onPause();
}
}
just use the same mode on text to speech ADD and it will play when the first one is done, ADD = ADD, FLUSH = reset
textToSpeech.speak("this will play when first is done",
TextToSpeech.QUEUE_ADD, null);
You have to call startVoiceInput() again.
You are setting this call for an onClick() handler on a TextView already.
1.MainActivity.java file
I think the error got at this line
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop()
I'm trying to open the camera and display using SurfaceView. This delays the loading of the activity for a really long time. So I'm wondering what are the best practices of opening the camera.
package com.example.software2.ocrhy;
public class MainActivity extends AppCompatActivity {
private TextView textView;
private SurfaceView surfaceView;
private CameraSource cameraSource;
private TextRecognizer textRecognizer;
private TextToSpeech textToSpeech;
private String stringResult = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityCompat.requestPermissions(this, new String[]{CAMERA}, PackageManager.PERMISSION_GRANTED);
textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
cameraSource.release();
}
private void textRecognizer(){
textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
cameraSource = new CameraSource.Builder(getApplicationContext(), textRecognizer)
.setRequestedPreviewSize(1280, 1024)
.build();
surfaceView = findViewById(R.id.surfaceView);
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
#SuppressLint("MissingPermission")
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
cameraSource.start(surfaceView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
textRecognizer.setProcessor(new Detector.Processor<TextBlock>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<TextBlock> detections) {
SparseArray<TextBlock> sparseArray = detections.getDetectedItems();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i<sparseArray.size(); ++i){
TextBlock textBlock = sparseArray.valueAt(i);
if (textBlock != null && textBlock.getValue() !=null){
stringBuilder.append(textBlock.getValue() + " ");
}
}
final String stringText = stringBuilder.toString();
Handler handler = new Handler(Looper.getMainLooper());
handler.post(() -> {
stringResult = stringText;
resultObtained();
});
}
});
}
private void resultObtained(){
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
textView.setText(stringResult);
textToSpeech.speak(stringResult, TextToSpeech.QUEUE_FLUSH, null, null);
}
public void buttonStart(View view){
setContentView(R.layout.surface);
textRecognizer();
}
}
I got full code from this link
javafile
error got in camera activity
According to your source code, your camera starts reading the text immediately. If you want to first see your text on your camera and only then start reading it we can break down it to following steps:
Open your camera
Navigate to specific text
Finally when you see via your camera the text what you want to read it
I suggest you to do small modifications on your code
Add Capture button on your surfaceview.xml (for example in a code below)
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<SurfaceView
android:id="#+id/surfaceView"
android:layout_width="308dp"
android:layout_height="503dp"
android:layout_marginStart="64dp"
android:layout_marginTop="32dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:id="#+id/capture"
android:layout_marginHorizontal="32dp"
android:layout_marginBottom="32dp"
android:text="Capture"
app:layout_constraintEnd_toEndOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
Move out text processing to separate function
private void capture() {
textRecognizer.setProcessor(new Detector.Processor<TextBlock>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<TextBlock> detections) {
SparseArray<TextBlock> sparseArray = detections.getDetectedItems();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i<sparseArray.size(); ++i){
TextBlock textBlock = sparseArray.valueAt(i);
if (textBlock != null && textBlock.getValue() !=null){
stringBuilder.append(textBlock.getValue() + " ");
}
}
final String stringText = stringBuilder.toString();
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
stringResult = stringText;
resultObtained();
}
});
}
});
}
Capture your text on capture button click
public void buttonStart(View view){
setContentView(R.layout.surfaceview);
Button capture = findViewById(R.id.capture);
capture.setOnClickListener(v -> capture());
textRecognizer();
}
As a result whole MainActivity
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.speech.tts.TextToSpeech;
import android.util.SparseArray;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.text.TextBlock;
import com.google.android.gms.vision.text.TextRecognizer;
import java.io.IOException;
import static android.Manifest.permission.CAMERA;
public class MainActivity extends AppCompatActivity {
private TextView textView;
private SurfaceView surfaceView;
private CameraSource cameraSource;
private TextRecognizer textRecognizer;
private TextToSpeech textToSpeech;
private String stringResult = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityCompat.requestPermissions(this, new String[]{CAMERA}, PackageManager.PERMISSION_GRANTED);
textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
cameraSource.release();
}
private void textRecognizer() {
textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
cameraSource = new CameraSource.Builder(getApplicationContext(), textRecognizer)
.setRequestedPreviewSize(1280, 1024)
.setAutoFocusEnabled(true)
.build();
surfaceView = findViewById(R.id.surfaceView);
Context context = this;
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
cameraSource.start(surfaceView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
}
private void capture() {
textRecognizer.setProcessor(new Detector.Processor<TextBlock>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<TextBlock> detections) {
SparseArray<TextBlock> sparseArray = detections.getDetectedItems();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i<sparseArray.size(); ++i){
TextBlock textBlock = sparseArray.valueAt(i);
if (textBlock != null && textBlock.getValue() !=null){
stringBuilder.append(textBlock.getValue() + " ");
}
}
final String stringText = stringBuilder.toString();
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
stringResult = stringText;
resultObtained();
}
});
}
});
}
private void resultObtained(){
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
textView.setText(stringResult);
textToSpeech.speak(stringResult, TextToSpeech.QUEUE_FLUSH, null, null);
}
public void buttonStart(View view){
setContentView(R.layout.surfaceview);
Button capture = findViewById(R.id.capture);
capture.setOnClickListener(v -> capture());
textRecognizer();
}
}
I want to show the progress of the music played in the seekbar. I am not able to do so. Please help!
I am not understanding what's the problem here. I am very much new to programming. I am actually trying to build an app that can play music and the music progress is displayed on the seekbar
package com.example.musicapp;
import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
MediaPlayer startmusic;
SeekBar seekBar;
ImageButton play;
ImageButton pause;
Handler handler;
Runnable runnable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play=findViewById(R.id.play_button);
seekBar=findViewById(R.id.seekBar);
pause=findViewById(R.id.pause_button);
startmusic=MediaPlayer.create(this,R.raw.music);
}
public void playmusic(View v){
startmusic.start();
play.setImageResource(R.drawable.pause);
play.setVisibility(play.GONE);
pause.setVisibility(pause.VISIBLE);
seekBar.setMax(startmusic.getDuration());
Toast toast=Toast.makeText(getApplicationContext(),"Music is playing", Toast.LENGTH_SHORT);
toast.show();
changeSeekbar();
}
private void changeSeekbar() {
if(startmusic.isPlaying()){
seekBar.setProgress(startmusic.getCurrentPosition());
runnable=new Runnable() {
#Override
public void run() {
changeSeekbar();
handler.postDelayed(runnable,100);
}
};
}
}
public void pausemusic(View v){
if(startmusic.isPlaying()) {
startmusic.pause();
play.setImageResource(R.drawable.pause);
play.setVisibility(play.VISIBLE);
pause.setVisibility(pause.GONE);
seekBar.setProgress(startmusic.getCurrentPosition());
Toast toast=Toast.makeText(getApplicationContext(),"Music is paused", Toast.LENGTH_SHORT);
toast.show();
}
}
}
You can use the common methods of the MediaPlayer class in order to show the progress:
start()
stop()
release() – To prevent memory leaks.
seekTo(position) – This will be used with the SeekBar
isPlaying() – Let us know whether the song is being played or not.
getDuration() – Is used to get the total duration. Using this we’ll
know the upper limit of our SeekBar. This function returns the
duration in milli seconds
setDataSource(FileDescriptor fd) – This is used to set the file to be played.
setVolume(float leftVolume, float rightVolume) – This is used to set
the volume level. The value is a float between 0 or 1.
<SeekBar
android:id="#+id/seekbar"
android:layout_margin="16dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center" />
The code for the MainActivity.java class is given below:
public class MainActivity extends AppCompatActivity implements Runnable {
MediaPlayer startmusic;
SeekBar seekBar;
ImageButton play;
ImageButton pause;
Handler handler;
Runnable runnable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play=findViewById(R.id.play_button);
seekBar=findViewById(R.id.seekBar);
pause=findViewById(R.id.pause_button);
startmusic=MediaPlayer.create(this,R.raw.music);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
seekBarHint.setVisibility(View.VISIBLE);
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
seekBarHint.setVisibility(View.VISIBLE);
int x = (int) Math.ceil(progress / 1000f);
if (x == 0 && startmusic != null && !startmusic.isPlaying()) {
clearMediaPlayer();
MainActivity.this.seekBar.setProgress(0);
}
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
if (startmusic != null && startmusic.isPlaying()) {
startmusic.seekTo(seekBar.getProgress());
}
}
});
}
//its look that you call this method form layout itself
//change your play method defination to
public void playmusic(View v) {
try {
play.setImageResource(R.drawable.pause);
play.setVisibility(play.GONE);
pause.setVisibility(pause.VISIBLE);
Toast toast=Toast.makeText(getApplicationContext(),"Music is playing", Toast.LENGTH_SHORT);
toast.show();
if (startmusic == null) {
startmusic = new MediaPlayer();
}
AssetFileDescriptor afd = context.getResources().openRawResourceFd(/*your raw id resource*/);
if (afd == null)
return;
startmusic.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
startmusic.prepare();
startmusic.setVolume(0.5f, 0.5f);
startmusic.setLooping(false);
seekBar.setMax(startmusic.getDuration());
startmusic.start();
new Thread(this).start();
} catch (Exception e) {
e.printStackTrace();
}
}
public void pausemusic(View v) {
//add null check
if(startmusic != null && startmusic.isPlaying()) {
startmusic.pause();
play.setImageResource(R.drawable.pause);
play.setVisibility(play.VISIBLE);
pause.setVisibility(pause.GONE);
seekBar.setProgress(startmusic.getCurrentPosition());
Toast toast=Toast.makeText(getApplicationContext(),"Music is paused", Toast.LENGTH_SHORT);
toast.show();
}
}
public void run() {
int currentPosition = startmusic.getCurrentPosition();
int total = startmusic.getDuration();
if (currentPosition == total) {
clearMediaPlayer();
}
while (startmusic != null && startmusic.isPlaying() && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = startmusic.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seekBar.setProgress(currentPosition);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
clearMediaPlayer();
}
private void clearMediaPlayer() {
startmusic.stop();
startmusic.release();
startmusic = null;
}
}
I am trying to get data from a server and post it on screen and push with notification. The data is a random number and it's changing second by second.
On opening, the server is working on background and the data is receiving but data is posting on screen one time, it isn't changing and I can't get notification. With button, the data is perfectly posting on screen and it's changing second by second but I can't get notification again.
import android.view.View;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import android.os.Bundle;
import com.star_zero.sse.EventHandler;
import com.star_zero.sse.EventSource;
import com.star_zero.sse.MessageEvent;
//STAR-ZERO/sse-android
public class MainActivity extends AppCompatActivity {
static TextView s;
String a =null;
private final String CHANNEL_ID = "server_notifications";
private final int NOTIFICATIONS_ID = 1;
public EventSource eventSource;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
s=findViewById(R.id.random);
final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
final NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID);
eventSource = new EventSource("path", new EventHandler() {
#Override
public void onOpen() {
}
#Override
public void onMessage(MessageEvent messageEvent) {
a=messageEvent.getData();
try {
builder.setPriority(NotificationCompat.PRIORITY_MAX)
.setAutoCancel(true)
.setContentText(a)
.setContentTitle("ALERT!!!")
.setSmallIcon(R.drawable.noti_icon);
notificationManager.notify (NOTIFICATIONS_ID,builder.build());
s.setText(a);
}
catch (Exception e){
e.printStackTrace();
}
}
#Override
public void onError(Exception e) {
try {
s.setText("error");
}
catch (Exception d) {
d.printStackTrace();
}
}
});
eventSource.connect();
findViewById(R.id.button_open).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
eventSource.connect();
}
});
findViewById(R.id.button_close).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
eventSource.close();
}
});
}
}
You should not build a new notification on each onMessage instead, maintain a global notification reference and update the content. See this response for more details: Update text of notification, not entire notification
I want to achieve Facebook Integration in my app. At this point of time, I have the login and post to wall functionality, but the wall post I have is only like the simple wall post.
I want to achieve this. Just like in every game, they have this kind of facebook feed..
This is the current code I have..
package com.example.facebooktrial;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
#SuppressWarnings("deprecation")
public class AndroidFacebookConnectActivity extends Activity {
Button btnFbLogin;
Button btnPostToWall;
// Your Facebook APP ID
private static String APP_ID = "593769430655402"; // Replace your App ID here
// Instance of Facebook Class
private Facebook facebook;
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnFbLogin = (Button) findViewById(R.id.btnFbLogin);
btnPostToWall = (Button) findViewById(R.id.btnFbPost);
facebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(facebook);
btnFbLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginToFacebook();
}
});
btnPostToWall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
postToWall();
}
});
}
#SuppressWarnings("deprecation")
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
facebook.setAccessToken(access_token);
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this,
new String[] { "email", "publish_stream" },
new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
#SuppressWarnings("deprecation")
public void postToWall() {
// post on user's wall.
facebook.dialog(this, "feed", new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onComplete(Bundle values) {
}
#Override
public void onCancel() {
}
});
}
}
I found the solution. Just make use of a Bundle where you'll store all the necessary information like the picture, name, link and so on.. After that, include that bundle in the Facebook dialog as an argument..
#SuppressWarnings("deprecation")
public void postToWall() {
// post on user's wall.
Bundle params = new Bundle();
params.putString("name", "Check it out, I am playing FLIP game!");
params.putString("caption", "Come on FLIP with me");
params.putString("description", "FLIP!");
params.putString("picture", "http://www.rawk.com/media/images/uploaded/products/2099/flip-hkd-black-complete-skateboard.3043.full.jpg");
facebook.dialog(this, "feed",params, new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onComplete(Bundle values) {
}
#Override
public void onCancel() {
}
});
}