I m new on android
I want to start two services and one service sendbroadcast another will catch this broadcast but it is not working even if I register another service in this broadcasting
here is my code am I doing something wrong ?
Thanks advice.
public class MainActivity extends Activity {
Intent i;
Intent i2;
static final String LOG_TAG = "ServiceActivity";
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
Log.d(LOG_TAG, "onCreate");
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
//Start service
i = new Intent(this, com.example.user.sensorservicetest.SimpleService.class);
i2= new Intent(this,com.example.user.sensorservicetest.AnotherService.class);
Log.d(LOG_TAG, "onCreate/startService");
}
#Override
public void onResume() {
super.onResume();
Log.d(LOG_TAG, "onResume/registering receiver");
//Register BroadcastReceiver to receive accelerometer data from service
startService(i);
startService(i2);
}
}
#Override
public void onPause() {
super.onPause();
Log.d(LOG_TAG, "onPause/unregistering receiver");
stopService(i);
stopService(i2);
}
#Override
protected void onStop() {
super.onStop();
Log.d(LOG_TAG, "onStop");
stopService(i);
stopService(i2);
}
}
SimpleService
public class SimpleService extends Service implements SensorEventListener {
private String reading;
private SensorManager mgr;
private List<Sensor> sensorList;
static final String LOG_TAG = "SimpleService";
Intent intent = new Intent("com.practice.SimpleService.MY_ACTION");
final static String MY_ACTION = "com.practice.SimpleService.MY_ACTION";
#Override
//public void onStartCommand() {
public void onCreate() {
Log.d(LOG_TAG, "onStartCommand");
mgr = (SensorManager) getSystemService(SENSOR_SERVICE);
sensorList = mgr.getSensorList(Sensor.TYPE_ACCELEROMETER);
for (Sensor sensor : sensorList) {
mgr.registerListener(this, sensor,
SensorManager.SENSOR_DELAY_NORMAL);
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent,flags,startId);
}
#Override
public void onDestroy() {
Log.d(LOG_TAG, "onDestroy");
mgr.unregisterListener(this);
super.onDestroy();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
Log.d(LOG_TAG, "onSensorChanged");
StringBuilder builder = new StringBuilder();
for (int i = 0; i < event.values.length; i++) {
builder.append(" [");
builder.append(i);
builder.append("] = ");
builder.append(event.values[i]);
builder.append("\n");
}
reading = builder.toString();
//Send back reading to Activity
intent.putExtra("measurement", reading);
sendBroadcast(intent);
}
}
AnotherService
public class AnotherService extends Service {
static final String TAG = "AnotherService";
private AnotherServiceReceiver anotherServiceReceiver = new AnotherServiceReceiver();
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG,"onStartCommand");
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.practice.SimpleService.MY_ACTION");
registerReceiver(anotherServiceReceiver, intentFilter);
return super.onStartCommand(intent,flags,startId);
}
#Override
public void onDestroy() {
if (anotherServiceReceiver != null)
unregisterReceiver(anotherServiceReceiver);
super.onDestroy();
}
public static class AnotherServiceReceiver extends BroadcastReceiver {
static final String receiverTag = "AnotherServiceReceiver";
#Override
public void onReceive(Context context, Intent intent) {
Log.d(receiverTag, "onReceive");
String measurement = intent.getStringExtra("measurement");
Log.d(receiverTag, "measurement - 2 : " + measurement);
}
}
}
Manifest
<service android:name=".SimpleService" ></service>
<service android:name=".AnotherService"></service>
<receiver android:name=".AnotherService$AnotherServiceReceiver" android:enabled="true">
<intent-filter>
<action android:name="here is problem I think"
</intent-filter>
</receiver>
According #Evgeniy Mishustin answer (thanks to him)
Solution is adding service in manifest xml file now working each service communication
<service android:name=".SimpleService" ></service>
<service android:name=".AnotherService"></service>
<receiver android:name=".AnotherService$AnotherServiceReceiver" android:enabled="true">
<intent-filter>
<action android:name="com.practice.SimpleService.MY_ACTION"></action>
</intent-filter>
</receiver>
</application>
Related
I have tried this code but it's not working. Does anybody have any different solution? I have tried many ways like the below one from Stack Overflow but none of them is working.
manifest.xml
<receiver android:name=".ScreenReceiver">
<intent-filter>
<action android:name="android.intent.action.SCREEN_OFF"/>
<action android:name="android.intent.action.SCREEN_ON"/>
</intent-filter>
</receiver>
screenreceiver
public class ScreenReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON))
{
Intent intent = new Intent();
intent.setClass(context, ScreenLockActivity.class);
startActivity(intent);
}
}
}
To listen to screen on/off, your app should run by time and register Broadcast receiver to OS programmatically.
ScreenOnOffService.java
public class ScreenOnOffService extends Service {
public IBinder onBind(Intent intent) {
return null;
}
public void onCreate() {
super.onCreate();
Log.i("ScreenOnOffService", "onCreate: ");
IntentFilter intentFilter = new IntentFilter();
// intentFilter.addAction("android.intent.action.SCREEN_OFF");
intentFilter.addAction("android.intent.action.SCREEN_ON");
registerReceiver(ScreenOnReceiver.newInstance(), intentFilter);
}
public void onDestroy() {
super.onDestroy();
Log.i("ScreenOnOffService", "onDestroy: ");
unregisterReceiver(ScreenOnReceiver.newInstance());
// startService(new Intent(this,ScreenOnOffService.class));
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;
}
}
ScreenOnReceiver.java
public class ScreenOnReceiver extends BroadcastReceiver {
public static final String TAG = "ScreenOn";
public static volatile ScreenOnReceiver screenOn;
public static ScreenOnReceiver newInstance() {
if (screenOn == null) {
screenOn = new ScreenOnReceiver();
}
return screenOn;
}
#Override
public void onReceive(Context context, Intent intent) {
Log.i("hieuN", "intent: " + intent.getAction());
// do work. start activity.
}
}
Start service in activity
Intent service = new Intent(this, ScreenOnOffService.class);
startService(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
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
I am trying to create a service that will run on bootup, however when trying it in my emulator the log is not showing my message through log tag, so clearly something is wrong.
Here is my code.
service.java
public class service extends Service {
private static final String TAG = "myapp.mycomp";
public service() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "Service started");
Runnable r = new Runnable() {
#Override
public void run() {
/** something to do **/
}
};
Thread service = new Thread(r);
service.start();
return Service.START_STICKY;
}
#Override
public void onDestroy() {
Log.i(TAG, "Service stopped");
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
MyReceiver.java
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent myIntent = new Intent(context, service.class);
context.startService(myIntent);
}
}
XML manifest intent
<receiver android:name=".MyReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
XML manifest permission
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
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);
}
}
}