I have a background music which is in Service, it works fine but when I pressed the HOME Button the music won't stop. Help me.
Service:
public class BackgroundSoundService extends Service {
private static final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.haha);
player.setLooping(true); // Set looping
player.setVolume(100,100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
public void onStart(Intent intent, int startId) {
// TO DO
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
public void onStop() {
}
public void onPause() {
}
#Override
public void onDestroy() {
player.stop();
player.release();
}
#Override
public void onLowMemory() {
}
This is my Activity where have the intent:
public class MainActivity extends Activity implements OnClickListener {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent svc=new Intent(this, BackgroundSoundService.class);//This is the intent
startService(svc);
View adventuretime1 = this.findViewById(R.id.button1);
adventuretime1.setOnClickListener(this);
View advanced2 = this.findViewById(R.id.button2);
advanced2.setOnClickListener(this);
}
#Override
public void onBackPressed(){
new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Exit")
.setMessage("Are you sure you want to exit?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
System.exit(0);
}
}).setNegativeButton("No", null).show();
}
public void onClick(View v) {
switch(v.getId()){
case R.id.button1:
Intent button1 = new Intent(this, AdventureTime.class);
startActivity(button1);
break;
case R.id.button2:
Intent button2 = new Intent(this, AdvancedKids.class);
startActivity(button2);
break;
}
Well it is a Service and Services are supposed to have a longer life time that your UI activity or fragments. From your code I don't see the case where you are handling the HOME button click in your app and stopping the service or likewise. You should probably be doing that.Its just another H/W button which triggers events on which you can piggyback.
By the way whats System.exit(0); doing in your android code?
Because when you click the HOME_BUTTON,the service will not call onDestory().
You can register a broadcastReceiver for the HOME_BUTTON,like this:
context.registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//destory the service if you want
}
}, new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
If you just want to stop the Service, then you can call this method.
Related
I am a really junior android developer and do some practices on service right now. But I get some problems when doing this practice.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWidget();
registerListener();
}
public void getWidget()
{
startService = (Button) findViewById(R.id.startService);
shutdownService = (Button) findViewById(R.id.shutdownService);
}
public void registerListener()
{
ButtonListener bl = new ButtonListener();
startService.setOnClickListener(bl);
shutdownService.setOnClickListener(bl);
}
class ButtonListener implements View.OnClickListener
{
#Override
public void onClick(View v) {
Intent intent = null;
switch(v.getId())
{
case R.id.startService:
intent = new Intent(MainActivity.this,CountService.class);
startService(intent);
Log.v(TAG,"start service");
break;
case R.id.shutdownService:
intent = new Intent(MainActivity.this,CountService.class);
stopService(intent);
Log.v(TAG,"stop service");
break;
public class CountService extends Service{
boolean threadDisable ;
int count;
public IBinder onBind(Intent intent){
return null;
}
public void onCreate(){
super.onCreate();
/**New thread, count increased by 1 every 1s*/
new Thread(new Runnable(){
public void run(){
while(!threadDisable){
try{
Thread.sleep(1000);
}catch(InterruptedException e){
}
count++;
Log.v("CountService","Count is"+count);
}
}
}).start();
}
public void onDestroy(){
super.onDestroy();
/**service ends*/
this.threadDisable = true;
}
public int getConunt(){
return count;
}
class ServiceBinder extends Binder{
public CountService getService(){
return CountService.this;
}
}
When I click the button, the service doesn't run. Who can help me with that? Thank you.
Thanks for Perroloco's help. I forgot to add service permission in mainfest files.
<service android:name=".CountService"></service>
First of all, you don't need two instances of ButtonListener. This should be enough:
public void registerListener()
{
ButtonListener bl = new ButtonListener();
startService.setOnClickListener(bl);
shutdownService.setOnClickListener(bl);
}
Also, the intent you use is equal in both cases, so:
class ButtonListener implements View.OnClickListener
{
#Override
public void onClick(View v) {
intent = new Intent(MainActivity.this,CountService.class);
switch(v.getId())
{
case R.id.startService:
startService(intent);
Log.v(TAG,"start service");
break;
case R.id.shutdownService:
stopService(intent);
Log.v(TAG,"stop service");
break;
...
Now, I think your code is right, at least for starting the service. You should look at your service's code. I would start the thread in the onStartCommand method, and not in onCreate.
Also, did you declare your service in the manifest?
I have started an Intent activity from a service. Now, how I can stop that intent activity from service itself?
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void startService (View view) {
Intent intent = new Intent(this,MainService.class);
startService(intent);
}
public void stopService (View view) {
Intent intent = new Intent(this,MainService.class);
stopService(intent);
}
}
startService, stopService have buttons associated.
public class MainService extends Service {
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service started",Toast.LENGTH_LONG).show();
Intent dialogIntent = new Intent(this, calledActivity.class);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(dialogIntent);
return START_STICKY;
//return super.onStartCommand(intent,flags,startId);
}
#Override
public void onDestroy() {
//super.onDestroy();
Toast.makeText(this, "Service stopped",Toast.LENGTH_LONG).show();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
//Intent dialogIntent = new Intent(this, MainActivity.class);
//dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//startActivity(dialogIntent);
return null;
}
}
public class calledActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(this, "I am here", Toast.LENGTH_LONG).show();
displayNumber();
}
#Override
protected void onStop() {
super.onStop();
Toast.makeText(this, "I am stopping", Toast.LENGTH_LONG).show();
finish();
}
#Override
protected void onDestroy () {
super.onDestroy();
Toast.makeText(this, "I am being destroyed", Toast.LENGTH_LONG).show();
finish();
}
public void displayNumber () {
TextView tv = (TextView)findViewById(R.id.textView);
Integer counter = 10;
while (counter > 0) {
//tv.setText("Here you go" + String.valueOf(counter));
tv.setText("Here you go" + counter);
counter = counter - 1 ;
Toast.makeText(this, "I am there "+counter, Toast.LENGTH_LONG).show();
}
}
}
When service invokes the intent activity, I think intent activity is on the foreground. Now, whenever I press stop service button, application crashes. I believe as stopService is associated with the service class but not in the intent activity. Is there any way to stop the intent activity from the service?
Service works on UI thread. Try using IntentService. It runs on background thread.
I have created a Service and started using an Activity on Button click, but the Service gets stops after I closes an Activity. So what should I do to keep running the Service without gets stopped?
MainActivity.java
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void startService(View v){
Intent i = new Intent(this, NotStickyService.class);
startService(i);
}
public void stopService(View v){
Intent i = new Intent(this, NotStickyService.class);
stopService(i);
}
Service.java
public class NotStickyService extends Service{
MediaPlayer mp;
#Override
public void onCreate() {
showToast("onCreate");
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
showToast("onStart");
mp = new MediaPlayer();
AssetFileDescriptor descriptor;
descriptor = getAssets().openFd("msg.mp3");
mp.setDataSource(descriptor.getFileDescriptor(),
descriptor.getStartOffset(),descriptor.getLength());
descriptor.close();
mp.prepare();
mp.start();
return Service.START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
showToast("onDestroy");
}
private void showToast(String message){
Toast toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
toast.show();
}
}
I have a service and an activity that communicate.
When I click the button(I have galaxy s3 there is only one button) then my activity of course disapear and my service is keep running but if I click the back (touch) button then my service is destroyed.
How can I change that?I want the service to keep running untill the activity destroys it.
EDIT
Here is the code:
Service:
public class MyService extends Service
{
private static final String TAG = "BroadcastService";
public static final String BROADCAST_ACTION = "com.websmithing.broadcasttest.displayevent";
private final Handler handler = new Handler();
private Intent intent;
int counter = 0;
#Override
public void onCreate()
{
super.onCreate();
intent = new Intent(BROADCAST_ACTION);
}
#Override
public void onStart(Intent intent, int startId)
{
// handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 1000); // 1 second
}
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
DisplayLoggingInfo();
handler.postDelayed(this, 1000); // 10 seconds
}
};
private void DisplayLoggingInfo() {
intent.putExtra("counter", String.valueOf(++counter));
sendBroadcast(intent);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
handler.removeCallbacks(sendUpdatesToUI);
super.onDestroy();
}
}
Activity:
public class MainActivity extends Activity {
private static final String TAG = "BroadcastTest";
private Intent intent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intent = new Intent(this, MyService.class);
startService(intent);
registerReceiver(broadcastReceiver, new IntentFilter(MyService.BROADCAST_ACTION));
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateUI(intent);
}
};
#Override
public void onDestroy() {
super.onPause();
unregisterReceiver(broadcastReceiver);
stopService(intent);
}
private void updateUI(Intent intent)
{
String counter = intent.getStringExtra("counter");
Log.d(TAG, counter);
TextView txtCounter = (TextView) findViewById(R.id.textView1);
txtCounter.setText(counter);
}
}
you can put your app in the background instead off finishing it.
#Override
public void onBackPressed() {
moveTaskToBack(true);
// super.onBackPressed();
}
Ofcourse your service stops, when you press the back button. The back button most calls finish() on the activity, and it is destroyed. When you press the other button (the home button), it just minimizes your app, and it will be only destroyed later, when the OS wants to free up space.
If you want to keep your service running, make it a foreground service, and dont stop it on activity destroy.
I want to display an alert when a sms is received, so my idea is to start a new activity that launch the alertdialog.
My service starts with no problem, and starts receiver as well..
I can receive sms and display toast alerts fine.. but i'd like to show a custom alertdialog instead.
This is the activity that starts my service (ServiceExampleActivity ):
public class ServiceExampleActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnStartService = (Button) findViewById(R.id.btnStart);
Button btnStopService = (Button) findViewById(R.id.btnStop);
btnStartService.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
StartMyService();
}
});
btnStopService.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
StopMyService();
}
});
}
private void StartMyService() {
Intent myServiceIntent = new Intent(this, ServiceTest.class);
startService(myServiceIntent);
}
private void StopMyService() {
Intent myServiceIntent = new Intent(this, ServiceTest.class);
stopService(myServiceIntent);
}
}
This is my Service (ServiceTest):
public class ServiceTest extends Service {
private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
private BroadcastReceiver myBroadcastReceiver = null;
#Override
public void onCreate() {
super.onCreate();
final IntentFilter theFilter = new IntentFilter();
theFilter.addAction(ACTION);
this.myBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
StartDialogActivity(context, intent);
}
};
this.registerReceiver(myBroadcastReceiver, theFilter);
}
#Override
public IBinder onBind(Intent arg) {
return null;
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.d("ServiceTest", "Started");
Toast.makeText(this, "Service started...", 3000).show();
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(myBroadcastReceiver);
Toast.makeText(this, "Service destroyed...", 3000).show();
}
private void StartDialogActivity(Context context, Intent intent) {
Intent dlgIntent = new Intent(context, DialogActivity.class);
dlgIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(dlgIntent);
}
}
And this is the activity i want to launch to display the alertdialog normally..
public class DialogActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog);
}
}
When it tries to start the activity, the app crashes..
Can you tell me were is the error..??
Like this, you want start activity from service
Intent dlgIntent = new Intent(context, DialogActivity.class);
dlgIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(dlgIntent );