Service Broadcast Receiver Logs more than expected - android

My problem is that I think my service runs multiple times. The service is controlled by a switch calling a method that starts and stops the service. I have a broadcast listener inside my service and the receiver logs whenever it receives a broadcast. at first switch on, it logs two times. After switch off and on, it logs four times.
public class Service1 extends Service implements DetectionListener {
private static final String TAG = "ListenerService";
private final broadcastReceiver1 receiver = new broadcastReceiver1();
public HashMap<String, String> hashMapData;
private ARSonicManager arSonicManager;
public ListenerService() {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
IntentFilter filter = new IntentFilter();
filter.addAction("com.digify.almostrealsonic.broadcast_intent");
registerReceiver(receiver, filter);
}
#Override
public void onDestroy() {
unregisterReceiver(receiver);
super.onDestroy();
}
#Override
public void onStart(Intent intent, int startId) {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (null != intent) {
try {
hashMapData = (HashMap<String, String>) intent.getSerializableExtra("hashMapData");
// Do something with hashMapData
} catch (Exception e) {
Log.i("onStartCommand", e.toString());
}
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onMarkerDetected(String markerKey) {
Intent intent = new Intent();
intent.putExtra("hashMapData", hashMapData);
intent.setAction("com.broadcastReceiver1_intent");
sendBroadcast(intent);
}
public static class broadcastReceiver1 extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String hashMapData = intent.getStringExtra("hashMapData");
Log.i("receiver", "Got message: " + hashMapData);
}
}
}

Related

Created Service with accessibility service but unable to stop it

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

onCreate doesn't run in a service

I'm writing this service but I can't see the log strings when I launch the app.
if I put a Log.i in the method startBeaconDetecting I can see it but after the onCreate() method doesn't start.
Why onCreate doesn't run?
public class ProximityBeacon extends Service
{
private String server;
private String ID;
public ProximityBeacon(String server)
{
this.server=server;
//TODO indirizzo del server
}
public void startBeaconDetecting(String ID, Intent intent, Context context)
{
this.ID=ID;
context.startService(intent);
}
public void stopBeaconDetecting()
{
stopSelf();
onDestroy();
}
public void onCreate()
{
super.onCreate();
Log.i(TAG, "Oncreate");
}
public int onStartCommand(Intent intent, int flag, int startId)
{
Log.i(TAG, "onStartCommand");
return Service.START_STICKY;
}
}
Change your Service class to this:
public class ProximityBeacon extends Service
{
private static final String TAG = "TAG";
private String server;
private String ID;
public ProximityBeacon() {
}
public ProximityBeacon(String server)
{
this.server=server;
//TODO indirizzo del server
}
public void startBeaconDetecting(String ID, Intent intent, Context context)
{
this.ID=ID;
context.startService(intent);
}
public void stopBeaconDetecting()
{
stopSelf();
onDestroy();
}
public void onCreate()
{
super.onCreate();
Log.i(TAG, "ProximityBeacon Oncreate");
}
public int onStartCommand(Intent intent, int flag, int startId)
{
Log.i(TAG, "ProximityBeaconon StartCommand");
return Service.START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
and then call it using this:
new ProximityBeacon("").startBeaconDetecting("" ,new Intent(HomeActivity.this, ProximityBeacon.class) ,mContext) ;
then add it in manifest.xml like this :
<service android:name=".services.ProximityBeacon" />
Output : 19:25:11.873 23002-23002/com.sample.service I/TAG: ProximityBeaconon StartCommand
after startService(service); will run onStartCommand, not onCreate

Best practices for running worker threads for periodically updating the UI

What are the best practices for running worker threads in the background that periodically update UI elements in an activity. The goal here is to avoid any screen freezing on any kind of updates and if there are any specific guidelines/standards that should be followed.
Try Service for Background Work.
I have made an example for you.
Try this.
TestActivity.java
public class TestActivity extends AppCompatActivity {
private final String TAG = "TestActivity";
public final static String RECEIVER_ACTION = "com.action.MyReceiverAction";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_work);
registerMyReceiver();
startService(new Intent(this, BackgroundService.class));
}
MyReceiver myReceiver = new MyReceiver();
private void registerMyReceiver() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(RECEIVER_ACTION);
registerReceiver(myReceiver, intentFilter);
}
class MyReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent) {
Log.e(TAG, "onReceive() called");
}
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(myReceiver);
}
}
BackgroundService.java
public class BackgroundService extends Service {
private String TAG = "BackgroundService";
#Override
public void onCreate() {
super.onCreate();
Log.e(TAG, "onCreate() called");
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
Log.e(TAG, "onBind() called");
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "onStartCommand() called");
notifyToUI();
return super.onStartCommand(intent, flags, startId);
}
/**
* This Methd will notify your Activity
*/
private void notifyToUI()
{
Intent myIntent = new Intent();
myIntent.setAction(TestActivity.RECEIVER_ACTION);
sendBroadcast(myIntent);
}
}
Now at the end register BackgroundService in AndroidManifest.xml file
<service android:name=".BackgroundService"/>
Use AlarmManager (or some other timer) to periodically start a service. That service then updates the model, and notifies UI thread with for example LocalBroadcastManager. UI thread can then use BroadcastReceiver to catch the Intent and update itself.

Unable to receive Broadcast

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

Keep service while phone is alive

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

Categories

Resources