I have a sound file running in a loop on a service.
The activity that starts the service also has a button. When I press the button I want the sound file in the service to stop playing, i.e kill the service. Have been unsuccessful so far as when I call stopService() the service continues to run.
Any Ideas? Thanks.
Activity
public class AlarmPage extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm_page);
TextView timeview = (TextView)findViewById(R.id.timefiled);
final Button dismissButton =(Button)findViewById(R.id.dismissButton);
Bundle b = getIntent().getExtras();
String hrval = b.getString("HR");
String minval = b.getString("MN");
timeview.setText(hrval + ":" + minval);
final Intent alarmring = new Intent(this, alarmringService.class);
startService(alarmring);
dismissButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent alarmmenu = new Intent(getApplicationContext(),SetAlarmsActivity.class);
startActivity(alarmmenu);
System.out.println("Button:" + dismissButton.isPressed());
stopService(alarmring);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.alarm_page, menu);
return true;
}
}
Service
public class alarmringService extends IntentService{
public alarmringService(){
super("alarmringService");
// TODO Auto-generated constructor stub
}
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.drawable.startrekcommsound);
mp.setLooping(true);
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
}
}
I can't see why it doesn't work since I'm not an expert, but to fix your problem you could use intents. By the way, IntentService stops itself when it has no more work!
Try this: Send to the IntentService an Intent with a command saying to stop itself.
Then in onHandleIntent() check if this was the request and call stopSelf() from inside the Service.
Moreover, I don't know how MediaPlayer works, but maybe it has his own thread and you should stop this thread too!
Related
i have a develop an app to searching and play the video, in my project ive face a diffculty to pass the path of the searched video to video play activity. when i put actual path of the video directly in to the player activity it palys the video but if i get the video name from the intent and then i convert it as path of that video. it dont get paly. and my program does not show any error
i cant get the intent data that i passed from the first activity it shows "null" when i set that data into the textview pls help me to recover this problem
HERE IS MY FIRST ACTIVITY
public class FirstActivity extends Activity {
EditText et;
Button bt;
String filename;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.firstscreen);
et = (EditText)findViewById(R.id.editText1);
filename = et.getText().toString();
bt = (Button)findViewById(R.id.button1);
final Intent i = new Intent(this, MainActivity.class);
i.putExtra("text_label", filename);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
startActivity(i);
}
});
}
}
AND THIS IS MY SECOND ACTIVITY TO THE VIDEO PLAYER
public class MainActivity extends Activity implementsSurfaceHolder.Callback{
MediaPlayer mediaPlayer;
urfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean pausing = false;;
String uriString;
String stringPaths= "/sdcard/video/";
String stringPath;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonPlayVideo = (Button)findViewById(R.id.playvideoplayer);
Button buttonPauseVideo = (Button)findViewById(R.id.pausevideoplayer);
Intent i = getIntent();
uriString = i.getStringExtra("text_label");
stringPath = stringPaths+uriString+".3gp";
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView)findViewById(R.id.surfaceview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setFixedSize(176, 300);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mediaPlayer = new MediaPlayer();
buttonPlayVideo.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
pausing = false;
if(mediaPlayer.isPlaying()){
mediaPlayer.reset();
}
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDisplay(surfaceHolder);
try {
mediaPlayer.setDataSource(stringPath);
mediaPlayer.prepare();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaPlayer.start();
}});
buttonPauseVideo.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(pausing){
pausing = false;
mediaPlayer.start();
}
else{
pausing = true;
mediaPlayer.pause();
}
}});
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
}
so here is my questions
1. did i pass the intent corectly to the second activity.
2. how should i concatenate that get intent data with the file path string.
pls help me
im struck with this.
The problem lies in onCreate method - your intent is created each time the activity is created but not shown to the user so the TextView is empty.
Try to put extra to the intent in onClick - and there you can also check if textView is empty. It will be something like this:
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
filename = et.getText().toString();
Intent i = new Intent(FirstActivity.this, MainActivity.class);
i.putExtra("text_label", filename);
startActivity(i);
}
});
You can still create intent in the onCreate method's scope keeping it final but assigning extra in the onClick method.
Also consider that et.getText() can be null and et.getText().toString() can generate NullPointerException, so I'd rather extracted it to the Editable variable and check if it's not null and not empty.
I was wondering, how can I keep the device listening for voice commands with voice recognition while the device is asleep? The idea I have is that I would like the device to respond to my voice, even if I have the screen locked or the screen has timed out.
Is this possible? I have tried using this as a service and an interface and it stops listening once the screen locks. Can I receive any help with this? This is my class.
public class VoiceEngineService extends Activity {
private boolean isSpeakingDone = false; // default setting
private SpeechRecognizer sr = SpeechRecognizer.createSpeechRecognizer(this);
private AudioManager mAudioManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.wait_for_speech);
// mute beep sound
mAudioManager.setStreamSolo(AudioManager.STREAM_VOICE_CALL, true);
sr.setRecognitionListener(new listener());
Intent i = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); // LANGUAGE_MODEL_WEB_SEARCH
i.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getApplication()
.getClass().getName());
i.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 6);
i.putExtra(RecognizerIntent.EXTRA_PROMPT, "");
i.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS, 5500);
sr.startListening(i);
}
class listener implements RecognitionListener {
#Override
public void onReadyForSpeech(Bundle params) {
// TODO Auto-generated method stub
}
#Override
public void onBeginningOfSpeech() {
// TODO Auto-generated method stub
}
#Override
public void onRmsChanged(float rmsdB) {
// TODO Auto-generated method stub
}
#Override
public void onBufferReceived(byte[] buffer) {
// TODO Auto-generated method stub
}
#Override
public void onEndOfSpeech() {
// TODO Auto-generated method stub
}
#Override
public void onError(int error) {
// TODO Auto-generated method stub
if (SharedPref.getVoiceController() == false) {
sr.cancel();
Intent i = new Intent();
sr.startListening(i);
} else {
sr.stopListening();
sr.destroy();
finish();
}
}
#Override
public void onResults(Bundle results) {
// TODO Auto-generated method stub
isSpeakingDone = true;
ArrayList<String> mDataList = results
.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
Intent i = new Intent();
i.putStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS, mDataList);
setResult(RESULT_OK, i);
finish();
}
#Override
public void onPartialResults(Bundle partialResults) {
// TODO Auto-generated method stub
}
#Override
public void onEvent(int eventType, Bundle params) {
// TODO Auto-generated method stub
}
} // end listener class
#Override
protected void onPause() {
if ((isSpeakingDone == false)) {
finish();
}
super.onPause();
}
#Override
protected void onStop() {
// when speaking is true finish() has already been called
if (isSpeakingDone == false) {
finish();
}
super.onStop();
}
#Override
protected void onDestroy() {
sr.stopListening();
sr.destroy();
super.onDestroy();
}
}
You have to implement your voice listener in a service. Create a class that extends 'Service' and make up some logic to take care of recording.
If you tried already the service, then it might be that you tried to redirect commands to an activity which most likely has been stopped by Android OS. Generally when talking about doing stuff when phone is in lock mode, you only can hope to accomplish tasks in one or more services coupled togethe.
When you are in Activity, of course wen the activity goes out of scope it will be shut down by Android OS. but services can still run in background unless shut dow mm explicitly by your own code or in rare cases that Android will recognize that it needs memory and processor power for other tasks.
I'm developing a radio app in which I have written MediaPlayer class inside Service,on button click starting and closing service to start and stop MediaPlayer.But in the project I'm facing two problems
1.I want to show progress while preparing music.although I have written code inside service so not able to show ProgressBar.
2.when we volume up then instead of music volume ringing volume is increasing.
I spent my lot time and didn't get success can any please tell me how to resolve this.Your valuable suggestion would be great appreciated.
PlayerService.java
public class PlayerService extends Service implements OnPreparedListener {
private MediaPlayer mPlayer;
public PlayerService() {
// TODO Auto-generated constructor stub
super();
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
try {
mPlayer = new MediaPlayer();
mPlayer.setDataSource(Live.mUrl);
mPlayer.prepare();
mPlayer.setOnPreparedListener(this);
// mVisualizerView = (VisualizerView)
// findViewById(R.id.visualizerView);
// mVisualizerView.link(mPlayer);
// Start with just line renderer
// addLineRenderer();
} catch (Exception e) {
// TODO: handle exception
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mPlayer.start();
return 0;
}
#Override
public void onDestroy() {
mPlayer.release();
super.onDestroy();
}
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
}
}
Check out registerMediaButtonEventReceiver(ComponentName broadcastReceiver);
Define a BroadcastReceiver that handles ACTION_MEDIA_BUTTON. The recieved intent includes a single extra field, EXTRA_KEY_EVENT, containing the key event that caused the broadcast. You can use this key event to get which key was pressed.
This is just a sample code. syntax errors may be there.
// in onCreate of activity
registerMediaButtonEventReceiver(mediaReceiver );
// later somewhere in activity.
MediaButton_Receiver mediaReceiver = new MediaButton_Receiver();
class MediaButton_Receiver implements BroadcastReceiver {
void onReceive(Intent intent) {
KeyEvent ke = (KeyEvent)intent.getExtra(Intent.EXTRA_KEY_EVENT);
if (ke .getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN) {
//Decrease your volume
}
// Similarly other key codes .......
}
}
Unregister the receiver in onPause() or onStop()
In my project I am using binder mechanism to communicate to remote service. The remote service class will call JNI function and updates to UI for every 10 seconds. The JNI function has below code
static int n = 100;
return ++n;
This JNI function calling in Service class and updating to UI like below
public class MyService extends Service{
private static final String TAG = "MyService";
private final Handler serviceHandler = new Handler();
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
System.out.println("inside service onCreate");
Log.d(TAG, "entered onStart");
serviceHandler.removeCallbacks(sendUpdatesToUI);
serviceHandler.postDelayed(sendUpdatesToUI, 1000); // 1 second
}
1. private IMyService.Stub bioStub = new IMyService.Stub() {
2.
3. #Override
4. public int intFromJNI() throws RemoteException {
5. // TODO Auto-generated method stub
6. int libData = Abcd.intFromJNI();
7. System.out.println("inside ****** stub"+libData);
8. return libData;
}
};
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
System.out.println("inside binder ");
return bioStub;
}
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
Log.d(TAG, "entered Runnable");
try {
bioStub.intFromJNI();
serviceHandler.postDelayed(this, 10000);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
}
This service class is calling in Activty
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Intent serviceIntent=new Intent();
serviceIntent.setClass(context, MyService.class);
boolean ok=bindService(serviceIntent, mServiceConnection , Context.BIND_AUTO_CREATE);
Log.v("ok", String.valueOf(ok));
}
private ServiceConnection mServiceConnection=new ServiceConnection(){
#Override
public void onServiceConnected(ComponentName arg0, IBinder service) {
// TODO Auto-generated method stub
System.out.println("inside ServiceConnection");
myService = IMyService.Stub.asInterface(service);
try {
Log.d("Client", "entered mServiceConnection");
8. int jniValue = myService.intFromJNI();
9. System.out.println("value if JNI==>"+jniValue);
10.
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
// TODO Auto-generated method stub
}
};
Here my problem is, The service class is not updating UI for every 10 seconds and the value is not incremeting in UI but the value is incrementing for every 10 seconds in service class i.e the print statement below is updating for every 10 seconds which is in line Number 7 in above code(Service).
System.out.println("inside ****** stub"+libData);
But I want to it update in UI also. i.e the statement line num 10.
System.out.println("value if JNI==>"+jniValue);
I`t is not happening in my code . How to solve this one .`
You are missing any way for the Service to tell the Activity about new events. The call from the Activity to the Service, intFromJNI, is a one-off function call which happens just once - it has no ongoing responsibility for telling the UI about changes in future.
You should add some listener class. For example, add IMyServiceListener.aidl with something like this:
package com.something;
interface IMyServiceListener {
void valueUpdated(int newValue);
}
And then in IMyService.aidl add this:
import com.something.IMyServiceListener;
void addListener(in IMyServiceListener newListener);
Then, within your IMyService.Stub class you will need to implement addListener - you should add the resulting object to some array of listeners, and call valueUpdated on each listener, each time the value changes.
Within the activity, you should call myService.addListener and pass in some object which receives notification of the changes. You can then display that on the UI within the activity.
I'm playing video via MediPlayer in my android application and have SeekBar displayed. Now I want this seeks bar to automatically update as the video progresses so it should automatically move from left to right. At the moment, (code below) the bar updates and this is done via running thread, that every second updates the progress of seekBar. The problem is it is not smooth and as seekBar is updated via its seekProgress() the video stops for split second and all is very jumpy. Now I would like it to have updated more often then every second as well as keep functionality that I already implemented to allow user to tap on the bar and change progress of the video.
I'm after something like Android MediaPLayer application have, seekBar is on transparent background and all is smooth and I have no idea how it is done.
No, currently as you see from the code below thread updates every second as it sleeps inside f run method. I've also tried to use handlers to update UI thread, effect was the same. I also extended SeekBar to its own class, had thread there and this was no good either, exactly same effect.
If anyone can explain to me how to solve this problem and how its done with other player appls that would be great.
public class FightPlayerActivity extends Activity implements Runnable, OnSeekBarChangeListener, SurfaceHolder.Callback, OnPreparedListener {
private MediaPlayer mp=null;
private SeekBar seekBar;
private Thread progressBarUpdater;
private String filePath;
private Handler handler=new Handler();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Toast.makeText(this,"Create ", 2000).show();
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
public void onStop()
{
super.onStop();
mp.stop();
mp.reset();
mp.release();
}
public void run()
{
while(true)
{
try {
progressBarUpdater.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
seekBar.setProgress(mp.getCurrentPosition());
// handler does have same effect, so video stops for split second
//handler.postDelayed(this, 1000);
}
}
public void onStart()
{
super.onStart();
setContentView(R.layout.fight_player);
filePath=getIntent().getStringExtra("filename");
filePath=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)+"/FightAll_BJJ_Scoring/"+filePath;
Toast.makeText(this,filePath, 2000).show();
// seek bar
seekBar=(SeekBar) findViewById(R.id.seek_bar);
seekBar.setOnSeekBarChangeListener(this);
try {
SurfaceView sv=(SurfaceView) findViewById(id.video_preview);
SurfaceHolder sh=sv.getHolder();
sh.addCallback(this);
sh.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void stop(View view)
{
mp.seekTo(0);
mp.pause();
}
public void pause(View view)
{
mp.pause();
}
public void play(View view)
{
mp.start();
}
public void surfaceCreated(SurfaceHolder holder) {
try {
mp=new MediaPlayer();
mp.setDataSource(filePath);
mp.setDisplay(holder);
mp.setOnPreparedListener(this);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.prepare();
//handler.removeCallbacks(this);
//handler.postDelayed(this, 1000);
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
public void onPrepared(MediaPlayer mediaplayer) {
mp.start();
seekBar.setMax(mp.getDuration());
progressBarUpdater=new Thread(this);
progressBarUpdater.start();
//handler.postDelayed(this, 1000);
}
public void onProgressChanged(SeekBar sb,int progress,boolean fromUser)
{
//Toast.makeText(this, progress, 2000).show();
mp.seekTo(progress);
}
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
onProgressChanged(seekBar,seekBar.getProgress(),true);
}
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}
Your major problem is in your onProgressChanged() method.
You are seeking to the specified position every time the seekBar progress changes, even when it is done programmatically. Which means that every time you call seekBar.setProgress(mp.getCurrentPosition()), onProgressChanged() will be fired.
So we change it to the following:
public void onProgressChanged(SeekBar sb, int progress, boolean fromUser) {
if (fromUser) {
mp.seekTo(progress);
}
}
That way it will only be fired when the user moves the seekBar.
Moreover, according to this answer, it would be better to replace your while(true) loop with:
public void run() {
seekBar.setProgress(mp.getCurrentPosition());
if (mp.getCurrentPosition() < mp.getDuration()) {
seekBar.postDelayed(this, MILLISECONDS);
}
}