Android Bluetooth - detect a disconnection from a device - java

I am trying to catch a bluetooth device disconnection intent filter.
I added a log to the onReceive but it never reaches it and is not displayed in the logcat.
I suspect that the problem is with my manifest.xml configuration:
manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.company"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<receiver android:name="com.company.MyReceiver" android:enabled="true" android:exported="true">
<intent-filter>
<category android:name="android.intent.category.DEFAULT" />
<action android:name="android.bluetooth.device.action.ACL_DISCONNECT_REQUESTED" />
<action android:name="android.bluetooth.adapter.action.CONNECTION_STATE_CHANGED" />
<action android:name="android.bluetooth.adapter.action.DISCOVERY_STARTED" />
</intent-filter>
</receiver>
<activity
android:name=".BTActivity"
android:label="BTActivity" >
</activity>
</application>
</manifest>
MyReceiver extends BroadcastReceiver:
#Override
public void onReceive(Context context, Intent intent) {
Log.i("got-in", "got-in-");
// String action = intent.getAction();
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.i("disconnect", device.getName());
Intent i = new Intent(context, BTActivity.class);
Bundle b = new Bundle();
b.putString("deviceName", device.getName());
intent.putExtras(b); // Put your id to your next Intent
context.startActivity(i);
// finish();
}

Use this code for receiving a disconnect (when Bluetooth is still turned on):
<intent-filter> <action android:name="android.bluetooth.device.action.ACL_CONNECTED" />
<action android:name="android.bluetooth.device.action.ACL_DISCONNECT_REQUESTED" />
<action android:name="android.bluetooth.device.action.ACL_DISCONNECTED" />
</intent-filter>
Also you have to register a service that then registers a broadcast receiver for Bluetooth status change, so your app knows when Bluetooth was turned off and therefore discards all active devices, as you won't receive a ACL_DISCONNECT when Bluetooth is simply turned off.
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(bluetoothTurnedOnOff, filter);
return START_STICKY;
}
private final BroadcastReceiver bluetoothTurnedOnOff = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1) == BluetoothAdapter.STATE_OFF) {
[...]

For new users. it will works . Your manifest file looks
<receiver android:name="(package name).BluetoothReceiver" >
<intent-filter>
<action android:name="android.bluetooth.device.action.ACL_CONNECTED" />
<action android:name="android.bluetooth.device.action.ACL_DISCONNECTED" />
</intent-filter>
</receiver>
and your receiver will look like
else if (intent.getAction().equals(`enter code here`
BluetoothDevice.ACTION_ACL_DISCONNECTED)) {
// connection lost

Try removing the <category .../> from the intent-filter and try again.

Try android.bluetooth.device.action.ACL_DISCONNECTED action in intent filter. It should solve your problem.

Related

android broadcast receiver and service to get notification

hi i have used the following code in receiver class
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.e("the time is right","yay!");
Intent i = new Intent(context, AlarmServie.class);
context.startService(i);
}
}
here i the code which i used in service class
public class AlarmServie extends Service {
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.e("onStart:","came" );
/* NotificationManager notifyman = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Intent main_activity = new Intent(this.getApplicationContext(), MainActivity.class);
PendingIntent o = PendingIntent.getActivity(this, 0, main_activity, 0);
/*Notification noti = new Notification.Builder(this)
.setContentTitle("Reminder to Pill")
.setContentText("Click for info")
.setAutoCancel(true)
.setContentIntent(o)
.build();*/
NotificationManager nm = (NotificationManager) this.getApplicationContext().getSystemService(NOTIFICATION_SERVICE);
Intent in = new Intent(this.getApplicationContext(), MainActivity.class);
PendingIntent pending = PendingIntent.getactivity(this, 0, in, 0);
NotificationCompat.Builder mBuilder =new NotificationCompat.Builder(AlarmServie.this);
mBuilder.setContentTitle("Pill Reminder");
mBuilder.setContentText("CLick here to View");
//mBuilder.setSound(sound);
TaskStackBuilder ts=TaskStackBuilder.create(this);
ts.addParentStack(MainActivity.class);
nm.notify(9999,mBuilder.build());
}}
i created this code to get notification.when i run the app the receiver class is triggered but it is not moving to service class to invoke notification.can anyone say whats wrong in the code or say me how to get notification using broadcast receiver and service in a detailed tutorial
here is the manifest file and say me where to put the code exactly
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".AlarmReceiver"></receiver>
<activity android:name=".Set"></activity><!-- ATTENTION: This was auto-generated to add Google Play services to your project for
App Indexing. See https://g.co/AppIndexing/AndroidStudio for more information. -->
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</application>
</manifest>
please explain in detail what the problem in code.please tell exactly where to put the service tag
You must declare service in manifest also.
Intent to start service is sent to system then system tries to find right application component to handle this particular intent using information passed in manifest files.
It should be enough, but I'm not sure if you put service in the default package.
<application>
....
<service android:name=".AlarmServie"/>
....
</application>
Your Manifest should look something like this
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
//here is your service
<service android:name=".AlarmServie" android:enabled="true"/>
<receiver android:name=".AlarmReceiver"></receiver>
<activity android:name=".Set"></activity><!-- ATTENTION: This was auto-generated to add Google Play services to your project for
App Indexing. See https://g.co/AppIndexing/AndroidStudio for more information. -->
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</application>

