I am trying to stream shoutcast URL in my app through media player and it works fine ( no stops after sometime) for API 14 and older (ie. in my friend mobile it works fine who has note 2) but it stops playing after sometime for higher API (ie: my android version is 7 Samsung galaxy S6 edge plus) and it stops for me after sometime.
How can i solve this issue?
below is the code:
ActivityRadio.java
public class ActivityRadio extends BaseActivity {
private String[] navMenuTitles;
private TypedArray navMenuIcons;
Button startButton, stopButton;
static Context context;
boolean isPlaying;
Intent streamService;
SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.radio);
context = getApplicationContext();
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items); // load
// titles
// from
// strings.xml
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);// load icons from
// strings.xml
set(navMenuTitles, navMenuIcons);
AdView adView = (AdView)this.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
//.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
// .addTestDevice("TEST_DEVICE_ID")
.build();
adView.loadAd(adRequest);
startButton = (Button) findViewById(R.id.startButton);
stopButton = (Button) findViewById(R.id.stopButton);
prefs = PreferenceManager.getDefaultSharedPreferences(context);
getPrefs();
streamService = new Intent(ActivityRadio.this, ServiceRadio.class);
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startService(streamService);
startButton.setEnabled(false);
}
});
stopButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
stopService(streamService);
startButton.setEnabled(true);
}
});
}
public void getPrefs() {
isPlaying = prefs.getBoolean("isPlaying", false);
if (isPlaying) startButton.setEnabled(false);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK ) {
Intent intent = new Intent(ActivityRadio.this, ActivityMain.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
}
return super.onKeyDown(keyCode, event);
}
}
ServiceRadio.java
public class ServiceRadio extends Service implements OnAudioFocusChangeListener {
private static final String TAG = "StreamService";
MediaPlayer mp;
boolean isPlaying;
SharedPreferences prefs;
SharedPreferences.Editor editor;
private AudioManager mAudioManager;
Notification n;
NotificationManager notificationManager;
// Change this int to some number specifically for this app
int notifId = 5315;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#SuppressWarnings("deprecation")
#Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate");
// Init the SharedPreferences and Editor
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
editor = prefs.edit();
// Set up the buffering notification
notificationManager = (NotificationManager) getApplicationContext()
.getSystemService(NOTIFICATION_SERVICE);
Context context = getApplicationContext();
String notifTitle = context.getResources().getString(R.string.app_name);
String notifMessage = context.getResources().getString(R.string.buffering);
n = new Notification();
n.icon = R.drawable.icon;
n.tickerText = "Buffering";
n.when = System.currentTimeMillis();
Intent nIntent = new Intent(context, ActivityRadio.class);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, nIntent, 0);
n.setLatestEventInfo(context, notifTitle, notifMessage, pIntent);
notificationManager.notify(notifId, n);
// It's very important that you put the IP/URL of your ShoutCast stream here
// Otherwise you'll get Webcom Radio
String url = "http://listen.shoutcast.com/fmd";
mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mp.setDataSource(url);
mp.prepare();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
Log.e(TAG, "SecurityException");
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
Log.e(TAG, "IllegalStateException");
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(TAG, "IOException");
}
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
}
#Override
public void onAudioFocusChange(int focusChange) {
if(focusChange<=0) {
mp.pause();
} else {
mp.start();
}
}
#SuppressWarnings("deprecation")
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStart");
mp.start();
// Set the isPlaying preference to true
editor.putBoolean("isPlaying", true);
editor.commit();
Context context = getApplicationContext();
String notifTitle = context.getResources().getString(R.string.app_name);
String notifMessage = context.getResources().getString(R.string.now_playing);
n.icon = R.drawable.icon;
n.tickerText = notifMessage;
n.flags = Notification.FLAG_NO_CLEAR;
n.when = System.currentTimeMillis();
Intent nIntent = new Intent(context, ActivityRadio.class);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, nIntent, 0);
n.setLatestEventInfo(context, notifTitle, notifMessage, pIntent);
// Change 5315 to some nother number
notificationManager.notify(notifId, n);
return Service.START_STICKY; // not supported in SDK
}
#Override
public void onDestroy() {
Log.d(TAG, "onDestroy");
mp.stop();
mp.release();
mp = null;
editor.putBoolean("isPlaying", false);
editor.commit();
notificationManager.cancel(notifId);
mAudioManager.abandonAudioFocus(this);
}
}
use the following line startForeground(notifId, n) instead of this one notificationManager.notify(notifId, n);
When using notifications in a service, the notification also must be persistent.
instead of use startService(streamService);
please use
try {
Intent playbackServiceIntent = new Intent(this, MusicService.class);
startService(playbackServiceIntent);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(playbackServiceIntent);
}
}catch (Exception e){
e.printStackTrace();
}
Related
I have a service that is started when the main activity starts. I call the Service using this code
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, CheckService.class));
finish();
}
The Service has the following code:
public class CheckService extends Service {
private static final String TAG = "CheckService";
WakeLock wakeLock;
public CheckService() {
// TODO Auto-generated constructor stub
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
return START_STICKY;
}
#Override
public void onTaskRemoved(Intent rootIntent) {
// TODO Auto-generated method stub
Intent restartService = new Intent(getApplicationContext(),
this.getClass());
restartService.setPackage(getPackageName());
PendingIntent restartServicePI = PendingIntent.getService(
getApplicationContext(), 1, restartService,
PendingIntent.FLAG_ONE_SHOT);
//Restart the service once it has been killed android
AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 100, restartServicePI);
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
PowerManager pm = (PowerManager) getSystemService(this.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DoNotSleep");
Log.e("Checker", "Service Created");
Timer myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
check_pref();
}
}, 0, 5000);
}
#Override
#Deprecated
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
}
#Override
public void onDestroy() {
super.onDestroy();
sendBroadcast(new Intent("YouWillNeverKillMe"));
}
public void check_pref( ) {
Context con;
Log.e("check_pref", "Restarting");
try {
Process p = Runtime.getRuntime().exec("su");
DataOutputStream dos = new DataOutputStream(p.getOutputStream());
dos.writeBytes("chmod -R 0777 /data/data/com.my.project.app/\n");
dos.writeBytes("exit\n");
dos.flush();
dos.close();
p.waitFor();
p.destroy();
con = createPackageContext("com.my.project.app", 0);
SharedPreferences pref = con.getSharedPreferences("myprefs", 0);
String login_id = pref.getString("login", "");
System.out.println(login_id);
} catch (PackageManager.NameNotFoundException e)
{
Log.e("check_pref", e.toString());
}
catch (NullPointerException e){
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (InterruptedException e){
e.printStackTrace();
}
}
}
Every 5 seconds in my service runs method check_pref(), which checks login in another app (com.my.project.app) and prints it in Logcat. But even login has been changed it returns same value as previously. Only if I restart app it returns actual value. My device(android 5.1.1) is rooted and I allowed permissions for my app. Whats wrong with my code? How to make it always return the actual value, which located in /data/data/com.my.project.app/myprefs.xml ?
PS. I found a solution. I changed
SharedPreferences pref = con.getSharedPreferences("myprefs", 0);
to
SharedPreferences pref = con.getSharedPreferences("myprefs", MODE_MULTI_PROCESS); and it works now.
I changed
SharedPreferences pref = con.getSharedPreferences("myprefs", 0);
to
SharedPreferences pref = con.getSharedPreferences("myprefs", MODE_MULTI_PROCESS);
and it works now.
From what I can tell, the Uri.parse in my code is causing my MediaPlayer to fail on audio files with special characters in the filename, like "#" and others. I cannot figure out how to resolve this issue. I want to be able to use special characters in my filenames. Here is the code that I think is causing the issue:
public void playAudio(int media) {
try {
switch (media) {
case LOCAL_AUDIO:
/**
* TODO: Set the path variable to a local audio file path.
*/
if (path == "") {
// Tell the user to provide an audio file URL.
Toast
.makeText(
MediaPlayerDemo_Audio.mp,
"Please edit MediaPlayer_Audio Activity, "
+ "and set the path variable to your audio file path."
+ " Your audio file must be stored on sdcard.",
Toast.LENGTH_LONG).show();
}
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setLooping(sound_loop);
mMediaPlayer.setDataSource(MediaPlayerDemo_Audio.mp, Uri.parse(path));
mMediaPlayer.prepare();
resetTimer();
startTimer();
mMediaPlayer.start();
Intent intent = new Intent(MediaPlayerDemo_Audio.PLAY_START);
sendBroadcast(intent);
break;
case RESOURCES_AUDIO:
/**
* TODO: Upload a audio file to res/raw folder and provide
* its resid in MediaPlayer.create() method.
*/
// mMediaPlayer = MediaPlayer.create(this, R.raw.test_cbr);
//mMediaPlayer.start();
}
//tx.setText(path);
} catch (Exception e) {
//Log.e(TAG, "error: " + e.getMessage(), e);
}
}
I am using MediaPlayerDemo_Audio.java to play sounds. As you can see from the above code, the mMediaPlayer.setDataSource(MediaPlayerDemo_Audio.mp, Uri.parse(path)); is calling the code to retrieve the file and media player, I think. I am not too skilled with android code yet. Here is the code for MediaPlayerDemo_Audio.java:
public class MediaPlayerDemo_Audio extends Activity {
public static String path;
private String fname;
private static Intent PlayerIntent;
public static String STOPED = "stoped";
public static String PLAY_START = "play_start";
public static String PAUSED = "paused";
public static String UPDATE_SEEKBAR = "update_seekbar";
public static boolean is_loop = false;
private static final int LOCAL_AUDIO=0;
private Button play_pause, stop;
private SeekBar seek_bar;
public static MediaPlayerDemo_Audio mp;
private AudioPlayerService mPlayerService;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.media_player_layout);
//getWindow().setTitle("SoundPlayer");
//getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
// android.R.drawable.ic_media_play);
play_pause = (Button)findViewById(R.id.play_pause);
play_pause.setOnClickListener(play_pause_clk);
stop = (Button)findViewById(R.id.stop);
stop.setOnClickListener(stop_clk);
seek_bar = (SeekBar)findViewById(R.id.seekBar1);
seek_bar.setMax(100);
seek_bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar seekBar) {
if (mPlayerService!=null) {
int seek_pos = (int) ((double)mPlayerService.getduration()*seekBar.getProgress()/100);
mPlayerService.seek(seek_pos);
}
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
}
});
play_pause.setText("Pause");
stop.setText("Stop");
//int idx = path.lastIndexOf("/");
//fname = path.substring(idx+1);
//tx.setText(path);
IntentFilter filter = new IntentFilter();
filter.addAction(STOPED);
filter.addAction(PAUSED);
filter.addAction(PLAY_START);
filter.addAction(UPDATE_SEEKBAR);
registerReceiver(mPlayerReceiver, filter);
PlayerIntent = new Intent(MediaPlayerDemo_Audio.this, AudioPlayerService.class);
if (AudioPlayerService.path=="") AudioPlayerService.path=path;
AudioPlayerService.sound_loop = is_loop;
startService(PlayerIntent);
bindService(PlayerIntent, mConnection, 0);
if (mPlayerService!=null && mPlayerService.is_pause==true) play_pause.setText("Play");
mp = MediaPlayerDemo_Audio.this;
}
private BroadcastReceiver mPlayerReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String act = intent.getAction();
if (act.equalsIgnoreCase(UPDATE_SEEKBAR)){
int val = intent.getIntExtra("seek_pos", 0);
seek_bar.setProgress(val);
TextView counter = (TextView) findViewById(R.id.time_view);
counter.setText(DateUtils.formatElapsedTime((long) (intent.getLongExtra("time", 0)/16.666)));
//tx.setText(fname);
}
else if (act.equalsIgnoreCase(STOPED)) {
play_pause.setText("Play");
seek_bar.setProgress(0);
stopService(PlayerIntent);
unbindService(mConnection);
mPlayerService = null;
TextView counter = (TextView) findViewById(R.id.time_view);
counter.setText(DateUtils.formatElapsedTime(0));
}
else if (act.equalsIgnoreCase(PLAY_START)){
play_pause.setText("Pause");
}
else if (act.equalsIgnoreCase(PAUSED)){
play_pause.setText("Play");
}
}
};
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
mPlayerService = ((AudioPlayerService.LocalBinder)arg1).getService();
if (mPlayerService.is_pause==true) {
play_pause.setText("Play");
seek_bar.setProgress(mPlayerService.seek_pos);
}
if (mPlayerService.mTime!=0) {
TextView counter = (TextView) findViewById(R.id.time_view);
counter.setText(DateUtils.formatElapsedTime((long) (mPlayerService.mTime/16.666)));
}
if (path.equalsIgnoreCase(AudioPlayerService.path)==false){
AudioPlayerService.path = path;
mPlayerService.restart();
}
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
// TODO Auto-generated method stub
mPlayerService = null;
}
};
private OnClickListener play_pause_clk = new OnClickListener() {
#Override
public void onClick(View arg0) {
if (mPlayerService!=null)
mPlayerService.play_pause();
else{
AudioPlayerService.path=path;
startService(PlayerIntent);
bindService(PlayerIntent, mConnection, 0);
}
}
};
private OnClickListener stop_clk = new OnClickListener() {
#Override
public void onClick(View arg0) {
if (mPlayerService==null) return;
mPlayerService.Stop();
}
};
#Override
protected void onDestroy() {
super.onDestroy();
// TODO Auto-generated method stub
}
}
How can I fix this issue so files can be parsed with special characters and played correctly in MediaPlayer? Am I missing something?
Maybe it would help to show the entire code for my AudioPlayerService:
public class AudioPlayerService extends Service {
public MediaPlayer mMediaPlayer;
protected long mStart;
public long mTime;
public int seek_pos=0;
public static boolean sound_loop = false;
public boolean is_play, is_pause;
public static String path="";
private static final int LOCAL_AUDIO=0;
private static final int RESOURCES_AUDIO=1;
private int not_icon;
private Notification notification;
private NotificationManager nm;
private PendingIntent pendingIntent;
private Intent intent;
#SuppressWarnings("deprecation")
#Override
public void onCreate() {
playAudio(LOCAL_AUDIO);
mTime=0;
is_play = true;
is_pause = false;
CharSequence ticker = "Touch to return to app";
long now = System.currentTimeMillis();
not_icon = R.drawable.play_notification;
notification = new Notification(not_icon, ticker, now);
nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Context context = getApplicationContext();
intent = new Intent(this, MediaPlayerDemo_Audio.class);
pendingIntent = PendingIntent.getActivity(context, 0,intent, 0);
PhoneStateListener phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
//INCOMING call
//do all necessary action to pause the audio
if (is_play==true && is_pause==false){
play_pause();
}
} else if(state == TelephonyManager.CALL_STATE_IDLE) {
//Not IN CALL
//do anything if the phone-state is idle
} else if(state == TelephonyManager.CALL_STATE_OFFHOOK) {
//A call is dialing, active or on hold
//do all necessary action to pause the audio
//do something here
if (is_play==true && is_pause==false){
play_pause();
}
}
super.onCallStateChanged(state, incomingNumber);
}
};//end PhoneStateListener
TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if(mgr != null) {
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
OnAudioFocusChangeListener myaudiochangelistener = new OnAudioFocusChangeListener(){
#Override
public void onAudioFocusChange(int arg0) {
//if (arg0 ==AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK){
if (is_play==true && is_pause==false){
play_pause();
}
//}
}
};
AudioManager amr = (AudioManager)getSystemService(AUDIO_SERVICE);
amr.requestAudioFocus(myaudiochangelistener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
}
#SuppressWarnings("deprecation")
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Context context = getApplicationContext();
String title = "VoiceRecorder App";
CharSequence message = "Playing..";
notification.setLatestEventInfo(context, title, message,pendingIntent);
nm.notify(101, notification);
return START_STICKY;
}
public class LocalBinder extends Binder {
AudioPlayerService getService() {
return AudioPlayerService.this;
}
}
public void restart(){
mMediaPlayer.stop();
playAudio(LOCAL_AUDIO);
mTime=0;
is_play = true;
is_pause = false;
}
#Override
public IBinder onBind(Intent arg0) {
return mBinder;
}
private final IBinder mBinder = new LocalBinder();
public void Stop()
{
mMediaPlayer.stop();
Intent intent1 = new Intent(MediaPlayerDemo_Audio.STOPED);
sendBroadcast(intent1);
resetTimer();
is_play=false;
is_pause=false;
}
public void play_pause()
{
if (is_play==false){
try {
mMediaPlayer.start();
startTimer();
is_play=true;
is_pause = false;
} catch (Exception e) {
//Log.e(TAG, "error: " + e.getMessage(), e);
}
Intent intent = new Intent(MediaPlayerDemo_Audio.PLAY_START);
sendBroadcast(intent);
}
else{
mMediaPlayer.pause();
stopTimer();
Intent intent1 = new Intent(MediaPlayerDemo_Audio.PAUSED);
sendBroadcast(intent1);
is_play = false;
is_pause = true;
}
}
public int getduration()
{
return mMediaPlayer.getDuration();
}
public void seek(int seek_pos)
{
mMediaPlayer.seekTo(seek_pos);
mTime = seek_pos;
}
public void playAudio(int media) {
try {
switch (media) {
case LOCAL_AUDIO:
/**
* TODO: Set the path variable to a local audio file path.
*/
if (path == "") {
// Tell the user to provide an audio file URL.
Toast
.makeText(
MediaPlayerDemo_Audio.mp,
"Please edit MediaPlayer_Audio Activity, "
+ "and set the path variable to your audio file path."
+ " Your audio file must be stored on sdcard.",
Toast.LENGTH_LONG).show();
}
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setLooping(sound_loop);
mMediaPlayer.setDataSource(MediaPlayerDemo_Audio.mp, Uri.parse(path));
mMediaPlayer.prepare();
resetTimer();
startTimer();
mMediaPlayer.start();
Intent intent = new Intent(MediaPlayerDemo_Audio.PLAY_START);
sendBroadcast(intent);
break;
case RESOURCES_AUDIO:
/**
* TODO: Upload a audio file to res/raw folder and provide
* its resid in MediaPlayer.create() method.
*/
// mMediaPlayer = MediaPlayer.create(this, R.raw.test_cbr);
//mMediaPlayer.start();
}
//tx.setText(path);
} catch (Exception e) {
//Log.e(TAG, "error: " + e.getMessage(), e);
}
}
#SuppressLint("HandlerLeak")
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
long curTime = System.currentTimeMillis();
mTime += curTime-mStart;
mStart = curTime;
int pos = (int) ((double)mMediaPlayer.getCurrentPosition()*100/mMediaPlayer.getDuration());
seek_pos = pos;
Intent intent1 = new Intent(MediaPlayerDemo_Audio.UPDATE_SEEKBAR);
if (mMediaPlayer.isLooping()) intent1.putExtra("time", (long)mMediaPlayer.getCurrentPosition());
else intent1.putExtra("time", mTime);
intent1.putExtra("seek_pos", pos);
sendBroadcast(intent1);
if (mMediaPlayer.isPlaying()==false && mMediaPlayer.isLooping()==false){
mMediaPlayer.stop();
resetTimer();
Intent intent2 = new Intent(MediaPlayerDemo_Audio.STOPED);
sendBroadcast(intent2);
is_play=false;
}
if (mTime > 0) mHandler.sendEmptyMessageDelayed(0, 10);
};
};
private void startTimer() {
mStart = System.currentTimeMillis();
mHandler.removeMessages(0);
mHandler.sendEmptyMessage(0);
}
private void stopTimer() {
mHandler.removeMessages(0);
}
private void resetTimer() {
stopTimer();
mTime = 0;
}
#Override
public void onDestroy() {
super.onDestroy();
// TODO Auto-generated method stub
if (mMediaPlayer != null) {
mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
}
nm.cancel(101);
}
}
For local files, do not use Uri.parse(). Use Uri.fromFile(), passing in a File object pointing to the file in question. This should properly escape special characters like #.
I'm trying to create a service that will play music in the background, but when a song completes the nextone should be played but seems oncomplete listener is not called. Can anyone tell me where is the problem?
P.S. I don't get anything in logcat, and I dont get the log that should be shown when entering oncomplete listener.
Here is my code:
public class myPlayService extends Service implements OnCompletionListener,
OnPreparedListener, OnErrorListener, OnSeekCompleteListener,
OnInfoListener, OnBufferingUpdateListener {
private static final String TAG = "--";
public static MediaPlayer mediaPlayer = new MediaPlayer();
// songs
private static ArrayList<Songs> songs;
private static int position;
// Set up the notification ID
private static final int NOTIFICATION_ID = 1;
private boolean isPausedInCall = false;
private PhoneStateListener phoneStateListener;
private TelephonyManager telephonyManager;
// ---Variables for seekbar processing---
String sntSeekPos;
static int intSeekPos;
int mediaPosition;
int mediaMax;
// Intent intent;
private final Handler handler = new Handler();
private static int songEnded;
public static boolean serviceStarted=false;
public static final String BROADCAST_ACTION = "com.darkovski.quran.seekprogress";
// Set up broadcast identifier and intent
public static final String BROADCAST_BUFFER = "com.darkovski.quran.broadcastbuffer";
Intent bufferIntent;
Intent seekIntent;
// Declare headsetSwitch variable
private int headsetSwitch = 1;
// OnCreate
#Override
public void onCreate() {
Log.v(TAG, "Creating Service");
// android.os.Debug.waitForDebugger();
// Instantiate bufferIntent to communicate with Activity for progress
// dialogue
serviceStarted=true;
songs = new ArrayList<Songs>();
bufferIntent = new Intent(BROADCAST_BUFFER);
// ---Set up intent for seekbar broadcast ---
seekIntent = new Intent(BROADCAST_ACTION);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnErrorListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnSeekCompleteListener(this);
mediaPlayer.setOnInfoListener(this);
mediaPlayer.reset();
// Register headset receiver
registerReceiver(headsetReceiver, new IntentFilter(
Intent.ACTION_HEADSET_PLUG));
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// get songs and position
songs = new ArrayList<Songs>();
songs = (ArrayList<Songs>) intent.getSerializableExtra("songs");
Log.v("--", songs.size() + " size!#$");
position = intent.getIntExtra("position", -1);
// ---Set up receiver for seekbar change ---
registerReceiver(broadcastReceiver, new IntentFilter(
Player.BROADCAST_SEEKBAR));
// Manage incoming phone calls during playback. Pause mp on incoming,
// resume on hangup.
// -----------------------------------------------------------------------------------
// Get the telephony manager
Log.v(TAG, "Starting telephony");
telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
Log.v(TAG, "Starting listener");
phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
// String stateString = "N/A";
Log.v(TAG, "Starting CallStateChange");
switch (state) {
case TelephonyManager.CALL_STATE_OFFHOOK:
case TelephonyManager.CALL_STATE_RINGING:
if (mediaPlayer != null) {
pauseMedia();
isPausedInCall = true;
}
break;
case TelephonyManager.CALL_STATE_IDLE:
// Phone idle. Start playing.
if (mediaPlayer != null) {
if (isPausedInCall) {
isPausedInCall = false;
playMedia();
}
}
break;
}
}
};
// Register the listener with the telephony manager
telephonyManager.listen(phoneStateListener,
PhoneStateListener.LISTEN_CALL_STATE);
// Insert notification start
initNotification();
mediaPlayer.reset();
// Set up the MediaPlayer data source using the strAudioLink value
if (!mediaPlayer.isPlaying()) {
try {
// Send message to Activity to display progress dialogue
sendBufferingBroadcast();
mediaPlayer.setDataSource(songs.get(position).getLink());
;
// Prepare mediaplayer
mediaPlayer.prepare();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
}
}
// --- Set up seekbar handler ---
setupHandler();
return START_STICKY;
}
// ---Send seekbar info to activity----
private void setupHandler() {
handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 300); // 1 second
}
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
// // Log.d(TAG, "entered sendUpdatesToUI");
LogMediaPosition();
handler.postDelayed(this, 1000); // 2 seconds
}
};
private void LogMediaPosition() {
// // Log.d(TAG, "entered LogMediaPosition");
if (mediaPlayer.isPlaying()) {
mediaPosition = mediaPlayer.getCurrentPosition();
// if (mediaPosition < 1) {
// Toast.makeText(this, "Buffering...", Toast.LENGTH_SHORT).show();
// }
mediaMax = mediaPlayer.getDuration();
// seekIntent.putExtra("time", new Date().toLocaleString());
seekIntent.putExtra("counter", String.valueOf(mediaPosition));
seekIntent.putExtra("mediamax", String.valueOf(mediaMax));
seekIntent.putExtra("song_ended", String.valueOf(songEnded));
sendBroadcast(seekIntent);
}
}
// --Receive seekbar position if it has been changed by the user in the
// activity
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateSeekPos(intent);
}
};
// Update seek position from Activity
public void updateSeekPos(Intent intent) {
int seekPos = intent.getIntExtra("seekpos", 0);
if (mediaPlayer.isPlaying()) {
handler.removeCallbacks(sendUpdatesToUI);
mediaPlayer.seekTo(seekPos);
setupHandler();
}
}
// ---End of seekbar code
// If headset gets unplugged, stop music and service.
private BroadcastReceiver headsetReceiver = new BroadcastReceiver() {
private boolean headsetConnected = false;
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
// Log.v(TAG, "ACTION_HEADSET_PLUG Intent received");
if (intent.hasExtra("state")) {
if (headsetConnected && intent.getIntExtra("state", 0) == 0) {
headsetConnected = false;
headsetSwitch = 0;
// Log.v(TAG, "State = Headset disconnected");
// headsetDisconnected();
} else if (!headsetConnected
&& intent.getIntExtra("state", 0) == 1) {
headsetConnected = true;
headsetSwitch = 1;
// Log.v(TAG, "State = Headset connected");
}
}
switch (headsetSwitch) {
case (0):
headsetDisconnected();
break;
case (1):
break;
}
}
};
private void headsetDisconnected() {
stopMedia();
stopSelf();
}
// --- onDestroy, stop media player and release. Also stop
// phoneStateListener, notification, receivers...---
#Override
public void onDestroy() {
super.onDestroy();
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
}
if (phoneStateListener != null) {
telephonyManager.listen(phoneStateListener,
PhoneStateListener.LISTEN_NONE);
}
// Cancel the notification
cancelNotification();
// Unregister headsetReceiver
unregisterReceiver(headsetReceiver);
// Unregister seekbar receiver
unregisterReceiver(broadcastReceiver);
// Stop the seekbar handler from sending updates to UI
handler.removeCallbacks(sendUpdatesToUI);
// Service ends, need to tell activity to display "Play" button
resetButtonPlayStopBroadcast();
}
// Send a message to Activity that audio is being prepared and buffering
// started.
private void sendBufferingBroadcast() {
// Log.v(TAG, "BufferStartedSent");
bufferIntent.putExtra("buffering", "1");
sendBroadcast(bufferIntent);
}
// Send a message to Activity that audio is prepared and ready to start
// playing.
private void sendBufferCompleteBroadcast() {
// Log.v(TAG, "BufferCompleteSent");
bufferIntent.putExtra("buffering", "0");
sendBroadcast(bufferIntent);
}
// Send a message to Activity to reset the play button.
private void resetButtonPlayStopBroadcast() {
// Log.v(TAG, "BufferCompleteSent");
bufferIntent.putExtra("buffering", "2");
sendBroadcast(bufferIntent);
}
#Override
public void onBufferingUpdate(MediaPlayer arg0, int arg1) {
// TODO Auto-generated method stub
}
#Override
public boolean onInfo(MediaPlayer arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onSeekComplete(MediaPlayer mp) {
if (!mediaPlayer.isPlaying()) {
playMedia();
Toast.makeText(this, "SeekComplete", Toast.LENGTH_SHORT).show();
}
}
// ---Error processing ---
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
switch (what) {
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
Toast.makeText(this,
"MEDIA ERROR NOT VALID FOR PROGRESSIVE PLAYBACK " + extra,
Toast.LENGTH_SHORT).show();
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
Toast.makeText(this, "MEDIA ERROR SERVER DIED " + extra,
Toast.LENGTH_SHORT).show();
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
Toast.makeText(this, "MEDIA ERROR UNKNOWN " + extra,
Toast.LENGTH_SHORT).show();
break;
}
return false;
}
#Override
public void onPrepared(MediaPlayer arg0) {
// Send a message to activity to end progress dialogue
sendBufferCompleteBroadcast();
playMedia();
}
#Override
public void onCompletion(MediaPlayer mp) {
// When song ends, need to tell activity to display "Play" button
position += 1;
mp.stop();
mp.release();
Log.v("--", "complete");
// stopMedia();
playMedia();
// stopSelf();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public static void pause() {
mediaPlayer.pause();
}
public static void resume(){
mediaPlayer.start();
}
public static void playMedia() {
if (!mediaPlayer.isPlaying()) {
try {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(songs.get(position).getLink());
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
try {
mediaPlayer.setDataSource(songs.get(position).getLink());
mediaPlayer.prepare();
mediaPlayer.start();
} 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();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void nextSong() {
if (position + 1 == songs.size())
position = 0;
else
position += 1;
playMedia();
}
public static void prevSong() {
if (position - 1 >= 0)
position -= 1;
else
position = songs.size() - 1;
playMedia();
}
// Add for Telephony Manager
public void pauseMedia() {
// Log.v(TAG, "Pause Media");
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
}
}
public void stopMedia() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
}
// Create Notification
private void initNotification() {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
int icon = R.drawable.ic_launcher;
CharSequence tickerText = "Tutorial: Music In Service";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
notification.flags = Notification.FLAG_ONGOING_EVENT;
Context context = getApplicationContext();
CharSequence contentTitle = "Music In Service App Tutorial";
CharSequence contentText = "Listen To Music While Performing Other Tasks";
Intent notificationIntent = new Intent(this, Player.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText,
contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, notification);
}
// Cancel Notification
private void cancelNotification() {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
mNotificationManager.cancel(NOTIFICATION_ID);
}
}
I'm working on a group project for a class I'm taking and we cannot seem to figure out why our Alarm Manager does not fire intents repeatedly. We've picked through the source code from top to bottom and cannot seem to isolate the source of this issue.
Can anyone recommend a fix? (or perhaps a starting point?)
// Start service using AlarmManager
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 10);
Intent intent = new Intent(Rules.this, LMW.class);
PendingIntent pintent = PendingIntent.getService(Rules.this, 0, intent,
0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
7 * 1000, pintent);
// Start 2nd service using AlarmManager
Intent intent2 = new Intent(Rules.this, KillTimer.class);
PendingIntent pintent2 = PendingIntent.getActivity(Rules.this, 0, intent2,
0);
AlarmManager alarm2 = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
120 * 1000, pintent2); // here
Source:
public class AlarmManager extends ListActivity {
TextView empty;
TextView empty2;
private static final int ACTIVITY_CREATE = 0;
private static final int ACTIVITY_EDIT = 1;
public static final int INSERT_ID = Menu.FIRST;
private static final int DELETE_ID = Menu.FIRST + 1;
private List<ParseObject> todos;
private Dialog progressDialog;
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
// Override this method to do custom remote calls
public void setVisibility() {
empty.setVisibility(View.VISIBLE);
empty2.setVisibility(View.VISIBLE);
}
protected void doInBackground(Void... params) {
// Gets the current list of todos in sorted order
ParseQuery query = new ParseQuery("TestObject");
query.orderByDescending("_created_at");
try {
todos = query.find();
} catch (ParseException e) {
return;
}
runOnUiThread(new Runnable() {
public void run() {
}});
}
#Override
protected void onPreExecute() {
ToDoListActivity.this.progressDialog = ProgressDialog.show(ToDoListActivity.this, "",
"Loading...", true);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Void result) {
// Put the list of todos into the list view
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ToDoListActivity.this,
R.layout.todo_row);
for (ParseObject todo : todos) {
adapter.add((String) todo.get("DataI"));
adapter.add((String) todo.get("DataO"));
adapter.add((String) todo.get("DataRSSI"));
adapter.add((String) todo.get("DataSSID"));
adapter.add((String) todo.get("DataTIME"));
adapter.add((String) todo.get("DataRESTRICTED"));
}
setListAdapter(adapter);
ToDoListActivity.this.progressDialog.dismiss();
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_new);
empty = (TextView) findViewById(android.R.id.empty);
empty.setVisibility(View.INVISIBLE);
new RemoteDataTask().execute();
registerForContextMenu(getListView());
}
private void createTodo() {
Intent i = new Intent(this, CreateTodo.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (intent == null) {
return;
}
final Bundle extras = intent.getExtras();
switch (requestCode) {
case ACTIVITY_CREATE:
new RemoteDataTask() {
protected void doInBackground(Void... params) {
String DataI = extras.getString("DataI");
String DataO = extras.getString("DataO");
String DataRSSI = extras.getString("DataRSSI");
String DataSSID = extras.getString("DataSSID");
String DataTIME = extras.getString("DataTIME");
String DataRESTRICTED = extras.getString("DataRESTRICTED");
ParseObject todo = new ParseObject("Todo");
todo.put("DataI", DataI);
todo.put("DataO", DataO);
todo.put("DataRSSI", DataRSSI);
todo.put("DataSSID", DataSSID);
todo.put("DataTIME", DataTIME);
todo.put("DataRESTRICTED", DataRESTRICTED);
try { todo.save(); } catch (ParseException e) {
}
super.doInBackground();
return;
}
}.execute();
break;
case ACTIVITY_EDIT:
// Edit the remote object
final ParseObject todo;
todo = todos.get(extras.getInt("position"));
todo.put("DataI", extras.getString("DataI"));
todo.put("DataO", extras.getString("DataO"));
todo.put("DataRSSI", extras.getString("DataRSSI"));
todo.put("DataSSID", extras.getString("DataSSID"));
todo.put("DataTIME", extras.getString("DataTIME"));
todo.put("DataRESTRICTED", extras.getString("DataRESTRICTED"));
new RemoteDataTask() {
protected void doInBackground(Void... params) {
try {
todo.save();
} catch (ParseException e) {
}
super.doInBackground();
return;
}
}.execute();
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
boolean result = super.onCreateOptionsMenu(menu);
menu.add(0, INSERT_ID, 0, R.string.menu_insert);
return result;
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, DELETE_ID, 0, R.string.menu_delete);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case DELETE_ID:
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
// Delete the remote object
final ParseObject todo = todos.get(info.position);
new RemoteDataTask() {
protected void doInBackground(Void... params) {
try {
todo.delete();
} catch (ParseException e) {
}
super.doInBackground();
return;
}
}.execute();
return true;
}
return super.onContextItemSelected(item);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case INSERT_ID:
createTodo();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent i = new Intent(this, CreateTodo.class);
i.putExtra("DataI", todos.get(position).getString("DataI").toString());
i.putExtra("DataO", todos.get(position).getString("DataO").toString());
i.putExtra("DataRSSI", todos.get(position).getString("DataRSSI").toString());
i.putExtra("DataSSID", todos.get(position).getString("DataSSID").toString());
i.putExtra("DataTIME", todos.get(position).getString("DataTIME").toString());
i.putExtra("DataRESTRICTED", todos.get(position).getString("DataRESTRICTED").toString());
i.putExtra("position", position);
startActivityForResult(i, ACTIVITY_EDIT);
}
}
Service Class
public class LMW extends Service {
String Watchdog = "Watchdog";
String Dirty1 = "playboy";
String Dirty2 = "penthouse";
String Dirty3 = "pornhub";
String Dirty4 = "thepiratebay";
String Dirty5 = "vimeo";
String Dirty6 = "wired";
String Dirty7 = "limewire";
String Dirty8 = "whitehouse";
String Dirty9 = "hackaday";
String Dirty10 = "slashdot";
Long mStartRX = TrafficStats.getTotalRxBytes();
Long mStartTX = TrafficStats.getTotalTxBytes();
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(getApplicationContext(), "Watchdog Running!", Toast.LENGTH_SHORT).show();
Long.toString(mStartTX);
Long.toString(mStartRX);
ParseObject testObject = new ParseObject("TestObject");
testObject.put("DataO", String.valueOf(mStartTX));
testObject.put("DataI", String.valueOf(mStartRX));
testObject.saveInBackground(); String[] projection = new String[] { Browser.BookmarkColumns.TITLE,
Browser.BookmarkColumns.URL };
Cursor cursor = getContentResolver().query(android.provider.Browser.BOOKMARKS_URI,
projection, null, null, null);
String urls = "";
if (cursor.moveToFirst()) {
String url1 = null;
String url2 = null;
do {
String url = cursor.getString(cursor.getColumnIndex(Browser.BookmarkColumns.URL));
Log.i(Watchdog, url);
if (url.toLowerCase().contains(Dirty1) || url.toLowerCase().contains(Dirty2) || url.toLowerCase().contains(Dirty3) || url.toLowerCase().contains(Dirty4) || url.toLowerCase().contains(Dirty5) || url.toLowerCase().contains(Dirty6) || url.toLowerCase().contains(Dirty7) || url.toLowerCase().contains(Dirty8) || url.toLowerCase().contains(Dirty9) || url.toLowerCase().contains(Dirty10))
{
Intent intent2 = new Intent(LMW.this, Warning.class);
intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent2);
break;
} } while (cursor.moveToNext());
}
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
#Override
public void onCreate() {
super.onCreate();
}}
Activity Class:
public class Timer extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.killtimer);
Toast.makeText(getApplicationContext(), "KillWifi Running!", Toast.LENGTH_SHORT).show();
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
int networkId = wifiManager.getConnectionInfo().getNetworkId();
wifiManager.removeNetwork(networkId );
wifiManager.saveConfiguration();
}}
Go through the links, It helped me a lot.
http://android-er.blogspot.in/2010/10/simple-example-of-alarm-service-using.html
http://android-er.blogspot.in/2010/10/schedule-repeating-alarm.html
I have had a similar problem and perhaps it applies to you (hard to tell since the code you supplied is pretty hard to navigate).
My issue was that applying multiple intents to the manager that evaluated as equal overrode the previous applications of that intent. See http://developer.android.com/reference/android/content/Intent.html#filterEquals(android.content.Intent) for what I mean by equivalence.
As an example, I had a schedule that used the URI domy://thing, with extras that varied over each intent (I need to fire the same action with different arguments each time). Extras don't count in equivalence, so my alarms were getting overwritten by each other.
To get around this, I stored a queue of my alarms in a separate file and when one fired, popped the next off the top and put that in the manager. Maybe that'll help you.
UPDATE:
No examples publicly visible, but try this (Trigger is a simple object containing a URI and a time it needs to be fired, scheduleDb is a class that extends SQLiteOpenHelper):
/**
* Pops the next trigger off the queue, adds it to the alarm manager, and
* stores it in the DB in case we need to cancel it later.
*/
private void scheduleNextTrigger() {
Log.d(TAG, "Popping next trigger off queue");
Optional<Trigger> nextTrigger = scheduleDb.getNextTrigger();
if (!nextTrigger.isPresent()) {
Log.d(TAG, "Trigger queue is empty");
return;
}
Trigger trigger = nextTrigger.get();
Log.d(TAG, "Scheduling new trigger " + trigger);
PendingIntent operation = createPendingIntent(trigger);
long timestamp = trigger.getTimestamp();
// Ensure the next item is in the future
if (timestamp > clock.currentTimeMillis()) {
Log.v(TAG, "Found valid trigger: " + trigger);
alarmManager.set(AlarmManager.RTC_WAKEUP, timestamp, operation);
}
scheduleDb.setScheduledTrigger(trigger);
}
private PendingIntent createPendingIntent(Trigger trigger) {
// AlarmManager allows only one instance of each URI, and seems to randomly
// delete bundled URI extras, so we'll encode the triggered URI and place it
// on a constant stem
Uri triggerUri = Uri.parse(TRIGGER_URI + "?" + Uri.encode(trigger.getUri()));
Intent triggerIntent = new Intent(Intent.ACTION_VIEW, triggerUri);
triggerIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Log.d(TAG, "Created trigger intent " + triggerIntent);
PendingIntent operation = PendingIntent.getService(this, 0, triggerIntent, 0);
return operation;
}
Hope that helps
I have been trying to achieve this.
I have found this but they don't seem to help me:
http://android.amberfog.com/?p=415
Registering a headset button click with BroadcastReceiver in Android
https://issuetracker.google.com/issues/36910848
No matter what I try when I press the button on my head set the phone display the volume level control instead of being catch by my application and do something. Here is some of the code:
public class MediaButtonIntentReceiver extends BroadcastReceiver {
public MediaButtonIntentReceiver() {
super();
}
#Override
public void onReceive(Context context, Intent intent) {
Log.i("test1'", "test2");
String intentAction = intent.getAction();
if (!Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
return;
}
KeyEvent event = (KeyEvent) intent
.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (event == null) {
Log.i("test3'", "test4");
return;
}
int action = event.getAction();
if (action == KeyEvent.ACTION_DOWN) {
// do something
Log.i("test5'", "test6");
}
abortBroadcast();
}
}
public class MainActivity extends Activity {
private static final String TAG = "BTAudioActivity";
private MediaPlayer mPlayer = null;
private AudioManager amanager = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
amanager = (AudioManager) getSystemService(AUDIO_SERVICE);
amanager.setBluetoothScoOn(true);
amanager.startBluetoothSco();
amanager.setMode(2);
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(new FileInputStream("/sdcard/sample.wav")
.getFD());
mPlayer.prepare();
mPlayer.setVolume(8,8);
mPlayer.start();
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
MediaButtonIntentReceiver mMediaButtonReceiver = new MediaButtonIntentReceiver();
IntentFilter mediaFilter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
mediaFilter.setPriority(1000);
registerReceiver(mMediaButtonReceiver, mediaFilter);
super.onResume();
}
#Override
public void onDestroy() {
mPlayer.stop();
amanager.setMode(2);
amanager.setBluetoothScoOn(false);
super.onDestroy();
}
}
Try registering in onCreate...
and add a power manager wake_lock using this