I want to activate a service from my broadcastReceiver, this is my code but it didn't work:
public class PackageChangeReceiver extends BroadcastReceiver {
Context context;
Deletecontact delete= new Deletecontact();
#Override
public void onReceive(Context ctx, Intent intent) {
Uri uri = intent.getData();
String pkg = uri != null ? uri.getSchemeSpecificPart() : null;
if(intent.getAction().equals("android.intent.action.PACKAGE_REMOVED")&& pkg.equals("com.alarm"))
{Log.i("action","the package is removed");
Intent service = new Intent( context, Deletecontact.class);
context.startService(service);
}}}
and this is the service
public void onCreate()
{
//deletecontact();
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
return START_STICKY;
//return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy()
{
super.onDestroy();
}
#Override
public IBinder onBind(Intent arg0) {
return mBinder;
}
public class MyBinder extends Binder {
Deletecontact getService() {
return Deletecontact.this;
}
}
I just want to call the service when the action of the broadcast is set
#Emna when i see you code for start service you have used this code to start service.
context.startService(service);
In this code context this not assign like below
So before you call startService
context=ctx;
Add above code after onReceive.
And Make sure that you have define Deletecontact.class this class as Service Tag in AndroidManifest.xml For Example Below :
<service android:enabled="true" android:name="xxx.yyy.zzz.Deletecontact"
></service>
Hope this will work .
try this,use ctx instead of context for starting service and preparing Intent:
public class PackageChangeReceiver extends BroadcastReceiver {
Context context;
Deletecontact delete= new Deletecontact();
#Override
public void onReceive(Context ctx, Intent intent) {
Uri uri = intent.getData();
String pkg = uri != null ? uri.getSchemeSpecificPart() : null;
if(intent.getAction().equals("android.intent.action.PACKAGE_REMOVED")&& pkg.equals("com.alarm"))
{Log.i("action","the package is removed");
Intent service = new Intent(ctx, Deletecontact.class);
ctx.startService(service);
}}}
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);
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.
I'm not sure if my current approach is the proper way to use a Service: I would like to listen to a LocalBroadcastManager in the background (no Activity involved) and query some WebServices upon receiving an Intent. Could you please have a look at my code below and tell me if this is "good" or "bad" in regards of a robust code design? Of course I'd like to reduce the device resource utilisation to a minimum.
Originally, I had an IntentService in my mind but I didn't figure out how to start it from a BroadcastReceiver (you can't register a BroadcastReceiver in the manifest if it just listens to LocalBroadcasts).
public class WebRequestService extends Service {
#Override
public void onCreate() {
BroadcastReceiver mLocalMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
new getCurrentValues().execute();
}
};
IntentFilter messageFilter = new IntentFilter(Intent.ACTION_SEND);
LocalBroadcastManager.getInstance(this).registerReceiver(mLocalMessageReceiver, messageFilter);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Override
public void onDestroy() {}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
private class getCurrentValues extends AsyncTask<Void, Void, ResultDTO> {
#Override
protected ResultDTO doInBackground(Void... params) {
// do some magic
return resultDTO;
}
protected void onPostExecute(ResultDTO result) {
if (result != null) {
Intent messageIntent = new Intent();
messageIntent.setAction("currentValuesUpdated");
messageIntent.putExtra("result", result);
LocalBroadcastManager.getInstance(this).sendBroadcast(messageIntent);
}
}
} }
Thank you very much
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);
}
}
}
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