GCM Broadcast Receiver not triggering

I have looked at several questions on this site and none seem to be able to answer my question so hopefully someone can help with this. Currently for some reason when I send a message through from the PHP Website, my app doesn't receive the message. I have tried placing Log.d's in the lines of code but it doesn't appear as well. Can someone help to see if something has gone wrong?
[UPDATE] This is the result when I send from the php website
{"multicast_id":5610818169388245295,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1460536959734990%40ad5721f9fd7ecd"}]}
My manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.amosang.pushtest" >
<!-- GCM Permissions - Start here -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<permission
android:name="com.example.amosang.pushtest.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.amosang.pushtest.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".HomeActivity"
android:label="#string/title_activity_home" >
</activity>
</application>
<receiver
android:name=".GCMBroadcastReceiver"
android:enabled="true"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.example.amosang.pushtest" />
</intent-filter>
</receiver>
<service android:name=".GCMNotificationIntentService">
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</service>
</manifest>
My Broadcast Receiver
public class GCMBroadcastReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ComponentName comp = new ComponentName(context.getPackageName(), GCMNotificationIntentService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
Log.d("TESTTEST", "TEST");
setResultCode(Activity.RESULT_OK);
}
}
My intent service
public class GCMNotificationIntentService extends IntentService{
//set ID for the notification, so it can be updated
public static final int notifyID = 9001;
NotificationCompat.Builder builder;
public GCMNotificationIntentService() {
super("GCM Intent Service");
}
#Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
Log.d("RECEIVEDMESSAGE", messageType);
if (!extras.isEmpty()) {
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR
.equals(messageType)) {
sendNotification("Send error: " + extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED
.equals(messageType)) {
sendNotification("Deleted messages on server: "
+ extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE
.equals(messageType)) {
sendNotification("Message Received from Google GCM Server:nn"
+ extras.get(AppConstants.MSG_KEY));
}
}
GCMBroadcastReceiver.completeWakefulIntent(intent);
}
private void sendNotification(String msg){
Intent resultIntent = new Intent(this, HomeActivity.class);
Log.d("RECEIVEDPT2",msg);
resultIntent.putExtra("msg", msg);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this,0,resultIntent,PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder mNotifyBuilder;
NotificationManager mNotificationManager;
mNotificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
mNotifyBuilder = new NotificationCompat.Builder(this).setContentTitle("Alert")
.setContentTitle("You've received a new message");
//Set pending intent
mNotifyBuilder.setContentIntent(resultPendingIntent);
//Set vibration
int defaults = 0;
defaults = defaults | Notification.DEFAULT_LIGHTS;
defaults = defaults | Notification.DEFAULT_VIBRATE;
defaults = defaults | Notification.DEFAULT_SOUND;
mNotifyBuilder.setDefaults(defaults);
// Set the content for Notification
mNotifyBuilder.setContentText("You have new notifications");
// Set autocancel
mNotifyBuilder.setAutoCancel(true);
// Post a notification
mNotificationManager.notify(notifyID, mNotifyBuilder.build());
}
}
Please help.

Android - check for loss of Bluetooth connection?

