In this code I have created a service.After 3 seconds i want to destory this service and want to call another activity in destroy method.but this doesnt seem to work.
public class TimerService extends Service
{
#Override
public IBinder onBind(Intent intent)
{
return null;
}
#Override
public void onCreate()
{
super.onCreate();
}
#Override
public int onStartCommand(Intent intent,int flags,int startId)
{
new CountDownTimer(3000, 1000)
{
public void onTick(long millisUntilFinished)
{
}
public void onFinish()
{
stopSelf();
}
}.start();
return super.onStartCommand(intent,flags,startId);
}
#Override
public void onDestroy()
{
super.onDestroy();
Intent i = new Intent(this,Dummy.class);
i.putExtra("SessionTimedOut","Expire");
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(i);
}
}
Activity which calls My Service
public class MainActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent i = new Intent(this,TimerService.class);
startService(i);
}
}
Try to insert the code to the finish method:
#Override
public int onStartCommand(Intent intent,int flags,int startId)
{
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(this,Dummy.class);
i.putExtra("SessionTimedOut","Expire");
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
stopSelf();
}
}, 3000);
return super.onStartCommand(intent,flags,startId);
}
Related
I have created a service. When I start it from MainActivity its started but when I click on button to stop it it's doesn't stop. It is working fine in lower version devices but only issue found in Android 10 or higher versions.
public void startServices() {
Intent intent = new Intent(getApplicationContext(), PerformTaskService.class);
startService(intent);
}
public void stopServices() {
stopService(new Intent(getApplicationContext(), PerformTaskService.class));
}
PerformTaskService.java
public class PerformTaskService extends Service {
String TAG = "ServiceStatus";
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
int id;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
this.id = startId;
Log.e(TAG, "onStartCommand: "+startId );
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
stopSelfResult(id);
stopSelf(id);
new StatusBarService().onDestroy();
stopSelf();
super.onDestroy();
}
}
StatusBarService.java
public class StatusBarService extends AccessibilityService {
int id;
#Override
public ComponentName startForegroundService(Intent service) {
return super.startForegroundService(service);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
this.id = startId;
return START_NOT_STICKY;
}
#SuppressLint({"InflateParams", "InlinedApi"})
#Override
public void onCreate() {
super.onCreate();
View mFloatingView =
LayoutInflater.from(this).inflate(R.layout.layout_floating_widget,
null);
thumbView =
LayoutInflater.from(this).inflate(R.layout.layout_seekbar_thumb,
null, false);
deviceManger = ((DevicePolicyManager)
getSystemService(Context.DEVICE_POLICY_SERVICE));
}
#Override
public void onAccessibilityEvent(AccessibilityEvent event) {
}
#Override
public void onInterrupt() {
}
public void deviceadminCheck() {
Intent intent = new
Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
#Override
public void onDestroy() {
stopSelf();
stopSelf(id);
stopSelfResult(id);
super.onDestroy();
}
}
So, kindly let me know if you have any proper solution or Idea about this issue. how to stop service
I make a service for countdown timer, in activity i put a text view for show time every seconds: 100 - 0, but when i leave activity and back to that. i see timer as run very fast, but i want to this run just every second. where is problem ?
MainActivity:
public static final String mBroadcastIntegerAction = "com.example.broadcast.integer";
private IntentFilter mIntentFilter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showTime = (TextView) findViewById(R.id.textView1);
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(mBroadcastIntegerAction);
Intent serviceIntent = new Intent(this, AppServiceDay.class);
startService(serviceIntent);
}
#Override
public void onResume() {
super.onResume();
registerReceiver(mReceiver, mIntentFilter);
}
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(mBroadcastIntegerAction)) {
int second = intent.getIntExtra("Time", 0);
showTime.setText("" + second);
}
}
};
#Override
protected void onPause() {
registerReceiver(mReceiver, mIntentFilter);
// unregisterReceiver(mReceiver);
super.onPause();
}
Service:
public class AppServiceDay extends Service {
CountDownTimer cdt;
public static Handler mHandler;
int downer = 1000;
int time = 100;
int mainTime = 100000;
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
cdt = new CountDownTimer(mainTime, downer) {
#Override
public void onTick(long millisUntilFinished) {
time -= 1;
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(MainActivity.mBroadcastIntegerAction);
broadcastIntent.putExtra("Time", time);
sendBroadcast(broadcastIntent);
}
#Override
public void onFinish() {
time = 100;
this.start();
}
};
cdt.start();
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
onStartCommand is triggered everytime startService is called and in onStartCommand you are creating new countdown object,
Add a null check before creating new countdown object it will fix your duplicate timer running at same time.
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
If(cdt == null) {
cdt = new CountDownTimer(mainTime, downer) {
#Override
public void onTick(long millisUntilFinished) {
time -= 1;
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(MainActivity.mBroadcastIntegerAction);
broadcastIntent.putExtra("Time", time);
sendBroadcast(broadcastIntent);
}
#Override
public void onFinish() {
time = 100;
this.start();
}
};
cdt.start();
}
return super.onStartCommand(intent, flags, startId);
}
I have simple app for testing android:process attribute of service. So my service looks like this:
public class MyService extends IntentService {
static final String TAG = "MyService";
public MyService() {
super("MyService");
}
#Override
public void onCreate() {
super.onCreate();
Log.d(TAG,"onCreate()");
}
#Override
protected void onHandleIntent(Intent intent) {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
doJob();
return START_STICKY;
}
private void doJob() {
new Thread(new Runnable() {
#Override
public void run() {
Log.i(TAG,"job started");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i(TAG,"job stopped");
stopSelf();
}
}).start();
}
}
I'm trying to start service from the activity as follows:
findViewById(R.id.startServiceBtn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startService(new Intent(getApplicationContext(),MyService.class));
}
});
All works fine. Now i'm adding android:process=":service" attribute to service declaration in the manifest. And after that service doesnt't start. So why so and what should i change for start service in separate process?
I think you have to do this task i.e dowork() method call in onHandleIntent(). Because your service class extending Intent service instead of Service.
public class MyService extends IntentService {
static final String TAG = "MyService";
public MyService() {
super("MyService");
}
#Override
protected void onHandleIntent(Intent intent) {
doJob();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
}
private void doJob() {
new Thread(new Runnable() {
#Override
public void run() {
Log.i(TAG,"job started");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i(TAG,"job stopped");
stopSelf();
}
}).start();
}
}
oh sorry it was silly mistake - i have to select new process in android monitor tab) thanks to all
I am sending a Broadcast from my Service and trying to receive in my Activity but I don't see it receiving. Can someone suggest if I am doing something wrong. I am seeing onResume getting called but don't see flag
Log.d("InchooTutorial", msg_for_me);
getting logged.
Service Code :
Intent sendableIntent = new Intent("SOTGSAMReceiver");
sendableIntent.putExtra("kicked", prefs.getSurveySubmittedStatus(context));
LocalBroadcastManager.getInstance(AcrService.this).sendBroadcast(sendableIntent;
Activity Code :
// Get Broadcast
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.d("InchooTutorial", "Inside onResume");
IntentFilter intentFilter = new IntentFilter("SOTGSAMReceiver");
mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// extract our message from intent
String msg_for_me = intent.getStringExtra("kicked");
// log our message value
Log.d("InchooTutorial", msg_for_me);
}
};
// registering our receiver
this.registerReceiver(mReceiver, intentFilter);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
// unregister our receiver
this.unregisterReceiver(this.mReceiver);
}
If you are using LocalBroadcastManager to send broadcast you need to register with it.
Write for register:
LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, intentFilter);
And for unregister:
LocalBroadcastManager.getInstance(this).unregisterReceiver(this.mReceiver);
public class BroadcastService extends Service {
private final static String TAG = "BroadcastService";
public static final String COUNTDOWN_BR = "com.sixmod.com.sixmod.MyReceiver";
Intent bi = new Intent(COUNTDOWN_BR);
Intent ci = new Intent(COUNTDOWN_BR);
CountDownTimer cdt = null;
#Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Starting timer...");
cdt = new CountDownTimer(180000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
Log.i(TAG, "Countdown seconds remaining: " + millisUntilFinished / 1000);
bi.putExtra("countdown", millisUntilFinished);
sendBroadcast(bi);
}
#Override
public void onFinish() {
ci.putExtra("countdownFinish", 1);
sendBroadcast(ci);
Log.i(TAG, "Timer finished");
}
};
cdt.start();
}
#Override
public void onDestroy() {
cdt.cancel();
Log.i(TAG, "Timer cancelled");
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
In Activity
private BroadcastReceiver br = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateGUI(intent); // or whatever method used to update your GUI fields
}
};
#Override
public void onResume() {
super.onResume();
getActivity().registerReceiver(br, new IntentFilter(BroadcastService.COUNTDOWN_BR));
Log.e("Receiver Registered", "Registered broacast receiver");
}
#Override
public void onPause() {
super.onPause();
getActivity().unregisterReceiver(br);
Log.e("Unregistered", "Unregistered broacast receiver");
}
#Override
public void onStop() {
try {
getActivity().unregisterReceiver(br);
} catch (Exception e) {
// Receiver was probably already stopped in onPause()
}
super.onStop();
}
#Override
public void onDestroy() {
super.onDestroy();
}
private void updateGUI(Intent intent) {
if (intent.getExtras() != null) {// here you fetch the data
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