Service won't start in android - android

Hi!
I have a service that should be playing an audio file when it is started from an activity (by a click on the button). The problem is though, the service won't start when i click the required button in my activity.
Service class (with imports and some other methods omitted):
public class ClockService extends Service {
MediaPlayer myMediaPlayer;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
myMediaPlayer = MediaPlayer.create(this, R.raw.audio);
myMediaPlayer.setLooping(true);
}
#Override
public void onStart(Intent intent, int startid) {
myMediaPlayer.start();
}
}
The activity it is called from:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button startButton = (Button) findViewById(R.id.startButton);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startService(new Intent(getBaseContext(), ClockService.class));
}
});
}
}
I've struggled with it for an hour already, and i can't see what's wrong.

u got problem on below code line.u cant use this for context inside service.u need to pass context of mainactivity to service to get mediaplayer instance inside service.
myMediaPlayer = MediaPlayer.create(this, R.raw.audio);//wrong one

The problem is how you started the service
Change this line to startservice(new intent(mainactivity.this, clockservice));
here is a link you can refer to.

Related

How to stop previous ringtone?

I am trying to write a small android app for my son. The idea is to make ringtone start to play on button click and it should be stoped by clicking on the other button. Something like you click a button to start a calling and another button to answer to it.
What I manage to do is to make the first button to ring to work by the following code:
CallLukas.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), notification);
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
}
});
However, the second button to stop the ringtone does not work as it suppose to. I use the following code:
Incoming.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mp.isPlaying()) {
mp.stop();
mp.release();
}
}
});
It stops the ringtone but in the same time makes the app to crash.
What would be the right way to stop the previously activated ringtone?
Thnak you...
This answer should help you.
I believe the problem is you're creating multiple MediaPlayer objects. Also try to use .reset() instead of .stop().
The solution for my issue was making the MediaPlayer as a service.
I have created a new Java class to extend the service class. Here is the code for it:
public class RingtoneService extends Service {
private MediaPlayer mp;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mp = MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI);
mp.setLooping(true);
mp.start();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
mp.stop();
}
}
Then I have updated my MainActivity class with the fallowing code:
CallLukas.setOnClickListener(this);
Incoming.setOnClickListener(this);
#Override
public void onClick(View v) {
if (v == CallLukas){
startService(new Intent(this, RingtoneService.class));
}else if (v == Incoming) {
stopService(new Intent(this, RingtoneService.class));
}
}
The code basically sets the OnClickListener on my buttons and starts the service if one is clicked and stops the service if the other is clicked.
The final steps are to add the newly created service to the AndroidManifest file. It needs to be added inside the <application> tag.
<application
<service android:name=".RingtoneService"></service>
</application>
The completed instruction on how to implement this can be found here:
https://www.youtube.com/watch?v=p2ffzsCqrs8&t=315s

how can I stop music in one activity and start another music in next activity?

I have 3 activity, when I move from 1st act.to 2nd act. one music will start, and when I move from 2nd act. to 3rd act., 2nd activity's music should stop and 3rd activity's music should start. As per my coding, 2nd activity's music is stopping, but 3rd activity's music does not start. my code is given here-under: please help me.
//1st activity code start
public class MainActivity extends AppCompatActivity {
Button b;
static MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onResume() {
super.onResume();
final MediaPlayer mp = MediaPlayer.create(this,R.raw.bakaratwozeroone);
b = (Button) findViewById(R.id.butmove);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mp.start();
startActivity(new Intent(MainActivity.this,Main2Activity.class));
}
});
}
}
//1st activity code end
//2nd activity code start
public class Main2Activity extends AppCompatActivity {
Button b;
static MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
#Override
protected void onResume() {
super.onResume();
final MediaPlayer mp = MediaPlayer.create(this, R.raw.mumfive);
b = (Button) findViewById(R.id.butmove2);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mp.start();
startActivity(new Intent(Main2Activity.this, Main3Activity.class));
}
});
}
#Override
protected void onPause() {
super.onPause();
if(mp !=null);
mp.release();
mp = null;
}
}
//2nd activity code end
No need to keep MediaPlayer instance on every activity, Use BoundService to run media player and make communication with Service and activities.
For reference,use this link
https://github.com/SimpleMobileTools/Simple-Music-Player

