I'm trying to create a service which starts when I plug the battery charger and stop when unplug it. The problem is when I unplug the charger my service don't stop while when I plug it's all fine.
Here is my code:
public class PowerConnectionReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_POWER_CONNECTED)){
Intent i = new Intent(context,MyService.class);
context.startService(i);
}
if (intent.getAction().equals(Intent.ACTION_POWER_DISCONNECTED)){
Intent j = new Intent(context,MyService.class);
context.stopService(j);
}
}
}
Here is my Manifest:
<receiver android:name=".PowerConnectionReceiver">
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
</intent-filter>
</receiver>
Related
I want my service to be started when android is rebooted. I used BroadcastReceiver to do so.
public class autostart extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
MyService1 mYourService = new MyService1();
MainActivity.instance_main.showToast("BroadCast Received...................");
Intent mServiceIntent = new Intent(MainActivity.instance_main, mYourService.getClass());
if (!MainActivity.instance_main.isMyServiceRunning(mYourService.getClass())) {
MainActivity.instance_main.startService(mServiceIntent);
MainActivity.instance_main.showToast("Restarted...................");
}
else {
MainActivity.instance_main.showToast("already running..................");
}
}
}
Receiver in Android Manifest
<receiver android:name=".autostart" android:enabled="true" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</receiver>
Permissions defined
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>
Battery optimization ignore permission also requested in OnCreate()
Intent intent=new Intent();
intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:"+MainActivity.instance_main.getPackageName()));
MainActivity.instance_main.startActivity(intent);
But it won't work. Service won't start on reboot. Kindly Suggest me solution.
WE need to register the receiver. Add the following code to OnCreate()
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mService=new Autostart();
registerReceiver(mService,filter);
However after reboot it wont automatically hit.
I registered a BroadcastReceiver in my FragmentActivity like so:
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
setMapLocations(intent);
}
};
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
setMapLocations(intent);
}
};
and start the receiver is onStart():
public void onStart() {
super.onStart();
LocalBroadcastManager.getInstance(this).registerReceiver((mMessageReceiver),
new IntentFilter("MyNotificationData"));
}
and my broadcast sender is defined in the manifest as follows:
<service
android:name=".TrackerMessagingService"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>
The problem is that onReceive() never gets hit, even though the exact same code worked fine in an AppCompatActivity in the same app. Any idea what's going on? Do broadcast services not play well with FragmentActivity?
I don't know why this worked, but I was able to get around the issue by leaving the BroadcastReceiver code in the AppCompatActivity. In that case, both BroadcastReceivers got hit.
I've some problem with Oreo and Broadcast Receiver on Boot. My method work for earlier version of Android, but with Oreo (Huawei P20 Lite with Pie) it doesn't work.
The Log.e in the Boot Receiver is not displayed in the LogCat and the action in BootService onCreate is not executed (No Log in log cat).
Boot Receiver
public class BootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.e(TAG, "Boot Receiver : Boot Start Service : AlarmNotification");
if ( Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction()) ) {
Intent myIntent = new Intent(context, BootService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(myIntent);
} else {
context.startService(myIntent);
}
}
}
}
I've set the permissions in the Manifest file
AndroidManifest.xml
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver android:name=".BootReceiver"
android:enabled="true"
android:exported="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<category android:name="android.intent.category.DEFAULT" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.ACTION_BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<action android:name="com.htc.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
<service
android:name=".BootService"
android:enabled="true"
android:exported="true">
</service>
BootService
The Boot Service works on earlier versions of Android
public class BootService extends Service {
public BootService() {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
//Is fired by the Boot Receiver... on Boot !
Context context = this;
Log.e(TAG, "Start Alarm");
//Do something with the code
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_NOT_STICKY;
}
}
Perhaps I forget something, or do I something wrong ? Can somebody help me on this case, I already tested multiple solutions from StackeOverflow and read the doc, but for me it's not very clear for this case.
Thanks
I needed to restore alarm after reboot for this I added this broadcast receiver:
public class ClsRestartAlarm extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Logging.logMessage("Broadcast");
Intent i = new Intent(context, BootService.class);
context.startService(i);
}
}
}
and registered in manifest like this:
<receiver android:name=".classes.ClsRestartAlarm"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
and as result of broadcast I'm doing this:
public class BootService extends IntentService {
public BootService() {
super("boot service");
}
#Override
protected void onHandleIntent(Intent intent) {
AlarmManagerUtils.setStartAlarm();
AlarmManagerUtils.setEndAlarm();
}
}
I guess I'm not receiving BOOT_COMPLETE broadcast in ClsRestartAlarm class, because after restart alarm was not set and I was unable to get notification(the starting alarm start a job scheduler for sending notification and end alarm cancels job scheduler)also I have BOOT_COMPLETE permission like this:
<uses-permission android:name="ANDROID.PERMISSION.RECEIVE_BOOT_COMPLETED"/>
Use WakefulBroadcastReceiver instead. This is my workable solution:
public class BRAutoStart extends WakefulBroadcastReceiver {
private final String BOOT_COMPLETED_ACTION = "android.intent.action.BOOT_COMPLETED";
#Override
public void onReceive(Context ctx, Intent intent) {
_A.APPCTX = ctx.getApplicationContext();
if(intent.getAction().equals(BOOT_COMPLETED_ACTION)){
//code
}
}
}
<receiver android:name=".BRAutoStart">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
I have running service (previously successfuly binded, started and unbinded with main activity):
Intent startingIntent = new Intent(this, SturkoPlayerService.class);
startingIntent.setAction(SturkoPlayerService.PLAYER_START);
bindService(startingIntent, connection, Context.BIND_AUTO_CREATE);
When I successfuly close mainactivity (service is unbinded and keeps running) and want to reopen mainactivity with notification intent:
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("Service", 1);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); //tried also another flags
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
and then try to bind my running service
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
if (getIntent() != null && getIntent().hasExtra("Service")) {
if (!bound) {
bindService(new Intent(this, SturkoPlayerService.class), connection, 0);
}
}
}
the onServiceConnected function of my Connection variable is not called
private ServiceConnection connection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
SturkoPlayerService.LocalBinder mBinder = (SturkoPlayerService.LocalBinder) service;
sturkoService = mBinder.getService();
bound = true;
sturkoService.registerClient(MainActivity.this);
}
#Override
public void onServiceDisconnected(ComponentName name) {
bound = false;
}
};
Manifest:
...
<activity android:name=".MainActivity"
android:screenOrientation="portrait"
android:launchMode="singleTask"> //tried other modes too
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".Service.SturkoPlayerService"
android:enabled="true"
android:exported="true"
android:singleUser="true">
</service>
...
P.S.: Catlog did not show somthing
A service will only be running if:
There are 1+ clients bound to it, or
You called startService() on it and nothing has stopped it (e.g., stopSelf(), stopService())
Otherwise, once the last bound connection is unbound, the service stops.