How can I turn off Service in Android? OR How can I unregiser or turn off Reciever?
public void onDestroy() doesn't work
This is my Service
public class LockScreenService extends Service{
BroadcastReceiver mReceiver;
public static volatile boolean isMustBeLocked;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
KeyguardManager.KeyguardLock k1;
//getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON|WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
if(isMustBeLocked) {
KeyguardManager km = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
k1 = km.newKeyguardLock("IN");
k1.disableKeyguard();
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
mReceiver = new LockScreenReceiver();
registerReceiver(mReceiver, filter);
super.onCreate();
}
else{
Log.e("LockScreenService","TEST");
}
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
}
/*#Override
public void onPause(){
}*/
public void destroy(){
if(mReceiver!=null) {
unregisterReceiver(mReceiver);
Log.e("","TEST destroy3");
}
Log.e("","TEST destroy2");
}
#Override
public void onDestroy() {
if(mReceiver!=null) {
unregisterReceiver(mReceiver);
Log.e("","TEST destroy");
}Log.e("","TEST destroying");
super.onDestroy();
}
}
To turn off the service:
Intent intent = new Intent(this, Service.class)
stopService(intent);
To unregister Receiver be sure to first :
unregisterReceiver(mybroadcast);
Service- you call stopService. Inside the service you can call stopSelf. Receivers you call unregisterReceiver (only works for dynamically created receivers, not with ones registered in the manifest).
Related
I'm working on an Android app in which I need to detect when user locked and unlocked, not the screen on/off. So, that I can perform certain action according locked and unlocked. But I'm unable to achieve my goal.
I declare a broadcast inside a service, register the service and receiver inside the manifest and also actions.
It's working fine, when app is open. As the app goes in background it's stop working.
public class UseService extends Service {
#Nullable
Vibrator vibr;
MediaPlayer audi;
//This is Service Class
#Override
public IBinder onBind(Intent intent) {
return null;
}
public void onCreate() {
super.onCreate();
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction("android.intent.action.SCREEN_ON");
registerReceiver(receiver, filter);
}
//Broadcast Receiver
private final BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
KeyguardManager myKM = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
if (action.equals(Intent.ACTION_SCREEN_OFF) && myKM.inKeyguardRestrictedInputMode())
{
vibr.vibrate(500);
if( action.equals(Intent.ACTION_SCREEN_ON) && !myKM.inKeyguardRestrictedInputMode() )
{
vibr.vibrate(5000);
}
}
}
};
//************************Started*************
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
audi=MediaPlayer.create(UseService.this, R.raw.start);
Toast.makeText(UseService.this, "The Service Has Been Started",Toast.LENGTH_SHORT).show();
return START_STICKY;
}
//*******************OnDestroy****************
#Override
public void onDestroy() {
Toast.makeText(UseService.this, "The Service is Destroyed",Toast.LENGTH_SHORT).show();
unregisterReceiver(receiver);
}
}
Main Activity
public class MainActivity extends AppCompatActivity {
Vibrator vibr;
Button btns;
//this is MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btns=(Button)findViewById(R.id.btn);
vibr=(Vibrator) getSystemService(VIBRATOR_SERVICE);
btns.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(getApplicationContext(), UseService.class);
startService(intent);
}
});
}
#Override
protected void onPause() {
super.onPause();
}
}
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
please before you don't like my question , please read the details .. what i am trying to do is to use a broadcast receiver when screen-off , so i want my app to start if the screen goes off .. here is my broadcast receiver code :
public class BootReceiver extends BroadcastReceiver {
public boolean screenoff;
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenoff = true;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenoff = false;
}
Intent intent1 = new Intent(context, ShakeService.class);
intent1.putExtra("screen_state", screenoff);
context.startService(intent1);
}
and here is the service code :
public class ShakeService extends Service{
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stu
return null;
}
#Override
public void onCreate() {
super.onCreate();
// REGISTER RECEIVER THAT HANDLES SCREEN ON AND SCREEN OFF LOGIC
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new BootReceiver();
registerReceiver(mReceiver, filter);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
try{
Intent intent1 = new Intent(getApplicationContext(), SplashScreen.class)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return START_STICKY;
}
}
and here is my splash screen activity that i call from the service :
public class SplashScreen extends Activity {
private static int SPLASH_TIME_OUT=3000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_splash_screen);
ImageView imageView = (ImageView) findViewById(R.id.imageView1);
new Handler().postDelayed(new Runnable(){
public void run(){
Intent i =new Intent(SplashScreen.this,HomeScreen.class);
startActivity(i);
finish();
}
},SPLASH_TIME_OUT);
}
#Override
protected void onResume() {
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
BroadcastReceiver mReceiver = new BootReceiver();
registerReceiver(mReceiver, filter);
super.onResume();
}
#Override
protected void onPause() {
// mSensorManager.unregisterListener(mShakeDetector);
BroadcastReceiver mReceiver = new BootReceiver();
unregisterReceiver(mReceiver);
super.onPause();
}
}
and as you can noticed i have unregistered my receiver but still i keep seeing this in the logcat :
leaked Intent Receiver are you missing a call to unregisterReceiver??
I agree with the method of registering the receiver in onResume() and unregistering it in onPause(). This helps when the app goes in and out of scope. I'm somewhat confused on what you're trying to do with your app, but initially I see that you create a new instance of the braodcast receiver in onPause() and unregister that. Try unregistering using the same instance . Also, if you want your service to remain running in the background, you may want to look into implementation of a partial wake lock, that keeps the CPU running for your app while the screen remains off. Could you provide one more details about the purpose of the app?
I have broadcast receiver that activates on phone boot
public class autostart extends BroadcastReceiver {
public void onReceive(Context arg0, Intent arg1) {
Intent intent = new Intent(arg0, MyService.class);
arg0.startService(intent);
Log.i("Autostart", "started");
}
}
The service is very simple it just keeps registered an broadcast receiver that can be only registered by code and not from manifest
public class MyService extends Service
{
private static final String TAG = "MyService";
#Override
public IBinder onBind(Intent intent) {
return null;
}
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
}
ScreenOffReceiver actionScreenOffReceiver;
#Override
public void onStart(Intent intent, int startid)
{
try {
IntentFilter intentfilter = new IntentFilter();
intentfilter.addAction(Intent.MY_ACTION);
registerReceiver(actionScreenOffReceiver = new ScreenOffReceiver(),
intentfilter);
} catch (Exception e) {
}
}
}
The problem is that if the app get closed, for example with call of finish() on some activity, then the service just dies.
How can I keep the service running till the phone is turned on
what is the right way to do this ?
You don't need an BroadcastReceiver just add this code in your Service
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
Source: Service | Android Developers
How to get trigger that screen is locked or on in android??
i tried using SCREEN_OFF & SCREEN_ON action in broadcast receiver but it's not working.
public void onReceive(Context context, Intent intent) {
Log.d("XYZ", "Screen ON/OFF");
Toast.makeText(context, "screen",10000).show();
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
.......
}
}
in activity i have registered broadcast like-
screen is object of my broadcast receiver
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
mContext.registerReceiver(screen, filter);
Call the UpdateService.class within your MainActivity.class .
startService(new Intent(MainActivity.this, UpdateService.class));
UpdateService.class
public class UpdateService extends Service {
BroadcastReceiver mReceiver;
public static int countOn = 0;
public static int countOff = 0;
#Override
public void onCreate() {
super.onCreate();
// register receiver that handles screen on and screen off logic
Log.i("UpdateService", "Started");
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_ANSWER);
mReceiver = new MyReceiver();
registerReceiver(mReceiver, filter);
}
#Override
public void onDestroy() {
unregisterReceiver(mReceiver);
Log.i("onDestroy Reciever", "Called");
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
boolean screenOn = intent.getBooleanExtra("screen_state", false);
if (!screenOn) {
Log.i("screenON", "Called");
Log.i("viaService", "CountOn =" + countOn);
Toast.makeText(getApplicationContext(), "Awake", Toast.LENGTH_LONG)
.show();
} else {
Log.i("screenOFF", "Called");
Log.i("viaService", "CountOff =" + countOff);
}
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
Receiver class
public class MyReceiver extends BroadcastReceiver {
private boolean screenOff;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenOff = true;
// Log.i("via Receiver","Normal ScreenOFF" );
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenOff = false;
} else if(intent.getAction().equals(Intent.ACTION_ANSWER)) {
}
Intent i = new Intent(context, UpdateService.class);
i.putExtra("screen_state", screenOff);
context.startService(i);
}
}
Hey try using dynamic calling of broadcast,I tried this it will surly work...
public class MainActivity extends Activity {
//Create broadcast object
BroadcastReceiver mybroadcast = new BroadcastReceiver() {
//When Event is published, onReceive method is called
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.i("[BroadcastReceiver]", "MyReceiver");
if(intent.getAction().equals(Intent.ACTION_SCREEN_ON)){
Log.i("[BroadcastReceiver]", "Screen ON");
}
else if(intent.getAction().equals(Intent.ACTION_SCREEN_OFF)){
Log.i("[BroadcastReceiver]", "Screen OFF");
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerReceiver(mybroadcast, new IntentFilter(Intent.ACTION_SCREEN_ON));
registerReceiver(mybroadcast, new IntentFilter(Intent.ACTION_SCREEN_OFF));
}
}