Here's how I wrote my app.
MusicList
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.music_layout);
startService(new Intent(getApplicationContext(), LockScreenService.class));
//other codes
});
//send chosen music
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(lockIsChosen!=null) {
//other codes
try {
Intent i = new Intent("my.action");
i.putExtra("posLock", newPosition2).putExtra("songlistLock", mySongs).putExtra("lockSound", "lock");
sendBroadcast(i);
}catch (Exception e) {
Log.e(TAG, "Intent error");
}
finish();
}
if(unlockIsChosen!=null) {
//other codes
try {
Intent i = new Intent("my.action.unlock");
i.putExtra("posUnlock", newPosition3).putExtra("songlistUnlock", mySongs).putExtra("unlockSound", "unlock");
sendBroadcast(i);
}catch (Exception e) {
Log.e(TAG, "Intent error2");
}
finish();
}
}
});
And in my service class, this is what I wrote
LockScreenService
public class LockScreenService extends Service {
MediaPlayer mp;
ArrayList<File> mySongs;
ArrayList<File> mySongs2;
Uri u;
Uri u2;
AudioManager am;
BroadcastReceiver receiver;
public class LockScreenReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
am = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
if(action.equals(Intent.ACTION_BOOT_COMPLETED)) {
Intent service = new Intent(context, LockScreenService.class);
context.startService(service);
}
if(action.equals("my.action")) {
Bundle b = intent.getExtras();
mySongs = (ArrayList) b.getParcelableArrayList("songlistLock");
int position = b.getInt("posLock", 0);
u = Uri.parse(mySongs.get(position).toString());
}
if(action.equals("my.action.unlock")) {
Bundle b = intent.getExtras();
mySongs2 = (ArrayList) b.getParcelableArrayList("songlistUnlock");
int position = b.getInt("posUnlock", 0);
u2 = Uri.parse(mySongs2.get(position).toString());
}
if (action.equals(Intent.ACTION_SCREEN_ON) && am.getRingerMode() == AudioManager.RINGER_MODE_NORMAL)
{
if(u2!=null) {
stopPlaying();
mp = MediaPlayer.create(context, u2);
mp.start();
Toast.makeText(context, u2.toString(), Toast.LENGTH_SHORT).show();
}
}
else if (action.equals(Intent.ACTION_SCREEN_OFF) && am.getRingerMode() == AudioManager.RINGER_MODE_NORMAL)
{
if(u!=null) {
stopPlaying();
mp = MediaPlayer.create(context, u);
mp.start();
Toast.makeText(context, u.toString(), Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
#SuppressWarnings("deprecation")
public void onCreate() {
//Start listening for the Screen On, Screen Off, and Boot completed actions
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_BOOT_COMPLETED);
//Set up a receiver to listen for the Intents in this Service
receiver = new LockScreenReceiver();
registerReceiver(receiver, filter);
registerReceiver( receiver, new IntentFilter( "my.action" ) );
registerReceiver( receiver, new IntentFilter( "my.action.unlock" ) );
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Override
public void onDestroy() {
unregisterReceiver(receiver);
stopPlaying();
super.onDestroy();
}
private void stopPlaying() {
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
}
}
And here's my Manifest
AndroidManifest
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_SERVICE"/>
<service android:name=".LockScreenService" />
<receiver
android:name=".LockScreenService$LockScreenReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
What I want to do is, when user booted their phone, I want the receiver to be able to play the media player. So that an audio will play whenever user turn on or turn off their phone screen without needing to set it again manually through the app.
I don't know what's causing my app to crash. Is there something that I'm missing?
Create a standalone BroadcastReceiver. Your service is not started at this time. So you are accessing Broadcast reciever through a service which actually doesn't exists. I think, thus creating a seperate class for BroadcastReceiver will do the trick.
You Broadcast receiver name and android manifest receiver name is totally differ.
LockScreenReceiver or in manifest it is LockScreenService$LockScreenReceiver.
you have to manage it with different class of broadcastReciver.
Related
I spend about 20 hours until now and my problem there still is .
I am creating an android application that has several Activities (mainMenu , aboutUs,setting).
I followed the best answered of below link and that was O.K .
Music played using asyncTask isn't stopping by using cancel
When i run my app,(my code is in mainActivity ), the music begin and it does not stop when navigate to other Activities . This is GOOD .
But i put a ToggleButton in my setting_activity Activity that i hope this Button starts and stops this music. NOW my question is how can i stop and/or start music again from setting_activity ?
in another solution :
I create a class MusicManager and i call it`s start and stop .
But this was several problems too :
Music started in mainMenu_activity but only play for about 15 seconds and then stopped.
I could not stop the music from another activities.At this time i play music in mainMenua_ctivity as this line codes :
MusicManager mm = new MusicManager(this, R.raw.background_sound);
mm.play();
How can i stop playing that ?
3. The music stopped when i navigate to other activities .
public class MusicManager implements OnPreparedListener {
static MediaPlayer mPlayer;
Context context;
private int mySoundId;
public MusicManager(Context ctx, int musicID) {
context = ctx;
mySoundId = musicID;
mPlayer = MediaPlayer.create(context, mySoundId);
mPlayer.setOnPreparedListener(this);
}
public void play() {
mPlayer = MediaPlayer.create(context, mySoundId);
}
public void stop() {
mPlayer.stop();
mPlayer.release();
}
#Override
public void onPrepared(MediaPlayer player) {
player.start();
mPlayer.setLooping(true);
mPlayer.setVolume(25, 25);
}
}
Finally i want to play a background music in all activities without stop/start music .
How can i do it ?
You could put the music player in a service. This would make it independent from the Activities and you would still be able to control the playback through intents.
Here are some code example about it: https://stackoverflow.com/a/8209975/2804473
The code below is written by Synxmax here at StackOverflow, and covered in the link above:
public class BackgroundSoundService extends Service {
private static final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.idil);
player.setLooping(true); // Set looping
player.setVolume(100,100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
public void onStart(Intent intent, int startId) {
// TO DO
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
public void onStop() {
}
public void onPause() {
}
#Override
public void onDestroy() {
player.stop();
player.release();
}
#Override
public void onLowMemory() {
}
}
#Override
public void onCreate (){
super.onCreate();
Player = MediaPlayer.create(this, R.raw.jingle);
mPlayer.setOnErrorListener(this);
if(mPlayer!= null)
{
mPlayer.setLooping(true);
mPlayer.setVolume(100,100);
}
mPlayer.setOnErrorListener(new OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int
extra){
onError(mPlayer, what, extra);
return true;
}
});
}
public class serv extends Service{
MediaPlayer mp;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public void onCreate()
{
mp = MediaPlayer.create(this, R.raw.b);
mp.setLooping(false);
}
public void onDestroy()
{
mp.stop();
}
public void onStart(Intent intent,int startid){
Log.d(tag, "On start");
mp.start();
}
}
The top answer is correct, however you have to add the service to the manifest file.
<service android:enabled="true" android:name="BackgroundSoundService" />
Simon's answer above is correct. I had similar problem where I have fragments which had music player and I needed to go back to that UI on click of a button. Your case is similar but instead of going back to UI, you want to control playback. Here is what I did for my application. This takes care of playback of audio list including shuffle and repeat functionality. This takes care of showing media controls in notification bar too.
Create a service MusicPlayerService with following code:
public class MediaPlayerService extends Service implements MediaPlayer.OnCompletionListener,
MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, MediaPlayer.OnSeekCompleteListener,
MediaPlayer.OnInfoListener, MediaPlayer.OnBufferingUpdateListener,
AudioManager.OnAudioFocusChangeListener {
public static final String ACTION_PLAY = "pkg_name.ACTION_PLAY";
public static final String ACTION_PAUSE = "pkg_name.ACTION_PAUSE";
public static final String ACTION_PREVIOUS = "pkg_name.ACTION_PREVIOUS";
public static final String ACTION_NEXT = "pkg_name.ACTION_NEXT";
public static final String ACTION_STOP = "pkg_name.ACTION_STOP";
private MediaPlayer mediaPlayer;
//MediaSession
private MediaSessionManager mediaSessionManager;
private MediaSessionCompat mediaSession;
private MediaControllerCompat.TransportControls transportControls;
//AudioPlayer notification ID
private static final int NOTIFICATION_ID = 101;
//Used to pause/resume MediaPlayer
private int resumePosition;
// Binder given to clients
private final IBinder iBinder = new LocalBinder();
//List of available Audio files
private ArrayList<PlayableTrack> audioList;
private int audioIndex = -1;
//Handle incoming phone calls
private boolean ongoingCall = false;
private PhoneStateListener phoneStateListener;
private TelephonyManager telephonyManager;
private Bitmap albumArtBitmap;
private boolean shuffle = false;
private boolean repeat = false;
private Random rand;
/**
* Service lifecycle methods
*/
#Override
public IBinder onBind(Intent intent) {
return iBinder;
}
#Override
public void onCreate() {
super.onCreate();
// Perform one-time setup procedures
// Manage incoming phone calls during playback.
// Pause MediaPlayer on incoming call,
// Resume on hangup.
callStateListener();
//ACTION_AUDIO_BECOMING_NOISY -- change in audio outputs -- BroadcastReceiver
registerBecomingNoisyReceiver();
//Listen for new Audio to play -- BroadcastReceiver
register_playNewAudio();
rand = new Random();
StorageUtil storage = new StorageUtil(getApplicationContext());
shuffle = storage.loadShuffleRepeat("Shuffle");
repeat = storage.loadShuffleRepeat("Repeat");
}
//The system calls this method when an activity, requests the service be started
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
//Load data from SharedPreferences
StorageUtil storage = new StorageUtil(getApplicationContext());
audioList = storage.loadAudio();
audioIndex = storage.loadAudioIndex();
if (audioIndex != -1 && audioIndex < audioList.size()) {
//index is in a valid range
activeAudio = audioList.get(audioIndex);
} else {
stopSelf();
}
} catch (NullPointerException e) {
stopSelf();
}
if (mediaSessionManager == null) {
try {
initMediaSession();
initMediaPlayer();
} catch (RemoteException e) {
e.printStackTrace();
stopSelf();
}
buildNotification(PlaybackStatus.PLAYING);
}
//Handle Intent action from MediaSession.TransportControls
handleIncomingActions(intent);
return super.onStartCommand(intent, flags, startId);
}
#Override
public boolean onUnbind(Intent intent) {
mediaSession.release();
removeNotification();
return super.onUnbind(intent);
}
#Override
public void onDestroy() {
super.onDestroy();
if (mediaPlayer != null) {
stopMedia();
mediaPlayer.reset();
}
//Disable the PhoneStateListener
if (phoneStateListener != null) {
telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
}
removeNotification();
//unregister BroadcastReceivers
unregisterReceiver(becomingNoisyReceiver);
unregisterReceiver(playNewAudio);
Picasso.get().cancelRequest(target);
}
/**
* Service Binder
*/
public class LocalBinder extends Binder {
public MediaPlayerService getService() {
// Return this instance of LocalService so clients can call public methods
return MediaPlayerService.this;
}
}
/**
* MediaPlayer callback methods
*/
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
//Invoked indicating buffering status of
//a media resource being streamed over the network.
}
#Override
public void onCompletion(MediaPlayer mp) {
//Invoked when playback of a media source has completed.
stopMedia();
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
//Invoked when there has been an error during an asynchronous operation
switch (what) {
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
Log.d("MediaPlayer Error", "MEDIA ERROR NOT VALID FOR PROGRESSIVE PLAYBACK " + extra);
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
Log.d("MediaPlayer Error", "MEDIA ERROR SERVER DIED " + extra);
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
Log.d("MediaPlayer Error", "MEDIA ERROR UNKNOWN " + extra);
break;
}
return false;
}
#Override
public void onPrepared(MediaPlayer mp) {
//Invoked when the media source is ready for playback.
playMedia();
}
#Override
public void onAudioFocusChange(int focusState) {
//Invoked when the audio focus of the system is updated.
switch (focusState) {
case AudioManager.AUDIOFOCUS_GAIN:
// resume playback
if (mediaPlayer == null) initMediaPlayer();
else if (!mediaPlayer.isPlaying()) mediaPlayer.start();
mediaPlayer.setVolume(1.0f, 1.0f);
break;
case AudioManager.AUDIOFOCUS_LOSS:
// Lost focus for an unbounded amount of time: stop playback and release media player
if (mediaPlayer.isPlaying()) mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer = null;
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
// Lost focus for a short time, but we have to stop
// playback. We don't release the media player because playback
// is likely to resume
if (mediaPlayer.isPlaying()) mediaPlayer.pause();
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
// Lost focus for a short time, but it's ok to keep playing
// at an attenuated level
if (mediaPlayer.isPlaying()) mediaPlayer.setVolume(0.1f, 0.1f);
break;
}
}
/**
* MediaPlayer actions
*/
private void initMediaPlayer() {
if (mediaPlayer == null)
mediaPlayer = new MediaPlayer();//new MediaPlayer instance
//Set up MediaPlayer event listeners
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnErrorListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnSeekCompleteListener(this);
mediaPlayer.setOnInfoListener(this);
//Reset so that the MediaPlayer is not pointing to another data source
mediaPlayer.reset();
mediaPlayer.setAudioAttributes(new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.build());
try {
// Set the data source to the mediaFile location
mediaPlayer.setDataSource(activeAudio.getFileLocation());
} catch (IOException e) {
e.printStackTrace();
stopSelf();
}
mediaPlayer.prepareAsync();
}
public void playMedia() {
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
buildNotification(PlaybackStatus.PLAYING);
Intent intent = new Intent("PLAYBACK_STARTED");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
private void stopMedia() {
if (mediaPlayer == null) return;
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
}
public void pauseMedia() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
resumePosition = mediaPlayer.getCurrentPosition();
}
buildNotification(PlaybackStatus.PAUSED);
Intent intent = new Intent("PLAYBACK_PAUSED");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
private void resumeMedia() {
if (!mediaPlayer.isPlaying()) {
mediaPlayer.seekTo(resumePosition);
mediaPlayer.start();
buildNotification(PlaybackStatus.PLAYING);
Intent intent = new Intent("PLAYBACK_STARTED");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
}
/**
* ACTION_AUDIO_BECOMING_NOISY -- change in audio outputs
*/
private BroadcastReceiver becomingNoisyReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//pause audio on ACTION_AUDIO_BECOMING_NOISY
pauseMedia();
buildNotification(PlaybackStatus.PAUSED);
}
};
private void registerBecomingNoisyReceiver() {
//register after getting audio focus
IntentFilter intentFilter = new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
registerReceiver(becomingNoisyReceiver, intentFilter);
}
/**
* Handle PhoneState changes
*/
private void callStateListener() {
// Get the telephony manager
telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
//Starting listening for PhoneState changes
phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
//if at least one call exists or the phone is ringing
//pause the MediaPlayer
case TelephonyManager.CALL_STATE_OFFHOOK:
case TelephonyManager.CALL_STATE_RINGING:
if (mediaPlayer != null) {
pauseMedia();
ongoingCall = true;
}
break;
case TelephonyManager.CALL_STATE_IDLE:
// Phone idle. Start playing.
if (mediaPlayer != null) {
if (ongoingCall) {
ongoingCall = false;
resumeMedia();
}
}
break;
}
}
};
// Register the listener with the telephony manager
// Listen for changes to the device call state.
telephonyManager.listen(phoneStateListener,
PhoneStateListener.LISTEN_CALL_STATE);
}
/**
* MediaSession and Notification actions
*/
private void initMediaSession() throws RemoteException {
if (mediaSessionManager != null) return; //mediaSessionManager exists
mediaSessionManager = (MediaSessionManager) getSystemService(Context.MEDIA_SESSION_SERVICE);
// Create a new MediaSession
mediaSession = new MediaSessionCompat(getApplicationContext(), "AudioPlayer");
//Get MediaSessions transport controls
transportControls = mediaSession.getController().getTransportControls();
//set MediaSession -> ready to receive media commands
mediaSession.setActive(true);
//indicate that the MediaSession handles transport control commands
// through its MediaSessionCompat.Callback.
mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
//Set mediaSession's MetaData
updateMetaData();
// Attach Callback to receive MediaSession updates
mediaSession.setCallback(new MediaSessionCompat.Callback() {
// Implement callbacks
#Override
public void onPlay() {
super.onPlay();
resumeMedia();
}
#Override
public void onPause() {
super.onPause();
pauseMedia();
}
});
}
private void updateMetaData() {
fetchBitmapOfAlbum();
// Update the current metadata
mediaSession.setMetadata(new MediaMetadataCompat.Builder()
.putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, albumArtBitmap)
.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, "")
.putString(MediaMetadataCompat.METADATA_KEY_ALBUM, activeAudio.getAlbumName())
.putString(MediaMetadataCompat.METADATA_KEY_TITLE, activeAudio.getTrackName())
.build());
}
private Target target = new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
albumArtBitmap = bitmap;
}
#Override
public void onBitmapFailed(Exception e, Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
};
private void fetchBitmapOfAlbum() {
Picasso.get().load(activeAudio.getAlbumArt())
.placeholder(R.drawable.rotate_animation)
.error(R.drawable.ic_blank)
.into(target);
}
private void buildNotification(PlaybackStatus playbackStatus) {
int notificationAction = android.R.drawable.ic_media_pause;//needs to be initialized
PendingIntent play_pauseAction = null;
//Build a new notification according to the current state of the MediaPlayer
if (playbackStatus == PlaybackStatus.PLAYING) {
notificationAction = android.R.drawable.ic_media_pause;
//create the pause action
play_pauseAction = playbackAction(1);
} else if (playbackStatus == PlaybackStatus.PAUSED) {
notificationAction = android.R.drawable.ic_media_play;
//create the play action
play_pauseAction = playbackAction(0);
}
fetchBitmapOfAlbum(); //replace with your own image
String channelId = "";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
channelId = "APP_MUSIC";
}
// Create a new Notification
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId)
// Hide the timestamp
.setShowWhen(false)
// Set the Notification style
.setStyle(new androidx.media.app.NotificationCompat.MediaStyle()
// Attach our MediaSession token
.setMediaSession(mediaSession.getSessionToken())
// Show our playback controls in the compat view
.setShowActionsInCompactView(0, 1, 2))
// Set the Notification color
.setColor(ContextCompat.getColor(this.getApplicationContext(), R.color.colorAccent))
// Set the large and small icons
.setLargeIcon(albumArtBitmap)
.setSmallIcon(R.drawable.ic_stat_notifications)
// Set Notification content information
.setContentText(activeAudio.getTrackName())
.setTicker(activeAudio.getAlbumName() + "-" + activeAudio.getTrackName())
.setOngoing(true)
.setContentTitle(activeAudio.getAlbumName())
.setContentInfo(activeAudio.getTrackName())
// Add playback actions
.addAction(notificationAction, "pause", play_pauseAction)
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(NOTIFICATION_ID, notificationBuilder.build());
}
private PendingIntent playbackAction(int actionNumber) {
Intent playbackAction = new Intent(this, MediaPlayerService.class);
switch (actionNumber) {
case 0:
// Play
playbackAction.setAction(ACTION_PLAY);
return PendingIntent.getService(this, actionNumber, playbackAction, 0);
case 1:
// Pause
playbackAction.setAction(ACTION_PAUSE);
return PendingIntent.getService(this, actionNumber, playbackAction, 0);
default:
break;
}
return null;
}
private void removeNotification() {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(NOTIFICATION_ID);
}
private void handleIncomingActions(Intent playbackAction) {
if (playbackAction == null || playbackAction.getAction() == null) return;
String actionString = playbackAction.getAction();
if (actionString.equalsIgnoreCase(ACTION_PLAY)) {
transportControls.play();
} else if (actionString.equalsIgnoreCase(ACTION_PAUSE)) {
transportControls.pause();
}
}
/**
* Play new Audio
*/
private BroadcastReceiver playNewAudio = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//Get the new media index form SharedPreferences
audioIndex = new StorageUtil(getApplicationContext()).loadAudioIndex();
if (audioIndex != -1 && audioIndex < audioList.size()) {
//index is in a valid range
activeAudio = audioList.get(audioIndex);
} else {
stopSelf();
}
//A PLAY_NEW_AUDIO action received
//reset mediaPlayer to play the new Audio
stopMedia();
mediaPlayer.reset();
initMediaPlayer();
updateMetaData();
buildNotification(PlaybackStatus.PLAYING);
}
};
private void register_playNewAudio() {
//Register playNewMedia receiver
IntentFilter filter = new IntentFilter(MainActivity.Broadcast_PLAY_NEW_AUDIO);
registerReceiver(playNewAudio, filter);
}
public boolean isPlaying(){
return mediaPlayer.isPlaying();
}
public void setShuffle(){
if(shuffle) shuffle=false;
else shuffle=true;
StorageUtil storage = new StorageUtil(getApplicationContext());
storage.storeShuffleRepeat("Shuffle", shuffle);
}
public void setRepeat(){
if(repeat) repeat=false;
else repeat=true;
StorageUtil storage = new StorageUtil(getApplicationContext());
storage.storeShuffleRepeat("Repeat", repeat);
}
}
Add the service to your manifest
<service android:name=".service.MediaPlayerService" />
Bind the service in MainActivity and declare methods to call the service
public class MainActivity {
private MediaPlayerService player;
boolean serviceBound = false;
public static final String Broadcast_PLAY_NEW_AUDIO = "pkg_name.PlayNewAudio";
//Binding this Client to the AudioPlayer Service
private ServiceConnection serviceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
MediaPlayerService.LocalBinder binder = (MediaPlayerService.LocalBinder) service;
player = binder.getService();
serviceBound = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
serviceBound = false;
}
};
// Call this method to play track
public void playAudio(int audioIndex, ArrayList<PlayableTrack> updatedList) {
//Check is service is active
audioList = updatedList;
if (!serviceBound) {
Intent playerIntent = new Intent(this, MediaPlayerService.class);
startService(playerIntent);
bindService(playerIntent, serviceConnection, Context.BIND_AUTO_CREATE);
} else {
//Service is active
//Send a broadcast to the service -> PLAY_NEW_AUDIO
Intent broadcastIntent = new Intent(Broadcast_PLAY_NEW_AUDIO);
sendBroadcast(broadcastIntent);
}
}
// Additional methods for control
public void start() {
player.playMedia();
}
public void pause() {
player.pauseMedia();
}
public boolean isPlaying() {
if (player != null && serviceBound) {
return player.isPlaying();
}
return false;
}
}
This is my solution:
1- first add a music file in raw folder (in my case coffee.mp3)
2- create a class named BackgroundSoundService that extends Service:
public class BackgroundSoundService extends Service {
MediaPlayer mediaPlayer;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mediaPlayer = MediaPlayer.create(this, R.raw.coffee);
mediaPlayer.setLooping(true); // Set looping
mediaPlayer.setVolume(100, 100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction().equals("PLAY")) {
if(mediaPlayer.isPlaying() == false) {
mediaPlayer.start();
Toast.makeText(getApplicationContext(), "Music Is Playing", Toast.LENGTH_SHORT).show();
}
}
if (intent.getAction().equals("STOP")) {
this.stopService(intent);
Toast.makeText(getApplicationContext(), "Music Stopped", Toast.LENGTH_SHORT).show();
}
return startId;
}
#Override
public void onDestroy() {
mediaPlayer.stop();
mediaPlayer.release();
}
#Override
public void onLowMemory() {
}
}
do not forget to define this service in application tag of android manifest.xml:
<service android:name=".BackgroundSoundService" />
3- for play button in your activity use this code:
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String action = "PLAY";
Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
myService.setAction(action);
startService(myService);
}
});
3- for stop button in your activity use this code:
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String action = "STOP";
Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
myService.setAction(action);
startService(myService);
}
});
I have created a simple android app with two activity which play music in background service, the app will pause the music if app is not visible to the user (for example user pressed home button).
you can see it in my github for more details.
I am working on Integrating a Quickblox based video chat into my app.
Here i am running a listener in foreground service which listens to the video call initiated by opponent. here in switch statement, at call accept state i am calling a new activity which is nothing but a dialler screen with accept and disconnect button. accept button connects the call but disconnect cuts the call and closes the activity, but again the same activity (dialler screen) opens repeatedly after multiple times, My question is how to make service to call once and ignore the rest calls if its disconnected. (Am sending reject signal to opponent thus call drops from opponent but here service calls activity repeatedly though call is dropped from opponent)
Here is the code
VchatListener service with OnQBVideoChatListener with switch statement has a accept call state which calls new activity
public class VChatListener extends Service {
private VideoChatConfig videoChatConfig;
private CallState state;
QBUser a=DataHolder.getInstance().getCurrentQbUser();
/* private AlertDialog alertDialog;*/
private static final int notif_id=1;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
this.startForeground();
}
private void startForeground() {
startForeground(notif_id, getMyActivityNotification(""));
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
//startForeground(FOREGROUND_ID, notification);
Runnable runnable = new Runnable() {
#Override
public void run() {
try {
Log.i("******Service Call user Here","now*******");
if(a!=null){
Log.i("******Service testing",""+a);
}else{
Log.i("******Service testing user","nothing");
}
Log.i("***Still","running****");
QBVideoChatController.getInstance().setQBVideoChatListener(a, qbVideoChatListener);
} catch (NullPointerException ex) {
ex.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
}
};
};
new Thread(runnable).start();
return Service.START_REDELIVER_INTENT;
private OnQBVideoChatListener qbVideoChatListener = new OnQBVideoChatListener() {
#Override
public void onVideoChatStateChange(CallState state, VideoChatConfig receivedVideoChatConfig) {
Debugger.logConnection("onVideoChatStateChange: " + state);
videoChatConfig = receivedVideoChatConfig;
/*if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}*/
Log.i("service state",""+state.toString());
switch (state) {
case ACCEPT:
Intent intent = new Intent(VChatListener.this, CallActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(VideoChatConfig.class.getCanonicalName(), videoChatConfig);
startActivity(intent);
// showCallDialog();
Log.i("service state 1",""+state.toString());
break;
case ON_ACCEPT_BY_USER:
Log.i("service state 2",""+state.toString());
/* QBVideoChatController.getInstance().onAcceptFriendCall(videoChatConfig, null);*/
//startVideoChatActivity();
break;
case ON_REJECTED_BY_USER:
Log.i("service state 3",""+state.toString());
/*Toast.makeText(VChatListener.this, "Rejected by user", Toast.LENGTH_SHORT).show();*/
break;
case ON_DID_NOT_ANSWERED:
Log.i("service state 4",""+state.toString());
/* Toast.makeText(VChatListener.this, "User did not answer", Toast.LENGTH_SHORT).show();*/
break;
case ON_CANCELED_CALL:
videoChatConfig = null;
Log.i("service state 5","nothing");
/*if (alertDialog != null && alertDialog.isShowing()){
alertDialog.dismiss();
}
autoCancelHandler.removeCallbacks(autoCancelTask);*/
break;
}
}
};
public void onDestroyed(){
super.onDestroy();
}
private Notification getMyActivityNotification(String text){
// The PendingIntent to launch our activity if the user selects
// this notification
CharSequence title = getText(R.string.title_activity);
/* PendingIntent contentIntent = PendingIntent.getActivity(this,0, new Intent(this,Appointment.class), 0);*/
return new Notification.Builder(this)
.setContentTitle(title)
.setContentText(text)
.setSmallIcon(R.drawable.ic_launcher)
.getNotification();
}
}
Here is the activity which will be called by service the end button associated with function end, disconnects the call.
public class CallActivity extends Activity {
private ProgressDialog progressDialog;
private VideoChatConfig videoChatConfig;
private VChatListener vChatListener;
QBUser qbuser;
MediaPlayer mMediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_call);
ImageButton b1 = (ImageButton) findViewById(R.id.button1);
ImageButton b2 = (ImageButton) findViewById(R.id.button2);
playRingtone();
/*while(!b1.isPressed() || !b2.isPressed()){
playRingtone();
}*/
progressDialog = new ProgressDialog(this);
progressDialog.setMessage(getString(R.string.please_wait));
progressDialog
.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
// TODO add stopCalling here, send Cancel message if
// need
// XMPPSender.sendCancelCallMsg(videoChatConfig);
// QBVideoChatController.getInstance().stopCalling();
}
});
qbuser = DataHolder.getInstance().getCurrentQbUser();
videoChatConfig = getIntent().getParcelableExtra(
VideoChatConfig.class.getCanonicalName());
;
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onAcceptCallClick();
mMediaPlayer.stop();
}
private void onAcceptCallClick() {
//mMediaPlayer.stop();
QBVideoChatController.getInstance().acceptCallByFriend(
videoChatConfig, null);
startVideoChatActivity();
}
private void startVideoChatActivity() {
if (videoChatConfig.getCallType() == CallType.VIDEO_AUDIO) {
Intent intent = new Intent(getBaseContext(),
ActivityVideoChat.class);
intent.putExtra(VideoChatConfig.class.getCanonicalName(),
videoChatConfig);
startActivity(intent);
} else if(videoChatConfig.getCallType() == CallType.AUDIO) {
Intent intent = new Intent(getBaseContext(),
ActivityAudioChat.class);
intent.putExtra(VideoChatConfig.class.getCanonicalName(),
videoChatConfig);
startActivity(intent);
}
}
});
}
public void end(View view)
{
mMediaPlayer.stop();
QBVideoChatController.getInstance().finishVideoChat(videoChatConfig);
XMPPSender.sendCancelCallMsg(videoChatConfig);
QBVideoChatController.getInstance().stopCalling();
super.onDestroy();
finish();
}
public void playRingtone() {
try {
Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(this, alert);
final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
if (audioManager.getStreamVolume(AudioManager.STREAM_RING) != 0) {
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
mMediaPlayer.setLooping(true);
mMediaPlayer.prepare();
mMediaPlayer.start();
}
} catch(Exception e) {
e.printStackTrace();
}
/* try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(),
notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}*/
}
}
to limit the service to call activity once i included in manifest launch mode = "singleTask" which launches activity once, but when activity get closed by disconnect it is called again and doesnt stop.
<activity
android:name="com.yugays.videochatsample.ui.CallActivity"
android:label="#string/app_name"
android:launchMode="singleTask"
android:screenOrientation="landscape" >
</activity>
How to stop activity getting created after call is disconnected and activity is closed.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 8 years ago.
Improve this question
I am new to android.I have seen many examples.but all doesn't help me.I want example or tutorial for How to Record incoming and outgoing calls in android.can anyone refer good tutorial for this?
Ok, for this first of all you need to use Device Policy Manager, and need to make your device Admin device. After that you have to create one BroadCaast receiver and one service. I am posting code here and its working fine.
MainActivity:
public class MainActivity extends Activity {
private static final int REQUEST_CODE = 0;
private DevicePolicyManager mDPM;
private ComponentName mAdminName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
// Initiate DevicePolicyManager.
mDPM = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
mAdminName = new ComponentName(this, DeviceAdminDemo.class);
if (!mDPM.isAdminActive(mAdminName)) {
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mAdminName);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "Click on Activate button to secure your application.");
startActivityForResult(intent, REQUEST_CODE);
} else {
// mDPM.lockNow();
// Intent intent = new Intent(MainActivity.this,
// TrackDeviceService.class);
// startService(intent);
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (REQUEST_CODE == requestCode) {
Intent intent = new Intent(MainActivity.this, TService.class);
startService(intent);
}
}
}
//DeviceAdminDemo class
public class DeviceAdminDemo extends DeviceAdminReceiver {
#Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
}
public void onEnabled(Context context, Intent intent) {
};
public void onDisabled(Context context, Intent intent) {
};
}
//TService Class
public class TService extends Service {
MediaRecorder recorder;
File audiofile;
String name, phonenumber;
String audio_format;
public String Audio_Type;
int audioSource;
Context context;
private Handler handler;
Timer timer;
Boolean offHook = false, ringing = false;
Toast toast;
Boolean isOffHook = false;
private boolean recordstarted = false;
private static final String ACTION_IN = "android.intent.action.PHONE_STATE";
private static final String ACTION_OUT = "android.intent.action.NEW_OUTGOING_CALL";
private CallBr br_call;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy() {
Log.d("service", "destroy");
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// final String terminate =(String)
// intent.getExtras().get("terminate");//
// intent.getStringExtra("terminate");
// Log.d("TAG", "service started");
//
// TelephonyManager telephony = (TelephonyManager)
// getSystemService(Context.TELEPHONY_SERVICE); // TelephonyManager
// // object
// CustomPhoneStateListener customPhoneListener = new
// CustomPhoneStateListener();
// telephony.listen(customPhoneListener,
// PhoneStateListener.LISTEN_CALL_STATE);
// context = getApplicationContext();
final IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_OUT);
filter.addAction(ACTION_IN);
this.br_call = new CallBr();
this.registerReceiver(this.br_call, filter);
// if(terminate != null) {
// stopSelf();
// }
return START_NOT_STICKY;
}
public class CallBr extends BroadcastReceiver {
Bundle bundle;
String state;
String inCall, outCall;
public boolean wasRinging = false;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_IN)) {
if ((bundle = intent.getExtras()) != null) {
state = bundle.getString(TelephonyManager.EXTRA_STATE);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
inCall = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
wasRinging = true;
Toast.makeText(context, "IN : " + inCall, Toast.LENGTH_LONG).show();
} else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
if (wasRinging == true) {
Toast.makeText(context, "ANSWERED", Toast.LENGTH_LONG).show();
String out = new SimpleDateFormat("dd-MM-yyyy hh-mm-ss").format(new Date());
File sampleDir = new File(Environment.getExternalStorageDirectory(), "/TestRecordingDasa1");
if (!sampleDir.exists()) {
sampleDir.mkdirs();
}
String file_name = "Record";
try {
audiofile = File.createTempFile(file_name, ".amr", sampleDir);
} catch (IOException e) {
e.printStackTrace();
}
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
recorder = new MediaRecorder();
// recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION);
recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(audiofile.getAbsolutePath());
try {
recorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
recorder.start();
recordstarted = true;
}
} else if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
wasRinging = false;
Toast.makeText(context, "REJECT || DISCO", Toast.LENGTH_LONG).show();
if (recordstarted) {
recorder.stop();
recordstarted = false;
}
}
}
} else if (intent.getAction().equals(ACTION_OUT)) {
if ((bundle = intent.getExtras()) != null) {
outCall = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
Toast.makeText(context, "OUT : " + outCall, Toast.LENGTH_LONG).show();
}
}
}
}
}
//Permission in manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
//Declare following thing in manifest:
Declare DeviceAdminDemo class to manifest:
<receiver
android:name="com.example.voicerecorder1.DeviceAdminDemo"
android:description="#string/device_description"
android:label="#string/device_admin_label"
android:permission="android.permission.BIND_DEVICE_ADMIN" >
<meta-data
android:name="android.app.device_admin"
android:resource="#xml/my_admin" />
<intent-filter>
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
<action android:name="android.app.action.DEVICE_ADMIN_DISABLED" />
<action android:name="android.app.action.DEVICE_ADMIN_DISABLE_REQUESTED" />
</intent-filter>
</receiver>
<service android:name=".TService" >
</service>
//my_admin.xml
<device-admin xmlns:android="http://schemas.android.com/apk/res/android" >
<uses-policies>
<force-lock />
</uses-policies>
</device-admin>
well you could use an android app called Call Recorder from Google Play
Call Recorder
i've never tried it before but it was the first link in go*gle
good luck with that.
Aaron PM
I want to give the user the ability to unregister/register the broadcast receiver with the click of the button.
When the button is pressed for the first time, the broadcast receiver is registered and a toast comes up when the device is connected.
My problem is when I press the button again, the broadcast reciever is not unregistering like I specified.
Can somebody please check if there is something wrong with mylogic, or explain to me if there is another approach to detecting when usb is unplugged/plugged in?
Thank You.
btn.setOnClickListener(new View.OnClickListener() {
BroadcastReceiver receiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
int plugged = intent.getIntExtra(
BatteryManager.EXTRA_PLUGGED, -1);
if (plugged == BatteryManager.BATTERY_PLUGGED_USB) {
Toast.makeText(getApplicationContext(),
"Connected to USB", Toast.LENGTH_SHORT).show();
}
if (plugged != BatteryManager.BATTERY_PLUGGED_USB) {
Toast.makeText(getApplicationContext(),
"Disconnected from USB", Toast.LENGTH_SHORT)
.show();
}
}
};
#Override
public void onClick(View v) {
int mReceiver = 0;
mReceiver++;
if (mReceiver % 2 == 1) {
IntentFilter filter = new IntentFilter(
Intent.ACTION_BATTERY_CHANGED);
registerReceiver(receiver, filter);
}
if (mReceiver % 2 == 0) {
unregisterReceiver(receiver);
Toast.makeText(getApplicationContext(),
"Should be unregistered", Toast.LENGTH_LONG).show();
}
}
});
Your mReceiver value will always be equal to 1 because of these lines:
int mReceiver = 0;
mReceiver++;
I assume that mReceiver is an instance variable, in which case it should just be:
mReceiver++;
Better still, create a boolean value called isRegistered.
#Override
public void onClick(View v) {
if (!isRegistered) {
IntentFilter filter = new IntentFilter(
Intent.ACTION_BATTERY_CHANGED);
registerReceiver(receiver, filter);
isRegistered = true;
}
else {
unregisterReceiver(receiver);
isRegistered = false;
}
}
I know there are a lot of questions on this already but it doesn't seem to work, so basically I have a custom Service, the service works fine when the timer inside it expires, and calls the stopservice method. however when I try and stop the service from another activity it doesn't work?
code for custom service:
public class ConnectionService extends Service {
Intent service_intent;
Timer t;
int expiry_time = 0;
int timer_tick_starter = 0;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
t = new Timer();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
service_intent = intent;
Log.d("onConnectionService", "onStartCommand");
expiry_time = Integer.parseInt(intent.getStringExtra("expiry"));
//convert the minutes to milliseconds
timer_tick_starter = (expiry_time * 60000);
Log.d("onConnectionService", "Expiry Time (in milliseconds) " + timer_tick_starter);
} catch (Exception e) {
Log.d("onConnectionService", e.getMessage().toString());
}
//timer will only start to run on the expiry_time which will then close the connection
t.schedule(new TimerTask() {
#Override
public void run() {
Log.d("onConnectionService", "inside expiry time");
//close the connection
stopService(service_intent);
}
}, 30000);
return START_NOT_STICKY;
}
#Override
public boolean stopService(Intent name) {
Log.d("onConnectionService", "StopService called");
String message = name.getStringExtra("msg");
//broadcast sender
Intent intent = new Intent();
intent.putExtra("msg", message);
intent.setAction("fi.android.inetkeyapplication.CUSTOM_INTENT");
intent.putExtra("is_selected", UserConnectionState.getInstance().is_selected);
sendBroadcast(intent);
Log.d("onConnectionService", "Service has been killed");
return super.stopService(name);
}
#Override
public void onDestroy() {
Log.d("onConnectionService", "Destroy called");
}
}
here I start the service from onCreate:
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
Log.d("onConfigurationActivity", "Service starting ");
// Intent i = new Intent(ConfigurationActivity.this, ConnectionService.class);
Intent i = new Intent(context, ConnectionService.class);
i.putExtra("expiry", "1");
startService(i);
}
});
thread.start();
however later in my app when I try to kill it from the activity in which I start it, it doesn't work:
Button exit_button = (Button) findViewById(R.id.btnExit);
connect_button.setTypeface(roboto_light);
exit_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//do closing call
response_close = "";
//need to close service
//also kill the service
Log.d("onConfigurationActivity", "killing service");
Intent intent = new Intent(context, ConnectionService.class);
intent.putExtra("msg", "You have been disconnected");
stopService(intent);
}
});
I have tried my class - ConfigurationActivity.this (as context) and I have tried (this) at the moment I am using a custom context that I simply get inside onCreate. however nothing seems to work what am I missing?
thanx
ok so apparently stopping the service doesn't stop the timer. so I just called cancel() on timer