I am writing an app that connects to an Arduino bluetooth device. The goal is for the Android user to receive a push notification if the phone leaves the range of the Arduino. This should occur regardless of whether the app is in the foreground or not. To do this, I am currently using a BroadcastReceiver in the Android Manifest. However, I am not receiving any such notifications.
Here is the Receiver class that implements BroadcastReceiver:
public class Receiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED)) {
if (adapter.getState() == BluetoothAdapter.STATE_OFF) {
pushNotification(context);
}
}
}
public void pushNotification(Context context) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setAutoCancel(true);
builder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher));
builder.setContentTitle("This is a notification!");
builder.setContentText("This is the notification text!");
builder.setSubText("This is the notification subtext!");
NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
notificationManager.notify(1, builder.build());
}
}
And the AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".Receiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.bluetooth.adapter.action.STATE_CHANGED" />
</intent-filter>
</receiver>
</application>
</manifest>
I'm fairly certain that the problem lies in the constants I am using in my logic. However, I'm not sure which ones I should use. As it is, the receiver is activated when ANY state change occurs to the Android Bluetooth, but I only want a notification when the connection is lost, which might not have anything to do with a state change of the Android Bluetooth receiver.
What should I do to make sure pushNotification() is called under these conditions?
You have register wrong intent.
<action android:name="android.bluetooth.adapter.action.STATE_CHANGED" />
This intent only indicate wheather the bluetooth is on and off.If you want to receive bluetooth devices connect state , you should use follow actions:
<action android:name="android.bluetooth.device.action.ACL_DISCONNECTED" />
<action android:name="android.bluetooth.device.action.ACL_CONNECTED" />
In you onRecive method:
if(TextUtils.equals(action,BluetoothDevice.ACTION_ACL_DISCONNECTED)) {
BluetoothDevice device = intent.getExtras()
.getParcelable(BluetoothDevice.EXTRA_DEVICE);
if (isYourDevice(device)) {
// to push your notification
}
}

How to create an android app that is set to default when the device is turned on

I want to create an application in android , which after installation I need to set as default when ever the device is turned on .
I have tried the following
created a service ,
created a reciever to recieve boot completion event
It is not working actually.If I remove the launcher for MainActivity the it will show error saying
No Launcher activity found!
The launch will only sync the application package on the device!
my manifest file
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:screenOrientation="sensorLandscape" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".MyService"
android:label="My Service" >
<intent-filter>
<action android:name="com.example.splash_test.MyService" />
</intent-filter>
</service>
<receiver
android:name=".receiver.MyReceiver"
android:label="MyReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<activity
android:name="com.example.splash_test.Screen1"
android:label="#string/app_name"
android:screenOrientation="sensorLandscape" >
</activity>
</application>
MyReceiver.java
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
Intent serviceIntent = new Intent(context, MyService.class);
context.startService(serviceIntent);
}
}
}
MyService.java
public class MyService extends Service {
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
Intent i = new Intent(this, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.startActivity(i);
}
return null;
}
}
You have to follow below steps for achieve this task:-
Make a service in your app(Run all time).
check your app is running or not in service.(Through package name)
if running then good other wise run with the help of service.
Try it.... its working fine in my app. :)

Android - Start service on boot

