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();
}
}
Related
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 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.
I have a thread inside a service and I would like to be able to stop the thread when I press the buttonStop on my main activity class.
In my main activity class I have:
public class MainActivity extends Activity implements OnClickListener {
...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonStart = (Button) findViewById(R.id.buttonStart);
buttonStop = (Button) findViewById(R.id.buttonStop);
buttonStart.setOnClickListener(this);
buttonStop.setOnClickListener(this);
}
public void onClick(View src) {
switch (src.getId()) {
case R.id.buttonStart:
startService(new Intent(this, MyService.class));
break;
case R.id.buttonStop:
stopService(new Intent(this, MyService.class));
break;
}
}
}
And in my service class I have:
public class MyService extends Service {
...
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
int icon = R.drawable.myicon;
CharSequence tickerText = "Hello";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, "notification title", "notification message", pendingIntent);
startForeground(ONGOING_NOTIFICATION, notification);
...
}
#Override
public void onStart(Intent intent, int startid) {
Thread mythread= new Thread() {
#Override
public void run() {
while(true) {
MY CODE TO RUN;
}
}
}
};
mythread.start();
}
}
what is the best way to stop the mythread?
Also is the way that I have stopped the service by stopService(new Intent(this, MyService.class)); correct?
You can't stop a thread that has a running unstoppable loop like this
while(true)
{
}
To stop that thread, declare a boolean variable and use it in while-loop condition.
public class MyService extends Service {
...
private Thread mythread;
private boolean running;
#Override
public void onDestroy()
{
running = false;
super.onDestroy();
}
#Override
public void onStart(Intent intent, int startid) {
running = true;
mythread = new Thread() {
#Override
public void run() {
while(running) {
MY CODE TO RUN;
}
}
};
};
mythread.start();
}
You call onDestroy() method for stop service.
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 );
Hi friends i have a one problem to solve...I want to destroy the service completely, once i call onDestroy() method from Activity. But my problem is that i am unable to destroy it completely.. in background its keep on running, i am sharing the sample code what i tried..
//Activity Class
public class ServiceToAct extends Activity {
private static final String TAG = "BroadcastEvent";
private Intent intent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
intent = new Intent(this, BroadcastService.class);
startService(intent);
registerReceiver(broadcastReceiver, new IntentFilter(myService.BROADCAST_ACTION));
}
/*#Override
protected void onResume() {
super.onResume();
}*/
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
}
#Override
protected void onDestroy() {
stopService(intent);
Toast.makeText(this, "Destroy Completely", Toast.LENGTH_LONG).show();
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
}
};
}
// service class
public class myService extends Service {
private static final String TAG = "BroadcastEvent";
public static final String BROADCAST_ACTION = "com.service.activity.myService";
private final Handler handler = new Handler();
Intent intent;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "created", Toast.LENGTH_LONG).show();
intent = new Intent(BROADCAST_ACTION);
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Toast.makeText(this, "start", Toast.LENGTH_LONG).show();
handler.removeCallbacks(sendToUI);
handler.postDelayed(sendToUI, 1000);
}
#Override
public void onDestroy() {
super.onDestroy();
stopSelf();
//stopService(intent);
Toast.makeText(this, "Destroy", Toast.LENGTH_LONG).show();
}
private Runnable sendToUI = new Runnable() {
#Override
public void run() {
myData();
handler.postDelayed(this, 10000);
}
};
private void myData() {
Log.d(TAG, "keep on entering");
Toast.makeText(this, "Keep on despling in UI", Toast.LENGTH_LONG).show();
sendBroadcast(intent);
}
}
Here Actually i want to update my UI from service, Mine everything is working, but if i destroy the service its keep on calling myData() method, and i am getting the Toast msg if i close the application also.
My issue is i don't want that toast msg once the service is desroyed
I used stopService(intent) method, which destroy the service, but background method myData() is keep on calling
for stop service completely use this ..
myActivity.java
#Override
public void onDestroy() {
stopService(intent);
super.onDestroy();
Toast.makeText(this, "Destroy", Toast.LENGTH_LONG).show();
}
service.java
#Override
public void onDestroy()
{
stopSelf();
super.onDestroy();
}
You'd better never call onXxx() derectly.
Use stopService(Intent i) in your activity and stopSelf() in you service to stop instead.
use stopService() method after updating UI
or
Instead of using startService use bindService in the activity. When activity destroys, service also destroys