service stops when app is swiped off

I'm trying to play an mp3 when app is closed. It works when I'm out of the app but when i swipe it off from task manager the song ends. How can I make the service continue playing after close?
This is my service:
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onTaskRemoved(Intent rootIntent) {
Log.d("MusicService", "onTaskRemoved");
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
This is my main activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button)findViewById(R.id.start);
stop = (Button)findViewById(R.id.stop);
mp = MediaPlayer.create(getApplicationContext(),R.raw.gucci);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startService(new Intent(MainActivity.this,MyService.class));
mp.start();
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.pause();
stopService(new Intent(MainActivity.this,MyService.class));
}
});
}
NOTE: Other way may be not usable (ignore if not usable).
Don't give user the option to clear it from recents menu.
Use this manifest attribute for each activity component in your Player app
android:excludeFromRecents
just return START_STICKY in onstartcommand method of your service class . it will run forever in background .

Interface method cannot change TextView text in android

I am running an android service. I wish to change a TextView text when I get expected result from the service. I have implemented an interface method to get a callback to change my textView. Interface abstract method runs well but cannot change the Textview text of my activity.
I have simplified sample code here
public class MainActivity extends Activity implements MyInterface {
TextView mTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.sample_text);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("Asim----", "Start service"); // print this line well
startService(new Intent(MainActivity.this, MyService.class));
}
});
}
#Override
public void testMe() {
Log.e("Asim----", "Hi"); // print this line well
mTextView.setText("New Text"); // Chrashes happens here
}
}
The MyService class here
public class MyService extends Service {
#Override
public void onCreate() {
//super.onCreate();
Log.e("test1------", "onCreate"); // print this line well
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("test2------", "onStartCommand"); // print this line well
MyInterface mi = new MainActivity();
mi.testMe();
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
mTextView should be null you have to find it in this method
#Override
public void testMe() {
Log.e("Asim----", "Hi"); // print this line well
mTextView = (TextView) findViewById(R.id.sample_text);
mTextView.setText("New Text"); // Chrashes happens here
}
Try it once.
you need to pass Activity in your interface as well
#Override
public void testMe(Activity actvity) {
Log.e("Asim----", "Hi"); // print this line well
mTextView = (TextView) activity.findViewById(R.id.sample_text);
mTextView.setText("New Text"); // Chrashes happens here
}

Android: How do you start a wallpaperservice from a button?

I have a test live wallpaper that I wish to start from an activity. At the moment, it immediately finds itself in the live wallpaper chooser as I run the project on my emulator. Having searched everywhere, I still can't find a way to make it show up there only after a button in my main activity is pressed.
I tried introducing a static boolean in my main activity, isnotpressed, and setting it to false in the button onClick(). Then I used stopSelf() in my wallpaperservice class while isnotpressed is true. Unfortunately, none of this was to any avail and I don't think I'm going about it in the right way anyway. I also tried this, but it didn't work either. Any help would be deeply appreciated here.
Here's the main activity:
public class TestProjectActivity extends Activity{
static boolean isnotPressed;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
isnotPressed = true;
final Button b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
isnotPressed = false;
}
});
}
}
And here's part of the wallpaperservice:
public class MyWallpaperService extends WallpaperService {
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
while(TestProjectActivity.isnotPressed){stopSelf();}
}
Try this :
Intent i = new Intent();
if (Build.VERSION.SDK_INT > 15)
{
i.setAction(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER);
String pkg = MyPreferencesActivity.class.getPackage().getName();
String cls = MyPreferencesActivity.class.getCanonicalName();
i.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT, new ComponentName(pkg, cls));
}
else
{
i.setAction(WallpaperManager.ACTION_LIVE_WALLPAPER_CHOOSER);
}
startActivityForResult(i, 0);

Categories

Resources