I want to make sos app but errors in blinking method - android

I am very new to android. Following is my code and I am getting these errors.
Cannot resolve symbol params.
Variable "blinkDelay" never assigned.
When i hover the mouse over "Parameters". it says "android.hardware.Camera.Parameters Alt+Enter".
In the following code:
blinkButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String myString = "0101010101";
long blinkDelay 50;
for (int i = 0; i < myString.length(); i++) {
if (myString.charAt(i) == '0') {
params.setFlashMode(Parameters.FLASH_MODE_ON);
} else {
params.setFlashMode(Parameters.FLASH_MODE_OFF);
}
try {
Thread.sleep(blinkDelay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Here is my full MainActivity.java
package com.fusion.flashlight;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
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.ImageButton;
public class MainActivity extends AppCompatActivity {
private CameraManager mCameraManager;
private String mCameraId;
private ImageButton mTorchOnOffButton;
private ImageButton firstButton;
private Button blinkButton;
private Boolean isTorchOn;
private MediaPlayer media;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("MainActivity", "onCreate()");
setContentView(R.layout.activity_main);
mTorchOnOffButton = (ImageButton) findViewById(R.id.btnSwitch);
firstButton = (ImageButton) findViewById(R.id.btn1Switch);
blinkButton = (Button) findViewById(R.id.blinking);
isTorchOn = false;
Boolean isFlashAvailable = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!isFlashAvailable) {
AlertDialog alert = new AlertDialog.Builder(MainActivity.this)
.create();
alert.setTitle("Error !!");
alert.setMessage("Your device doesn't support flash light!");
alert.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// closing the application
finish();
System.exit(0);
}
});
alert.show();
return;
}
mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
mCameraId = mCameraManager.getCameraIdList()[0];
} catch (CameraAccessException e) {
e.printStackTrace();
}
mTorchOnOffButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (isTorchOn) {
turnOffFlashLight();
isTorchOn = false;
} else {
turnOnFlashLight();
isTorchOn = true;
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
blinkButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String myString = "0101010101";
long blinkDelay 50;
for (int i = 0; i < myString.length(); i++) {
if (myString.charAt(i) == '0') {
params.setFlashMode(Parameters.FLASH_MODE_ON);
} else {
params.setFlashMode(Parameters.FLASH_MODE_OFF);
}
try {
Thread.sleep(blinkDelay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
}
public void turnOnFlashLight() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mCameraManager.setTorchMode(mCameraId, true);
playOnOffSound();
mTorchOnOffButton.setImageResource(R.drawable.btn_on);
firstButton.setImageResource(R.drawable.btn11_on);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void turnOffFlashLight() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mCameraManager.setTorchMode(mCameraId, false);
playOnOffSound();
mTorchOnOffButton.setImageResource(R.drawable.btn_off);
firstButton.setImageResource(R.drawable.btn11_off);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void playOnOffSound(){
media = MediaPlayer.create(MainActivity.this, R.raw.light_switch_on);
media.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
//TODO Auto-generated method stub
mp.release();
}
});
media.start();
}
#Override
protected void onStop() {
super.onStop();
if(isTorchOn){
turnOffFlashLight();
}
}
#Override
protected void onPause() {
super.onPause();
if(isTorchOn){
turnOffFlashLight();
}
}
#Override
protected void onResume() {
super.onResume();
if(isTorchOn){
turnOnFlashLight();
}
}
}

For blinkDelay, you are missing an equal symbol when assigning,
For params, I cant see where do you create that variable.
And the other, alt+Enter is for autoImporting the Parameters class by Android Studio.

Cannot resolve symbol params. params not define
Variable "blinkDelay" never assigned. blinkDelay having no initial value
long blinkDelay =50;
When i hover the mouse over "Parameters". it says
"android.hardware.Camera.Parameters Alt+Enter". Alt+Enter for import

Related

TextView is not being updated

