i have tried to find the answer...and have no idea what i was doing wrong
public class RadioService extends Service {NotificationManager nm;Intent i;
String artist, title, streamUrl, title_play;
int id = 0;
public MediaPlayer mp ;
#Override
public void onCreate() {
super.onCreate();
mp = new MediaPlayer();
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mp.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start(); // TODO Auto-generated method stub
}
});
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public int onStartCommand(Intent intent, int flags, int startId) {
try {
artist = intent.getStringExtra("artist");
title = intent.getStringExtra("title");
streamUrl = intent.getStringExtra("streamUrl");
title_play = intent.getStringExtra("title_play");
id = intent.getIntExtra("id", 0);
Log.d("MyLog in radioservise", "" + artist + title + streamUrl
+ title_play + id);
} catch (Exception e1) {
Log.d("MyLog", "" + artist + title + streamUrl + title_play + id);
Log.d("Exeption here", e1 + "");
e1.printStackTrace();
}
Play();
sendNotif();
return super.onStartCommand(intent, flags, startId);
}
void sendNotif() {
Intent intent = new Intent(this, PlayActivity.class);
// intent.putExtra(MainActivity.FILE_NAME, "somefile");
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
notif.setLatestEventInfo(this, title_play, streamUrl, pIntent);
notif.flags |= Notification.FLAG_AUTO_CANCEL;
nm.notify(1, notif);
}
public void onExit() {
if (mp != null)
{
mp.stop();
mp.release();
mp = null;
}
nm.cancelAll();
}
public void Play(/* String play */) {
try {
if (mp.isPlaying()) {
stop();
} else {
mp.reset();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setDataSource(streamUrl);
mp.prepareAsync();
}
} catch (Exception e) {
}}
public void Pause() {
try {
if (mp.isPlaying()) {
if (mp!=null){
mp.pause();
}
}
} catch ( Exception e) {
e.printStackTrace();
}
}
public void Mute() {
try {
mp.setVolume(0, 0);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void Volume() {
try {
mp.setVolume(1, 1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void stop() {
if (mp.isPlaying()) {
try {
mp.stop();
mp.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
}
when i launch the activity i run service ,where i am play the music. The music plays fine, but when I click on pause or mute button the application crashes with NullPointer exception on mp.pause() or pm.volume(0,0) or mp.stop
The code of activity here:
public void onClick(View v) {
switch (v.getId()) {
case R.id.im_play:
rServ.Play(/*streamUrl*/);
ResetInfo(streamUrl);
break;
case R.id.im_pause:
rServ.Pause();
// rServ.mp.pause();
break;
case R.id.im_mute:
if (z == true) {
rServ.Mute();
mut.setImageResource(R.drawable.no_mute_bt_ic);
z = false;
} else {
rServ.Volume();
mut.setImageResource(R.drawable.mute_bt_ic);
z = true;
}
break;
}
}
public void onBackPressed() {
tm.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
try {
//if (rServ.mp != null && rServ.mp.isPlaying()) {
rServ.onExit();
//rServ.stop();
t.cancel();
//}
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Logcat error:
> 02-05 10:01:04.238: E/AndroidRuntime(429): FATAL EXCEPTION: main
02-05 10:01:04.238: E/AndroidRuntime(429): java.lang.NullPointerException
02-05 10:01:04.238: E/AndroidRuntime(429): at com.example.smpleradio.RadioService.onExit(RadioService.java:106)
02-05 10:01:04.238: E/AndroidRuntime(429): at com.example.smpleradio.PlayActivity.onBackPressed(PlayActivity.java:190)
02-05 10:01:04.238: E/AndroidRuntime(429): at com.example.smpleradio.PlayActivity.onOptionsItemSelected(PlayActivity.java:249)
I think your varible " nm " is becoming null. So please verify it where it happening.
Related
My app breaks down when I attempt to record a second a time when I hit the stop button. I went through this code several times. I can't find the problem. I'm not sure if its my MediaRecorder or my MediaPlayer. It works the first time around. But not the second time. can anyone find the problem.
public class PatientName extends Activity implements OnClickListener {
private Button instructionsBtn;
private ImageView record;
private ImageView stop;
private MediaPlayer instructions;
private MediaPlayer namePlayer;
private MediaRecorder nameRecorder;
private String OUTPUT_FILE;
private Button play;
private Button accept;
private LinearLayout review;
private Button delete;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.patient_name);
OUTPUT_FILE = Environment.getExternalStorageDirectory() + "/namerecording.3gpp";
initializeViews();
initializeListeners();
}
public void initializeViews() {
instructionsBtn = (Button)findViewById(R.id.patient_name_instructions);
record = (ImageView)findViewById(R.id.record_name);
stop = (ImageView)findViewById(R.id.stop_name);
stop.setVisibility(View.GONE);
play = (Button)findViewById(R.id.play_name);
play.setVisibility(View.GONE);
review = (LinearLayout)findViewById(R.id.review_name);
delete = (Button)findViewById(R.id.delete_name);
accept = (Button)findViewById(R.id.accept_name);
review.setVisibility(View.GONE);
}
public void initializeListeners() {
instructionsBtn.setOnClickListener(this);
record.setOnClickListener(this);
stop.setOnClickListener(this);
play.setOnClickListener(this);
delete.setOnClickListener(this);
accept.setOnClickListener(this);
}
#Override
public void onBackPressed() {
}
public void playInstructions() {
setMaxVolume();
instructions = MediaPlayer.create(PatientName.this, R.raw.intro_instructions);
instructions.start();
instructions.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer play) {
instructions.release();
instructionsBtn.setEnabled(true);
}
});
}
public void setMaxVolume() {
AudioManager audio = (AudioManager) getSystemService(this.AUDIO_SERVICE);
int maxVolume = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
audio.setStreamVolume(AudioManager.STREAM_MUSIC, maxVolume, 0);
}
public void onClick(View v) {
int id = v.getId();
if (id==R.id.patient_name_instructions) {
instructionsBtn.setEnabled(false);
playInstructions();
}
if (id==R.id.record_name) {
beginRecording();
}
if (id==R.id.stop_name){
play.setVisibility(View.VISIBLE);
nameRecorder.stop();
}
if (id==R.id.play_name) {
playbackRecording();
}
if (id==R.id.delete_name){
deleteRecording();
}
if (id==R.id.accept_name) {
saveAndContinue();
}
}
private void beginRecording(){
record.setVisibility(View.GONE);
stop.setVisibility(View.VISIBLE);
File outFile = new File(OUTPUT_FILE);
if (outFile.exists()) {
outFile.delete();
}else {
nameRecorder = new MediaRecorder();
nameRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
nameRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
nameRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_WB);
nameRecorder.setOutputFile(OUTPUT_FILE);
try {
nameRecorder.prepare();
} catch (IllegalStateException e) {
Toast toast = Toast.makeText(this,"Illegal State",Toast.LENGTH_LONG);
toast.show();
e.printStackTrace();
} catch (IOException e) {
Toast toast = Toast.makeText(this,"Error Recording",Toast.LENGTH_LONG);
toast.show();
e.printStackTrace();
}
nameRecorder.start();
}
}
private void playbackRecording() {
play.setVisibility(View.GONE);
namePlayer = new MediaPlayer();
try {
namePlayer.setDataSource(OUTPUT_FILE);
} 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();
}
try {
namePlayer.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
namePlayer.start();
namePlayer.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer play) {
namePlayer.release();
nameRecorder.release();
review.setVisibility(View.VISIBLE);
}
});
}
private void deleteRecording() {
Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
private void saveAndContinue() {
Intent intent = new Intent(PatientName.this, PatientLocation.class);
startActivity(intent);
}
}
Here is my logCat:
I figured out the issue. In the beginRecording method, I have an if and else statement that handles the output file. Unfortunately, the code that I had in the else statement was something that I wanted to always run no matter what.
I writting a music application play music with url get from website. In code of me, i using method prepared() and app work. But method prepared() block UI this makes me uncomfortable... I want using method prepareAsync()... But i don't know use it :(. I'm newbie with Android Programing. Please edit my code...!
I speak English bad. Sorry for the inconvenience
Code here :
Function playSong()
private void playSong(String urlData) {
btnPlay = (ImageButton) findViewById(R.id.btnPlay);
seekBar = (SeekBar) findViewById(R.id.seekBar);
btnPlay.setOnClickListener(this);
seekBar.setMax(99);
seekBar.setOnTouchListener(this);
mPlay = new MediaPlayer();
mPlay.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlay.setOnBufferingUpdateListener(this);
mPlay.setOnCompletionListener(this);
try {
mPlay.setDataSource(urlData);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onPrepared(MediaPlayer mp) {
if (mPlay != null) {
mPlay.start();
btnPlay.setImageResource(R.drawable.pause_icon);
} else {
mPlay.pause();
btnPlay.setImageResource(R.drawable.play);
}
mPlay.start();
primaryUpdateSeekBar();
}
Function onClick use play
#Override
public void onClick(View view) {
if (view.getId() == R.id.btnPlay) {
try {
mPlay.prepare();
} catch (Exception e) {
e.printStackTrace();
}
LenghData = mPlay.getDuration();
if (!mPlay.isPlaying()) {
mPlay.start();
btnPlay.setImageResource(R.drawable.pause_icon);
} else {
mPlay.pause();
btnPlay.setImageResource(R.drawable.play);
}
primaryUpdateSeekBar();
}
}
Functions of Seekbar
private void primaryUpdateSeekBar() {
seekBar.setProgress((int) (((float) mPlay.getCurrentPosition() / LenghData) * 100));
if (mPlay.isPlaying()) {
Runnable notification = new Runnable() {
#Override
public void run() {
long totalDuration = mPlay.getDuration();
long currentDuration = mPlay.getCurrentPosition();
tvTotalTime.setText(Utils.getTimeString(totalDuration));
tvCurrentTime.setText(Utils.getTimeString(currentDuration));
primaryUpdateSeekBar();
}
};
handler.postDelayed(notification, 1000);
}
}
#Override
public void onBackPressed() {
if (mPlay.isPlaying()) {
mPlay.stop();
}
super.onBackPressed();
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
seekBar.setSecondaryProgress(percent);
}
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
btnPlay.setImageResource(R.drawable.play);
seekBar.setProgress(0);
seekBar.setSecondaryProgress(0);
tvTotalTime.setText("00:00");
tvCurrentTime.setText("");
try {
playSong(ifChangeCheck);
mPlay.prepareAsync();
mPlay.setOnPreparedListener(this);
mPlay.setLooping(true);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
#Override
public boolean onTouch(View view, MotionEvent event) {
if (view.getId() == R.id.seekBar) {
SeekBar seekbar = (SeekBar) view;
int playPositioninMiliseconds = (LenghData / 100)
* seekbar.getProgress();
mPlay.seekTo(playPositioninMiliseconds);
}
return false;
}
Final
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (group.getCheckedRadioButtonId()) {
case R.id.rad32Kb:
String aftercheck32 = "";
int checkLinkIsPlay32 = urlDataSource.lastIndexOf("/") - 3;
String subString32 = urlDataSource.substring(checkLinkIsPlay32);
if (subString32.contains("128")) {
aftercheck32 = urlDataSource.replace("/128/", "/32/").replace(
".mp3", ".m4a");
} else if (subString32.contains("320")) {
aftercheck32 = urlDataSource.replace("/320/", "/32/").replace(
".mp3", ".m4a");
} else if (subString32.contains("m4a")) {
aftercheck32 = urlDataSource.replace("/m4a/", "/32/");
}
ifChangeCheck = aftercheck32;
try {
if (mPlay != null) {
mPlay.stop();
mPlay.reset();
}
playSong(ifChangeCheck);
mPlay.setLooping(true);
} catch (IllegalStateException e) {
e.printStackTrace();
}
break;
case R.id.rad128Kb:
try {
if (mPlay != null) {
ifChangeCheck = urlDataSource;
mPlay.stop();
mPlay.reset();
}
playSong(urlDataSource);
mPlay.setLooping(true);
} catch (IllegalStateException e) {
e.printStackTrace();
}
break;
case R.id.rad320Kb:
String aftercheck320 = "";
int checkLinkIsPlay320 = urlDataSource.lastIndexOf("/") - 3;
String subLink320 = urlDataSource.substring(checkLinkIsPlay320);
if (subLink320.contains("/32")) {
aftercheck320 = urlDataSource.replace("/32/", "/320/").replace(
".m4a", ".mp3");
} else if (subLink320.contains("128")) {
aftercheck320 = urlDataSource.replace("/128/", "/320/");
} else if (subLink320.contains("m4a")) {
aftercheck320 = urlDataSource.replace("/m4a/", "/320/")
.replace(".m4a", ".mp3");
}
ifChangeCheck = aftercheck320;
try {
if (mPlay != null) {
mPlay.stop();
mPlay.reset();
}
playSong(ifChangeCheck);
mPlay.setLooping(true);
} catch (IllegalStateException e) {
e.printStackTrace();
}
break;
case R.id.rad500:
String aftercheck500 = "";
int checkLinkIsPlay500 = urlDataSource.lastIndexOf("/") - 3;
String subLink500 = urlDataSource.substring(checkLinkIsPlay500);
if (subLink500.contains("/32")) {
aftercheck500 = urlDataSource.replace("/32/", "/m4a/");
} else if (subLink500.contains("128")) {
aftercheck500 = urlDataSource.replace("/128/", "/m4a/")
.replace(".mp3", ".m4a");
} else if (subLink500.contains("320")) {
aftercheck500 = urlDataSource.replace("/320/", "/m4a/")
.replace(".mp3", ".m4a");
}
ifChangeCheck = aftercheck500;
try {
if (mPlay != null) {
mPlay.stop();
mPlay.reset();
}
playSong(ifChangeCheck);
mPlay.setLooping(true);
} catch (IllegalStateException e) {
e.printStackTrace();
}
break;
default:
break;
}
}
Above is all code in class PlayMusicActivity of me... And thanks for helping me
Call the prepareAsync() method from the playsong method, as it will starting buffering the audio immediately. When enough audio has buffered the onPrepared method will be called and audio will play
private void playSong(String urlData) {
btnPlay = (ImageButton) findViewById(R.id.btnPlay);
seekBar = (SeekBar) findViewById(R.id.seekBar);
btnPlay.setOnClickListener(this);
seekBar.setMax(99);
seekBar.setOnTouchListener(this);
mPlay = new MediaPlayer();
mPlay.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlay.setOnBufferingUpdateListener(this);
mPlay.setOnCompletionListener(this);
try {
mPlay.setDataSource(urlData);
mPlay.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I am making a project in which i am using a transparent screen with a button on incoming call screen. It is working fine if the phone is unlock but if the phone is in lock condition and the call arrive on phone than firstly i have to unlock the phone
The code that i used is...
public class Recevo extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
TelephonyManager tm = (TelephonyManager)context.getSystemService(Service.TELEPHONY_SERVICE);
Intent i= new Intent(context,Servo.class);
int state = tm.getCallState();
if(state==TelephonyManager.CALL_STATE_RINGING){
String number=intent.getStringExtra("incoming_number");
Log.i("State", "Call is Ringing");
context.startService(i);
}else if (state==TelephonyManager.CALL_STATE_IDLE) {
Log.i("State", "Idle State");
Toast.makeText(context, "Call is Idle", Toast.LENGTH_SHORT).show();
context.stopService(i);
} else if (state==TelephonyManager.CALL_STATE_OFFHOOK) {
//Log.i("State", "Call is Ringing");
//Toast.makeText(context, "Phone is Ringing", Toast.LENGTH_SHORT).show();
}
}
}
public class Servo extends Service{
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
//Toast.makeText(getApplicationContext(), "in servo", Toast.LENGTH_SHORT).show();
Thread t=new Thread(new Times());
t.start();
}
public class Times extends Thread{
#Override
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(5000);
Intent i = new Intent(Servo.this,Blank.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class Blank extends Activity implements OnClickListener{
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.blank);
b=(Button)findViewById(R.id.button1);
b.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Button Clicked", Toast.LENGTH_SHORT).show();
AudioManager audio1 = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
//audio1.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
audio1.setStreamMute(AudioManager.STREAM_MUSIC, true);
finish();
}
Update 1
public class CallerService extends Service implements
TextToSpeech.OnInitListener {
String number;
boolean a;
private TextToSpeech tts;
int callState;
TelephonyManager mgr;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
tts = new TextToSpeech(this, this);
mgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
AudioManager audio1 = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int maxVolume = audio1.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float percent = 2.0f;
int seventyVolume = (int) (maxVolume*percent);
audio1.setStreamVolume(AudioManager.STREAM_MUSIC, seventyVolume, 0);
Thread t=new Thread(new Times());
t.start();
}
public class Times extends Thread{
#Override
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(5000);
Intent i = new Intent(CallerService.this,Blank.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
#Deprecated
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
number = intent.getStringExtra("phnumber");
//fetchContacts();
}
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
if (status != TextToSpeech.ERROR)
{
tts.setLanguage(Locale.ENGLISH);
fetchContacts();
}
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
public void fetchContacts() {
/* tts.speak("Hello everyone", TextToSpeech.QUEUE_FLUSH,
null);*/
String phoneNumber = null;
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(CONTENT_URI, null, null, null,
null);
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String contact_id = cursor
.getString(cursor.getColumnIndex(_ID));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor
.getColumnIndex(HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
Cursor phoneCursor = contentResolver.query(
PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?",
new String[] { contact_id }, null);
while (phoneCursor.moveToNext()) {
phoneNumber = phoneCursor.getString(phoneCursor
.getColumnIndex(NUMBER));
a = PhoneNumberUtils.compare(number,
phoneNumber);
callState= mgr.getCallState();
/*if(!a){
if(callState==TelephonyManager.CALL_STATE_RINGING) {
for (int i = 0; i < 15; i++) {
callState = mgr.getCallState();
if (callState==TelephonyManager.CALL_STATE_IDLE){
tts.stop();
tts.shutdown();
break;
}else if (callState==TelephonyManager.CALL_STATE_OFFHOOK){
tts.stop();
tts.shutdown();
break;
}
tts.speak("Unknown Calling", TextToSpeech.QUEUE_FLUSH,
null);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
else */if (a) {
String contname = phoneCursor.getString(phoneCursor
.getColumnIndex(DISPLAY_NAME));
if (!contname.equals(null)) {
Toast.makeText(getApplicationContext(),
contname, Toast.LENGTH_SHORT).show();
if(callState==TelephonyManager.CALL_STATE_RINGING) {
for (int i = 0; i < 15; i++) {
callState = mgr.getCallState();
if (callState==TelephonyManager.CALL_STATE_IDLE){
tts.stop();
tts.shutdown();
break;
}else if (callState==TelephonyManager.CALL_STATE_OFFHOOK){
tts.stop();
tts.shutdown();
break;
}
tts.speak(contname + " Calling", TextToSpeech.QUEUE_FLUSH,
null);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
phoneCursor.close();
}
}
}
if(!a){
if(callState==TelephonyManager.CALL_STATE_RINGING) {
for (int i = 0; i < 15; i++) {
callState = mgr.getCallState();
if (callState==TelephonyManager.CALL_STATE_IDLE){
tts.stop();
tts.shutdown();
break;
}else if (callState==TelephonyManager.CALL_STATE_OFFHOOK){
tts.stop();
tts.shutdown();
break;
}
tts.speak("Unknown Calling", TextToSpeech.QUEUE_FLUSH,
null);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
in the Blank class
public class Blank extends Activity implements OnClickListener{
Button b;
Window window;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.blank);
b=(Button)findViewById(R.id.button1);
b.setOnClickListener(this);
window = this.getWindow();
// use Window.addFlags() to add the flags in WindowManager.LayoutParams
window.addFlags(LayoutParams.FLAG_DISMISS_KEYGUARD);
window.addFlags(LayoutParams.FLAG_SHOW_WHEN_LOCKED);
window.addFlags(LayoutParams.FLAG_TURN_SCREEN_ON);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Button Clicked", Toast.LENGTH_SHORT).show();
AudioManager audio1 = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
//audio1.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
audio1.setStreamMute(AudioManager.STREAM_MUSIC, true);
finish();
}
}
Try following:
private Window window;
#Override
protected void onResume() {
super.onResume();
// get the window of your activity
window = this.getWindow();
// use Window.addFlags() to add the flags in WindowManager.LayoutParams
window.addFlags(LayoutParams.FLAG_DISMISS_KEYGUARD);
window.addFlags(LayoutParams.FLAG_SHOW_WHEN_LOCKED);
window.addFlags(LayoutParams.FLAG_TURN_SCREEN_ON);
}
Note: You can put this code in onCreate() as well, but I would suggest to put it in onResume().
FLAG_DISMISS_KEYGUARD - when set the window will cause the keyguard to be dismissed, only if it is not a secure lock keyguard.
FLAG_SHOW_WHEN_LOCKED - special flag to let windows be shown when the screen is locked
FLAG_TURN_SCREEN_ON - when set as a window is being added or made visible, once the window has been shown then the system will poke the power manager's user activity (as if the user had woken up the device) to turn the screen on.
I'm trying to create a Service that will play a music in the background in Android.
But I get an NPE while the service is starting.
Could anyone tell me what I'm doing wrong?
Log cat:
12-28 12:07:19.602: W/System.err(3768): java.lang.IllegalStateException
12-28 12:07:19.722: W/System.err(3768): at android.media.MediaPlayer.prepare(Native Method)
12-28 12:07:19.722: W/System.err(3768): at com.darkovski.quran.myPlayService.playMedia(myPlayService.java:413)
12-28 12:07:19.722: W/System.err(3768): at com.darkovski.quran.myPlayService.onPrepared(myPlayService.java:390)
12-28 12:07:19.722: W/System.err(3768): at android.media.MediaPlayer$EventHandler.handleMessage(MediaPlayer.java:1523)
12-28 12:07:19.722: W/System.err(3768): at android.os.Handler.dispatchMessage(Handler.java:99)
12-28 12:07:19.722: W/System.err(3768): at android.os.Looper.loop(Looper.java:137)
12-28 12:07:19.722: W/System.err(3768): at android.app.ActivityThread.main(ActivityThread.java:4441)
12-28 12:07:19.722: W/System.err(3768): at java.lang.reflect.Method.invokeNative(Native Method)
12-28 12:07:19.722: W/System.err(3768): at java.lang.reflect.Method.invoke(Method.java:511)
12-28 12:07:19.722: W/System.err(3768): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
12-28 12:07:19.722: W/System.err(3768): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
12-28 12:07:19.722: W/System.err(3768): at dalvik.system.NativeStart.main(Native Method)
My code:
public class myPlayService extends Service implements OnCompletionListener,
OnPreparedListener, OnErrorListener, OnSeekCompleteListener,
OnInfoListener, OnBufferingUpdateListener {
private static final String TAG = "TELSERVICE";
private MediaPlayer mediaPlayer = new MediaPlayer();
// songs
private ArrayList<Songs> songs;
private 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;
int intSeekPos;
int mediaPosition;
int mediaMax;
// Intent intent;
private final Handler handler = new Handler();
private static int songEnded;
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
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 = (ArrayList<Songs>) intent.getSerializableExtra("songs");
position = intent.getIntExtra("position", -1);
try {
mediaPlayer.setDataSource(songs.get(position).getLink());
} catch (IllegalArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// ---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, 1000); // 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;
stopMedia();
playMedia();
// stopSelf();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public void playMedia() {
if (!mediaPlayer.isPlaying()) {
try {
//line 413
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// 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);
}
}
Can anyone tell me what I'm doing wrong?
First, that's not an NPE (null pointer exception).
Second, you are calling your playMedia method entirely too often. Considering that it calls MediaPlayer.prepare, it doesn't make sense in several of the places I see it being called. In particular, you are calling it in the onPrepared callback. The MediaPlayer's state machine is giving you an IllegalStateException because you can't call prepare from the prepared state. You should also not call prepare from the onCompletion callback. The MediaPlayer has a strict state machine and you should probably pay more attention to it.
I am trying to make a service that plays in background which is unbounded. I have walked myself through some of the example codes on the internet but I can't get my application to play the radio when I'm calling the service class.
Please have a look at the code and tell me where I am going wrong... When I call MyService class from ArmanFMRadio onClick It toasts "My Service Created" & "My Service Started" but doesnt get to play the audio for the radio stream link. I've checked it otherwise and the link seems fine, so problem lies somewhere in the code to my understanding:
package com.etc.etcc;
public class ArmanFMRadio extends Activity implements OnClickListener {
private ProgressBar playSeekBar;
private Button buttonPlay;
private Button buttonStopPlay;
private MediaPlayer player;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.armanfm);
initializeUIElements();
//initializeMediaPlayer();
}
private void initializeUIElements() {
playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
playSeekBar.setMax(100);
playSeekBar.setVisibility(View.INVISIBLE);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonStopPlay.setEnabled(false);
buttonStopPlay.setOnClickListener(this);
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource("http://50.117.26.26:3953/Live");
} 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();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setVisibility(View.VISIBLE);
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
}
public void onClick(View v) {
switch(v.getId()){
case R.id.buttonPlay:
playSeekBar.setVisibility(View.VISIBLE);
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
startService(new Intent(this, MyService.class));
//startPlaying();
break;
case R.id.buttonStopPlay:
stopPlaying();
break;
}
}
private void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
playSeekBar.setVisibility(View.VISIBLE);
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
}
#Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
}
Just look at onClick on the above code, because this class works fine to my thinking.
MyService class:
package com.etc.etcc;
public class MyService extends Service {
private static final String TAG = "MyService";
private MediaPlayer player;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
}
#Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
player.stop();
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
player = new MediaPlayer();
try {
player.setDataSource("http://50.117.26.26:3953/Live");
} 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();
}
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
}
onStart is deprecated method. you should use onStartCommand method.
Debug your code and check weather there is any Exception or something
Also you are using the service so possible that you service will call twice in that case your onStartCommand method will be called twice so there you will have to check the startId which you will get as a parameter. If startId > 1 that means previously your service is started so you can stop media player and again start a media player with latest source or you can just ignore the second request.
If you are not confidence with service you can put your code in the activity and check weather your code is working fine or not after that you can replace this code in the service.