From everything I've seen on Stack Exchange and elsewhere, I have everything set up correctly to start an IntentService when Android OS boots. Unfortunately it is not starting on boot, and I'm not getting any errors. Maybe the experts can help...
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.phx.batterylogger"
android:versionCode="1"
android:versionName="1.0"
android:installLocation="internalOnly">
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.BATTERY_STATS" />
<application android:icon="#drawable/icon" android:label="#string/app_name">
<service android:name=".BatteryLogger"/>
<receiver android:name=".StartupIntentReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>
BroadcastReceiver for Startup:
package com.phx.batterylogger;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class StartupIntentReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent serviceIntent = new Intent(context, BatteryLogger.class);
context.startService(serviceIntent);
}
}
UPDATE: I tried just about all of the suggestions below, and I added logging such as Log.v("BatteryLogger", "Got to onReceive, about to start service"); to the onReceive handler of the StartupIntentReceiver, and nothing is ever logged. So it isn't even making it to the BroadcastReceiver.
I think I'm deploying the APK and testing correctly, just running Debug in Eclipse and the console says it successfully installs it to my Xoom tablet at \BatteryLogger\bin\BatteryLogger.apk. Then to test, I reboot the tablet and then look at the logs in DDMS and check the Running Services in the OS settings. Does this all sound correct, or am I missing something? Again, any help is much appreciated.
Well here is a complete example of an AutoStart Application
AndroidManifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="pack.saltriver" android:versionCode="1" android:versionName="1.0">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application android:icon="#drawable/icon" android:label="#string/app_name">
<receiver android:name=".autostart">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<activity android:name=".hello"></activity>
<service android:enabled="true" android:name=".service" />
</application>
</manifest>
autostart.java
public class autostart extends BroadcastReceiver
{
public void onReceive(Context context, Intent arg1)
{
Intent intent = new Intent(context,service.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intent);
} else {
context.startService(intent);
}
Log.i("Autostart", "started");
}
}
service.java
public class service 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");
}
#Override
public void onStart(Intent intent, int startid)
{
Intent intents = new Intent(getBaseContext(),hello.class);
intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intents);
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
}
}
hello.java - This will pop-up everytime you start the device after executing the Applicaton once.
public class hello extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Toast.makeText(getBaseContext(), "Hello........", Toast.LENGTH_LONG).show();
}
}
Following should work. I have verified. May be your problem is somewhere else.
Receiver:
public class MyReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_BOOT_COMPLETED.equals(arg1.getAction())) {
Log.d("TAG", "MyReceiver");
Intent serviceIntent = new Intent(context, Test1Service.class);
context.startService(serviceIntent);
}
}
}
Service:
public class Test1Service extends Service {
/** Called when the activity is first created. */
#Override
public void onCreate() {
super.onCreate();
Log.d("TAG", "Service created.");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("TAG", "Service started.");
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.d("TAG", "Service started.");
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test"
android:versionCode="1"
android:versionName="1.0"
android:installLocation="internalOnly">
<uses-sdk android:minSdkVersion="8" />
<application android:icon="#drawable/icon" android:label="#string/app_name">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.BATTERY_STATS"
/>
<!-- <activity android:name=".MyActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"></category>
</intent-filter>
</activity> -->
<service android:name=".Test1Service"
android:label="#string/app_name"
>
</service>
<receiver android:name=".MyReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>
Your Service may be getting shut down before it completes due to the device going to sleep after booting. You need to obtain a wake lock first. Luckily, the Support library gives us a class to do this:
public class SimpleWakefulReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// This is the Intent to deliver to our service.
Intent service = new Intent(context, SimpleWakefulService.class);
// Start the service, keeping the device awake while it is launching.
Log.i("SimpleWakefulReceiver", "Starting service # " + SystemClock.elapsedRealtime());
startWakefulService(context, service);
}
}
then, in your Service, make sure to release the wake lock:
#Override
protected void onHandleIntent(Intent intent) {
// At this point SimpleWakefulReceiver is still holding a wake lock
// for us. We can do whatever we need to here and then tell it that
// it can release the wakelock.
...
Log.i("SimpleWakefulReceiver", "Completed service # " + SystemClock.elapsedRealtime());
SimpleWakefulReceiver.completeWakefulIntent(intent);
}
Don't forget to add the WAKE_LOCK permission:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
I have found a way to make your application run well when the device reboots, please follow the steps below to be successful.
AndroidManifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="pack.saltriver" android:versionCode="1" android:versionName="1.0">
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".UIBootReceiver" 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>
<service android:name=".class_Service" />
</application>
</manifest>
UIBootReceiver
public class UIBootReceiver extends BroadcastReceiver {
private static final String TAG = "UIBootReceiver";
#Override
public void onReceive(Context context, Intent arg1)
{
Toast.makeText(context, "started", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context,class_Service.class);
context.startService(intent);
}
}
This is asking permission to not need to manage battery saving for this app so you can run in the background stably.
Declare this code in onCreate () of MainActivity class:
Intent myIntent = new Intent();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
myIntent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
myIntent.setData(Uri.parse("package:" +
DeviceMovingSpeed.this.getPackageName()));
}
startActivity(myIntent);
Looks very similar to mine but I use the full package name for the receiver:
<receiver android:name=".StartupIntentReceiver">
I have:
<receiver android:name="com.your.package.AutoStart">
I've had success without the full package, do you know where the call chain is getting interrupted? If you debug with Log()'s, at what point does it no longer work?
I think it may be in your IntentService, this all looks fine.
Just to make searching easier, as mentioned in comments, this is not possible since 3.1
https://stackoverflow.com/a/19856367/6505257

Categories

Resources