I am facing a problem, I have implemented a code, it is showing me message in Logs correctly but it doesn't update the TextView's text. Here i have tried this version. How i can update it? I tried it using threads as well but in vain.
I have seen many solution over this StackOverflow platform but i could not find my any solution for my problem.
package com.example.yousafmoh.seizuredetection;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.AsyncTask;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
public class ledControl extends AppCompatActivity {
// Button btnOn, btnOff, btnDis;
ImageButton On, Off, Discnt, Abt;
TextView txtMessage;
String address = null;
private ProgressDialog progress;
BluetoothAdapter myBluetooth = null;
BluetoothSocket btSocket = null;
private boolean isBtConnected = false;
//SPP UUID. Look for it
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent newint = getIntent();
address = newint.getStringExtra(DeviceList.EXTRA_ADDRESS); //receive the address of the bluetooth device
//view of the ledControl
setContentView(R.layout.activity_led_control);
//call the widgets
On = (ImageButton)findViewById(R.id.on);
Off = (ImageButton)findViewById(R.id.off);
Discnt = (ImageButton)findViewById(R.id.discnt);
Abt = (ImageButton)findViewById(R.id.abt);
txtMessage = (TextView) findViewById(R.id.txtMessage);
new ConnectBT().execute(); //Call the class to connect
//myBluetoothThread();
//commands to be sent to bluetooth
On.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
turnOnLed(); //method to turn on
}
});
Off.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
turnOffLed(); //method to turn off
}
});
Discnt.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Disconnect(); //close connection
}
});
}
private void myBluetoothThread() {
while(true)
{
if (btSocket!=null)
{
try
{
if(isBtConnected) {
InputStream inputStream = btSocket.getInputStream();
for (int i = 0; i <= inputStream.available(); i++) {
//Log.d("data", inputStream.read() + " "+"ok");
int val = inputStream.read();
if (val == 49) // seizure detected
{
this.runOnUiThread(new Runnable() {
#Override
public void run() {
txtMessage.setText("Seizure Detected!!!");
txtMessage.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
Log.d("Message", " Detected");
}
});
Log.d("Message", " Detected");
} else if (val == 48) // no detection
{
this.runOnUiThread(new Runnable() {
#Override
public void run() {
txtMessage.setText("Normal Condition");
txtMessage.setTextColor(getResources().getColor(android.R.color.holo_blue_dark));
Log.d("Message", "not Detected");
}
});
Log.d("Message", "not Detected");
//, Toast.LENGTH_SHORT).show();
}
}
}
}
catch (IOException e)
{
msg("Error");
}
}
}
}
private void Disconnect()
{
if (btSocket!=null) //If the btSocket is busy
{
try
{
btSocket.close(); //close connection
}
catch (IOException e)
{ msg("Error");}
}
finish(); //return to the first layout
}
private void turnOffLed()
{
if (btSocket!=null)
{
try
{
InputStream inputStream = btSocket.getInputStream();
for(int i = 0 ; i <= inputStream.available();i++)
{
Log.d("data",inputStream.read()+" ");
}
Log.d("Bytes available off",String.valueOf(inputStream.available()));
Log.d("Message off",String.valueOf(inputStream.read()));
//btSocket.getOutputStream().write("0".toString().getBytes());
}
catch (IOException e)
{
msg("Error");
}
}
}
private void turnOnLed()
{
if (btSocket!=null)
{
try
{
InputStream inputStream = btSocket.getInputStream();
Log.d("Bytes available on",String.valueOf(inputStream.available()));
Log.d("Message on",String.valueOf(inputStream.read()));
Log.d("Message on",inputStream.toString());
btSocket.getOutputStream().write("1".toString().getBytes());
}
catch (IOException e)
{
msg("Error");
}
}
}
// fast way to call Toast
private void msg(String s)
{
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
}
public void about(View v)
{
if(v.getId() == R.id.abt)
{
Intent i = new Intent(this, AboutActivity.class);
startActivity(i);
}
}
#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_led_control, 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);
}
private class ConnectBT extends AsyncTask<Void, Void, Void> // UI thread
{
private boolean ConnectSuccess = true; //if it's here, it's almost connected
#Override
protected void onPreExecute()
{
progress = ProgressDialog.show(ledControl.this, "Connecting...", "Please wait!!!"); //show a progress dialog
}
#Override
protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background
{
try
{
if (btSocket == null || !isBtConnected)
{
myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);//connects to the device's address and checks if it's available
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();//start connection
progress.dismiss();
}
}
catch (IOException e)
{
ConnectSuccess = false;//if the try failed, you can check the exception here
}
return null;
}
#Override
protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine
{
super.onPostExecute(result);
if (!ConnectSuccess)
{
msg("Connection Failed. Is it a SPP Bluetooth? Try again.");
finish();
}
else
{
msg("Connected.");
isBtConnected = true;
}
if(progress!=null)
progress.dismiss();
if(isBtConnected)
{
myBluetoothThread();
}
}
}
}
Try using this if its a fragment class
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
txtMessage.setText("Normal Condition");
txtMessage.setTextColor(getResources().getColor(android.R.color.holo_blue_dark));
}
});
and this is its an activity
this.runOnUiThread(new Runnable() {
#Override
public void run() {
txtMessage.setText("Normal Condition");
txtMessage.setTextColor(getResources().getColor(android.R.color.holo_blue_dark));
}
});
Another solution u can try is.
You can use handler
Handler handler = new Handler();
handler.post(new Runnable() {
public void run() {
txtMessage.setText("Seizure Detected!!!");
txtMessage.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
}
});
I have read some article somewhere that you should not update your textview directly inside the Runnable Thread. So what I did is i created a function that updates the textview then the Runnable run method calls that function. So It look like this.
public class SampleActivity extends AppCompatActivity {
TextView sample;
int counter = 0;
Handler handler;
Runnable runnable;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sample);
sample = findViewById(R.id.sample);
handler = new Handler();
runnable = new Runnable() {
#Override
public void run() {
counter++;
updateTextView("Counter: " + counter);
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(runnable, 1000);
}
public void updateTextView(String message) {
sample.setText(message);
}
But I tried it calling the sample.setText("Counter: "+counter) inside the Runnable Thread, it still works though.
Btw here is my sample.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/sample"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="SAWSAW"
android:textColor="#000"
android:textSize="32dp" />
</LinearLayout>

TarsosDSP PitchDetection Issue

I am using the audiodispatcher from the TarsosDSPlibrary.
The pitchdetection is used to detect sounds from the mic. Once detected, it switches to the next activity (which is a Maths quiz). After completing the quiz on the next activity, it returns to this activity and starts the process all over again.
What is bugging me is that my APP is working 90% of the time when using the pitchdetection function. However, sometimes it doesn't work and throws an error as follows:
E/AudioRecord: start() status -38
and the app no longers switches to the next activity.
package com.humanfactorsandappliedcognitionlab.research.mathsapp;
import android.content.Context;
import android.content.DialogInterface;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.IBinder;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import java.util.HashMap;
import java.util.Locale;
import java.util.concurrent.RunnableFuture;
import be.tarsos.dsp.AudioDispatcher;
import be.tarsos.dsp.AudioEvent;
import be.tarsos.dsp.io.android.AudioDispatcherFactory;
import be.tarsos.dsp.pitch.PitchDetectionHandler;
import be.tarsos.dsp.pitch.PitchDetectionResult;
import be.tarsos.dsp.pitch.PitchProcessor;
public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener {
MediaPlayer notifySound;
MediaPlayer endSound;
AudioDispatcher dispatcherMAIN;
PitchProcessor pitchProcessorMAIN;
public boolean isListening = false;
TextToSpeech tts;
private int sensitivity = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
notifySound = MediaPlayer.create(this, R.raw.samsung);
endSound = MediaPlayer.create(this, R.raw.ding);
OPTION = dbHandler.getOPTION();
tts = new TextToSpeech(this, this);
tts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
runOnUiThread(new Runnable() {
#Override
public void run(){
}
});
}
#Override
public void onDone(String utteranceId) {
runOnUiThread(new Runnable() {
#Override
public void run(){
startListenToTalk();
}
});
}
#Override
public void onError(String utteranceId) {
}
});
}
private void speakOut() {
Log.e("TTS", "SPEAKING...");
String text = "Please Say Continue to Proceed ";
HashMap<String, String> map = new HashMap<String, String>();
map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "");
tts.speak(text, TextToSpeech.QUEUE_FLUSH, map);
}
private void startListenToTalk() {
dispatcherMAIN = AudioDispatcherFactory.fromDefaultMicrophone(22050, 1024, 0);
pitchProcessorMAIN = new PitchProcessor(PitchProcessor.PitchEstimationAlgorithm.FFT_YIN, 22050, 1024, new PitchDetectionHandler() {
#Override
public void handlePitch(PitchDetectionResult pitchDetectionResult,
AudioEvent audioEvent) {
final float pitchInHz = pitchDetectionResult.getPitch();
runOnUiThread(new Runnable() {
#Override
public void run() {
ImageButton buttonOK = (ImageButton) findViewById(R.id.buttonOK);
TextView textINPUT = (TextView)findViewById(R.id.textINPUT);
if (pitchInHz > sensitivity) {
Log.e("pitch : ", pitchInHz + "");
if (isListening) {
try {
dispatcherMAIN.stop();
Intent gotoMaths = new Intent(MainActivity.this, MathsActivity.class);
startActivity(gotoMaths);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
});
}
});
dispatcherMAIN.addAudioProcessor(pitchProcessorMAIN);
new Thread(dispatcherMAIN, "Audio Dispatcher").start();
isListening = true;
}
#Override
protected void onPause() {
super.onPause();
if (notifySound != null) {
notifySound.release();
}
if (endSound != null) {
endSound.release();
}
if (isListening) {
try {
dispatcherMAIN.stop();
} catch (Exception e) {
e.printStackTrace();
}
isListening = false;
}
finish();
}
#Override
public void onStop(){
super.onStop();
if (tts != null) {
tts.shutdown();
}
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else {
if(OPTION == "3") {
speakOut();
}
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}

Android MediaRecorder recording looping back on itself

I have made an app which uses a MediaRecorder and a MediaPlayer, but whenever I record something and play it, it kinda loops back on itself.
e.g I say, one, two, three, four, five, six, seven, eight, nine, ten
but it plays back as one, two, three three, four four, five five five etc. it gets worse if the recording is longer?
It might be a simple bug, but I don't see it.
Here is my code :
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.CountDownTimer;
import android.os.Environment;
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.CompoundButton;
import android.widget.ProgressBar;
import android.widget.Switch;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
Switch switchPlay;
Button btnRecord, btnDelete;
ProgressBar pBarMetronome;
MediaRecorder mRecorder1, mRecorder2, mRecorder3, mRecorder4, mRecorder5, mRecorder6;
MediaPlayer mp1, mp2, mp3, mp4, mp5, mp6;
String sdPath = "/sdcard/Looper Recordings/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
switchPlay = (Switch)findViewById(R.id.switchPlay);
btnRecord = (Button)findViewById(R.id.buttonRecord);
btnDelete = (Button)findViewById(R.id.buttonDelete);
pBarMetronome = (ProgressBar)findViewById(R.id.progressBarMetronome);
clearFile();
createFile();
lineOne();
}
private void playOne(){
mp1 = new MediaPlayer();
Uri myUri = Uri.parse("/sdcard/Looper Recordings/one.mp3");
mp1.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mp1.setDataSource(getApplicationContext(), myUri);
} catch (IOException e) {
e.printStackTrace();
}
try {
mp1.prepare();
Toast.makeText(MainActivity.this, "preparing", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
mp1.start();
Toast.makeText(MainActivity.this, "play!", Toast.LENGTH_SHORT).show();
}
private void recordOne(){
mRecorder1 = new MediaRecorder();
mRecorder1.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder1.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mRecorder1.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
mRecorder1.setOutputFile(sdPath+"one.mp3");
//mRecorder1.setAudioEncoder(MediaRecorder.getAudioSourceMax());
mRecorder1.setAudioEncodingBitRate(16);
mRecorder1.setAudioSamplingRate(44100);
try {
mRecorder1.prepare();
Toast.makeText(MainActivity.this, "preparing...", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(MainActivity.this, "starting...", Toast.LENGTH_SHORT).show();
mRecorder1.start();
new CountDownTimer(5000,1000){
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
mRecorder1.stop();
Toast.makeText(MainActivity.this, "Stopped!", Toast.LENGTH_SHORT).show();
}
}.start();
}
private void lineOne(){
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
recordOne();
}
});
btnRecord.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new CountDownTimer(4000,1000){
#Override
public void onTick(long millisUntilFinished) {
btnRecord.setText(""+(millisUntilFinished/1000));
playOne();
}
#Override
public void onFinish() {
}
}.start();
}
});
switchPlay.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
//ON
}else{
//OFF
}
}
});
}
private void clearFile(){
File dir = new File(Environment.getExternalStorageDirectory()+"/sdcard/Looper Recordings");
if (dir.isDirectory())
{
String[] children = dir.list();
for (int i = 0; i < children.length; i++)
{
new File(dir, children[i]).delete();
}
}
}
private void createFile(){
File recordingDirectory = new File(Environment.getExternalStorageDirectory()+ File.separator+"Looper Recordings");
if(!recordingDirectory.exists() && !recordingDirectory.isDirectory())
{
// create empty directory
if (recordingDirectory.mkdirs())
{
Toast.makeText(MainActivity.this, "Folder for recordings created!", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this, "Folder for recordings could not be created?", Toast.LENGTH_SHORT).show();
}
}
else
{
}
}
}
I know it's very messy but I'm still prototyping
Thanks to anyone who is willing to help!
It seems you are initializing MediaPlayer multiple times and play them simeltenously
Did you try set looping false.
private void playOne(){
if(mp1 != null && mp1.isPlaying()){
{
mp1.stop();
}
mp1 = new MediaPlayer();
mp1.setLooping(false);
Uri myUri = Uri.parse("/sdcard/Looper Recordings/one.mp3");
mp1.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mp1.setDataSource(getApplicationContext(), myUri);
} catch (IOException e) {
e.printStackTrace();
}
try {
mp1.prepare();
Toast.makeText(MainActivity.this, "preparing", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
mp1.start();
Toast.makeText(MainActivity.this, "play!", Toast.LENGTH_SHORT).show();
}

start/stop button radio stream service

I have the code of a radio stream app from this site radio stream example, but when i want to stop the stream it restarts. The only way to stop it is exit the app and get back to the app via the "recent apps" button or notification screen.
Can someone help me with the code?
StreamService.java
package id.pratama.example.streamingaudio.service;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
import java.io.IOException;
import id.pratama.example.streamingaudio.MainActivity;
import id.pratama.example.streamingaudio.R;
/**
* Created by pratama on 4/22/14.
*/
public class StreamService extends Service implements
MediaPlayer.OnCompletionListener,
MediaPlayer.OnPreparedListener,
MediaPlayer.OnErrorListener,
MediaPlayer.OnBufferingUpdateListener {
/**
* for educational only
*/
// public static final String URL_STREAM = "http://jkt.jogjastreamers.com:8000/jisstereo?s=02766";
// radio UNISI
public static final String URL_STREAM = "http://202.162.32.23:8000";
// notification
private static final int NOTIFICATION_ID = 1;
private PhoneStateListener phoneStateListener;
private TelephonyManager telephonyManager;
private boolean isPausedInCall = false;
private NotificationCompat.Builder builder;
//intent
private Intent bufferIntent;
public static final String BROADCAST_BUFFER = "id.pratama.example.streamingaudio.broadcastbuffer";
private MediaPlayer mediaPlayer = new MediaPlayer();
#Override
public void onCreate() {
super.onCreate();
Log.d("create", "service created");
bufferIntent = new Intent(BROADCAST_BUFFER);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnErrorListener(this);
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.reset();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("play", "play streaming");
telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_OFFHOOK:
case TelephonyManager.CALL_STATE_RINGING:
if (mediaPlayer != null) {
pauseMedia();
isPausedInCall = true;
}
break;
case TelephonyManager.CALL_STATE_IDLE:
if (mediaPlayer != null) {
if (isPausedInCall) {
isPausedInCall = false;
playMedia();
}
}
break;
}
}
};
telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
initNotification();
mediaPlayer.reset();
/**
* play media
*/
if (!mediaPlayer.isPlaying()) {
try {
Log.d("streamm", "" + URL_STREAM);
mediaPlayer.setDataSource(URL_STREAM);
// sent to UI radio is buffer
sendBufferingBroadcast();
mediaPlayer.prepareAsync();
} catch (IllegalArgumentException e) {
Log.d("error", e.getMessage());
} catch (IllegalStateException e) {
Log.d("error", e.getMessage());
} catch (IOException e) {
Log.d("error", e.getMessage());
}
}
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onBufferingUpdate(MediaPlayer mediaPlayer, int i) {
}
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
stopMedia();
stopSelf();
}
#Override
public boolean onError(MediaPlayer mediaPlayer, int what, int extra) {
switch (what) {
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
Toast.makeText(this, "Error not valid playback", Toast.LENGTH_SHORT).show();
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
Toast.makeText(this, "Error server died", Toast.LENGTH_SHORT).show();
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
Toast.makeText(this, "Error unknown", Toast.LENGTH_SHORT).show();
break;
}
return false;
}
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
// sent to UI, audio has buffered
sendBufferCompleteBroadcast();
playMedia();
}
private void pauseMedia() {
if (mediaPlayer.isPlaying())
mediaPlayer.pause();
}
private void playMedia() {
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
}
private void stopMedia() {
if (mediaPlayer.isPlaying())
mediaPlayer.stop();
}
/**
* sent buffering
*/
private void sendBufferingBroadcast() {
bufferIntent.putExtra("buffering", "1");
sendBroadcast(bufferIntent);
}
/**
* sent buffering complete
*/
private void sendBufferCompleteBroadcast() {
bufferIntent.putExtra("buffering", "0");
sendBroadcast(bufferIntent);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d("tag", "remove notification");
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
}
if (phoneStateListener != null) {
telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
}
cancelNotification();
}
/**
* show notificaiton
*/
private void initNotification() {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent intent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Stream Radio")
.setContentText("895 JIZ fm");
builder.setContentIntent(intent);
builder.setOngoing(true);
notificationManager.notify(NOTIFICATION_ID, builder.build());
}
/**
* cancel notification
*/
private void cancelNotification() {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(NOTIFICATION_ID);
builder.setOngoing(false);
}
}
MainActivity.java
package id.pratama.example.streamingaudio;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import id.pratama.example.streamingaudio.service.StreamService;
import id.pratama.example.streamingaudio.utils.Utils;
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
private Intent serviceIntent;
private Button btnPlay;
private static boolean isStreaming = false;
private ProgressDialog pdBuff = null;
private boolean mBufferBroadcastIsRegistered;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnPlay = (Button) findViewById(R.id.btnPlay);
btnPlay.setOnClickListener(this);
serviceIntent = new Intent(this, StreamService.class);
isStreaming = Utils.getDataBooleanFromSP(this, Utils.IS_STREAM);
if (isStreaming)
btnPlay.setText("Stop");
}
#Override
public void onClick(View view) {
if (view == btnPlay) {
Log.d("playStatus", "" + isStreaming);
if (!isStreaming) {
btnPlay.setText("Stop");
startStreaming();
Utils.setDataBooleanToSP(this, Utils.IS_STREAM, true);
} else {
if (isStreaming) {
btnPlay.setText("Start");
Toast.makeText(this, "Stop Streaming..", Toast.LENGTH_SHORT).show();
stopStreaming();
isStreaming = false;
Utils.setDataBooleanToSP(this, Utils.IS_STREAM, false);
}
}
}
}
#Override
protected void onPause() {
super.onPause();
if (mBufferBroadcastIsRegistered) {
unregisterReceiver(broadcastBufferReceiver);
mBufferBroadcastIsRegistered = false;
}
}
#Override
protected void onResume() {
super.onResume();
if (!mBufferBroadcastIsRegistered) {
registerReceiver(broadcastBufferReceiver, new IntentFilter(
StreamService.BROADCAST_BUFFER));
mBufferBroadcastIsRegistered = true;
}
}
private void startStreaming() {
Toast.makeText(this, "Start Streaming..", Toast.LENGTH_SHORT).show();
stopStreaming();
try {
startService(serviceIntent);
} catch (Exception e) {
}
}
private void stopStreaming() {
try {
stopService(serviceIntent);
} catch (Exception e) {
}
}
private BroadcastReceiver broadcastBufferReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent bufferIntent) {
showProgressDialog(bufferIntent);
}
};
private void showProgressDialog(Intent bufferIntent) {
String bufferValue = bufferIntent.getStringExtra("buffering");
int bufferIntValue = Integer.parseInt(bufferValue);
switch (bufferIntValue) {
case 0:
if (pdBuff != null) {
pdBuff.dismiss();
}
break;
case 1:
pdBuff = ProgressDialog.show(MainActivity.this, "",
"Streaming...", true);
break;
}
}
}
finally figured it out myself!
edit the MainActivity.java and use this code
package id.pratama.example.streamingaudio;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import id.pratama.example.streamingaudio.service.StreamService;
import id.pratama.example.streamingaudio.utils.Utils;
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
private Intent serviceIntent;
private Button btnPlay;
private static boolean isStreaming;
private ProgressDialog pdBuff = null;
private boolean mBufferBroadcastIsRegistered;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnPlay = (Button) findViewById(R.id.btnPlay);
btnPlay.setOnClickListener(this);
serviceIntent = new Intent(this, StreamService.class);
isStreaming = Utils.getDataBooleanFromSP(this, Utils.IS_STREAM);
if (isStreaming)
btnPlay.setText("Stop");
}
#Override
public void onClick(View view) {
if (view == btnPlay) {
Log.d("playStatus", "" + isStreaming);
if (!isStreaming) {
btnPlay.setText("Stop");
startStreaming();
isStreaming = true;
Utils.setDataBooleanToSP(this, Utils.IS_STREAM, true);
} else {
if (isStreaming) {
btnPlay.setText("Start");
Toast.makeText(this, "Stop Streaming..", Toast.LENGTH_SHORT).show();
stopStreaming();
isStreaming = false;
Utils.setDataBooleanToSP(this, Utils.IS_STREAM, false);
}
}
}
}
#Override
protected void onPause() {
super.onPause();
if (mBufferBroadcastIsRegistered) {
unregisterReceiver(broadcastBufferReceiver);
mBufferBroadcastIsRegistered = false;
}
}
#Override
protected void onResume() {
super.onResume();
if (!mBufferBroadcastIsRegistered) {
registerReceiver(broadcastBufferReceiver, new IntentFilter(
StreamService.BROADCAST_BUFFER));
mBufferBroadcastIsRegistered = true;
}
}
private void startStreaming() {
Toast.makeText(this, "Start Streaming..", Toast.LENGTH_SHORT).show();
stopStreaming();
try {
startService(serviceIntent);
} catch (Exception e) {
}
}
private void stopStreaming() {
try {
stopService(serviceIntent);
} catch (Exception e) {
}
}
private BroadcastReceiver broadcastBufferReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent bufferIntent) {
showProgressDialog(bufferIntent);
}
};
private void showProgressDialog(Intent bufferIntent) {
String bufferValue = bufferIntent.getStringExtra("buffering");
int bufferIntValue = Integer.parseInt(bufferValue);
switch (bufferIntValue) {
case 0:
if (pdBuff != null) {
pdBuff.dismiss();
}
break;
case 1:
pdBuff = ProgressDialog.show(MainActivity.this, "",
"Streaming...", true);
break;
}
}
}

Android MediaPlayer seekTo() function working incorrect

I have a problem when using MediaPlayer to play video from url.
The follow of program : create an activity to play video -> press Home button -> back to app.
The requirement is video play from start, when press Home button video continuos play(only audio), and when back to app, video must play continuous(combine movie and audio).
The first, I created a MediaPlayer variable to play video. When Home button is pressed, MediaPlayer play continuous. But when back to app, video cannot displayed(black screen). So, I created other MediaPlayer variable to solved this issue. But when I using seekTo() function to seek second MediaPlayer to position of first MediaPlayer, this function is working incorrect.
import java.io.IOException;
import com.example.videotest.R;
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Toast;
public class PlayVideoActivity extends Activity implements OnClickListener,SurfaceHolder.Callback, FGMediaController.MediaPlayerControl {
SurfaceView videoSurface,videoSurfaceFullscreen,videoSurfaceSmallsceen;
MediaPlayer player, backupPlayer;
FGMediaController controller;
LinearLayout llControllerBar;
public boolean isFullscreen = false;
int videoDuration;
int videoCurrent;
SurfaceHolder viewHolder = null;
boolean isPaused = false;
String videoUrl = "http://cdn-smatopi.tv-bank.com/movie/867/867-32/867-32-2015042306-D3/hls/hls3/867-32-2015042306-D3-HLS3.m3u8";
Button btnSeek, btnRelease;
int currentPos = 30000;
boolean videoPrepared = false;
boolean backupPrepared = false;
boolean mVideoSizeIsSet = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.playvideo);
btnSeek = (Button) findViewById(R.id.btnSeek);
btnRelease = (Button) findViewById(R.id.btnRelease);
videoSurface = (SurfaceView)findViewById(getResources().getIdentifier("vvVideo", "id", getPackageName()));
SurfaceHolder videoHolder = videoSurface.getHolder();
videoHolder.addCallback(this);
player = new MediaPlayer();
backupPlayer = new MediaPlayer();
controller = new FGMediaController(this);
try {
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setDataSource(this, Uri.parse(videoUrl));
player.prepareAsync();
//backupPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
//backupPlayer.setDataSource(this, Uri.parse(videoUrl));
//backupPlayer.prepareAsync();
} catch (Exception e) {
e.printStackTrace();
}
btnSeek.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.e("Huhu",currentPos + "");
backupPlayer.seekTo(currentPos);
}
});
btnRelease.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
backupPlayer.stop();
backupPlayer.release();
}
});
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
}
});
player.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
controller.setMediaPlayer(PlayVideoActivity.this);
controller.setAnchorView((FrameLayout) findViewById(PlayVideoActivity.this.getResources().getIdentifier("videoSurfaceContainer", "id", PlayVideoActivity.this.getPackageName())));
player.start();
}
});
}
#Override
public void onDestroy(){
//backupPlayer.release();
player.release();
super.onDestroy();
}
#Override
public void onResume(){
Log.e("Surface Created","OnResume");
super.onResume();
}
// Implement SurfaceHolder.Callback
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
Log.e("Surface Created","Surface Created! " + holder);
if(viewHolder != null){
viewHolder = holder;
backupPlayer = new MediaPlayer();
try {
backupPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
backupPlayer.setDataSource(this, Uri.parse(videoUrl));
backupPlayer.prepareAsync();
backupPlayer.setDisplay(holder);
backupPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
backupPrepared = true;
backupPlayer.start();
}
});
backupPlayer.setOnVideoSizeChangedListener(new OnVideoSizeChangedListener() {
#Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
// TODO Auto-generated method stub
if (width == 0 || height == 0){
Toast.makeText(getApplicationContext(),"Width = 0 Height = 0"+ mp.getDuration(), Toast.LENGTH_LONG).show();
}else{
if(backupPrepared){
backupPrepared = false;
currentPos = player.getCurrentPosition();
player.reset();
Toast.makeText(getApplicationContext(),"Seek To "+ backupPlayer.getCurrentPosition() + " | " + backupPlayer.isPlaying() + "|" + currentPos, Toast.LENGTH_LONG).show();
Log.e("Huhu","Seek To "+ backupPlayer.getCurrentPosition() + " | " + backupPlayer.isPlaying() + "|" + currentPos);
backupPlayer.seekTo(currentPos); // If you set currentPos = 20000ms or 30000ms backupPlayer can to seek, but if you set currentPos = 10000ms backupPlayer cannot seek !
}
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}else{
player.setDisplay(holder);
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
Log.e("Surface Created","surfaceDestroyed! " + player.getCurrentPosition());
viewHolder = holder;
}
// End MediaPlayer.OnPreparedListener
// Implement VideoMediaController.MediaPlayerControl
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return true;
}
#Override
public boolean canSeekForward() {
return true;
}
#Override
public int getBufferPercentage() {
return 0;
}
#Override
public int getCurrentPosition() {
//Log.printLog(Log.ERROR, "CURRENT :"+player.getCurrentPosition());
int current = 0;
try{
current = player.getCurrentPosition();
}catch(Exception e){
e.printStackTrace();
}
return current;
}
#Override
public int getDuration() {
int duration = 0;
try{
duration = player.getDuration();
}catch(Exception e){
e.printStackTrace();
}
return duration;
}
#Override
public boolean isPlaying() {
boolean isPlaying = false;
try{
isPlaying = player.isPlaying();
}catch(Exception e){
e.printStackTrace();
}
return isPlaying;
}
#Override
public void pause() {
player.pause();
}
#Override
public void seekTo(int i) {
player.seekTo(i);
}
#Override
public void start() {
player.start();
}
#Override
public boolean isFullScreen() {
return isFullscreen;
}
#Override
public void toggleFullScreen() {
// TODO Auto-generated method stub
}
#Override
public void doBackPressed() {
// TODO Auto-generated method stub
}
#Override
public void onClick(View v) {
}
}

Categories

Resources