Start intent after Reboot - android

I have a GPS Service that gets GPS position every 60 seconds. It's working okay, but it doesn't do anything after phone reboot. I tried adding this in a BroadcastReceiver that is working after reboot but nothing happens. Any help would be great; I just need to load my Intents after reboot.
//Start intents after reboot
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
context.startService(new Intent(context, DashboardActivity.class));
}
GPSActivity.java
public int onStartCommand(Intent intent, int flags, int startId) {
//Toast.makeText(getBaseContext(), "Service Started", Toast.LENGTH_SHORT).show();
final Runnable r = new Runnable() {
public void run() {
Log.v("GPS_TRACKER", "Run Start");
location();
handler.postDelayed(this, 60000);
}
};
handler.postDelayed(r, 60000);
return START_STICKY;
}
Manifest
<!-- GPS Activity -->
<service android:enabled="true" android:name=".GPSActivity">
<intent-filter>
<action android:name="com.ni.androidtrack.GPSActivity"/>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</service>
<!-- Also permission for RECEIVE_BOOT_COMPLETED -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

In your manifest:
<service android:exported="false" android:name=".service.YourService" android:enabled="true"></service>
<receiver android:name=".service.YourBootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
Also add permission in manifest:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
YourBootReceiver:
public class YourBootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
Intent serviceIntent = new Intent(arg0, YourService.class);
arg0.startService(serviceIntent);
}

You have to add RECEIVE_BOOT_COMPLETED permission in your manifest file to get notified :
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
context.startService(new Intent(context, GPSActivity.class));
}

Related

Service doesn't start after device reboot

I want to start my service after reboot device if the service was working before reboot. I handled boot completed intent but my application is terminated when i want to start service again.
My BroadcastReceiver:
public class BootCompletedIntentReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
Intent serviceIntent = new Intent(context.getApplicationContext(), LocationService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
context.getApplicationContext().startForegroundService(serviceIntent);
}
else
{
context.getApplicationContext().startService(serviceIntent);
}
}
}
Part of LocationService:
#Override
public void onCreate()
{
...
startForeground(NotificationCreator.getNotificationId(), NotificationCreator.getNotification(this));
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
...
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
}
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
Toasty.warning(this, "Turn on GPS", Toast.LENGTH_SHORT).show();
isPause = true;
}
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 10, this);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10, this);
return Service.START_NOT_STICKY;
}
Part of class where i start service:
Intent serviceIntent = new Intent(getContext(), LocationService.class);
serviceIntent.putExtra(IntentExtras.COURSE, Parcels.wrap(course));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
getActivity().startForegroundService(serviceIntent);
}
else
{
getActivity().startService(serviceIntent);
}
Manifest:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-feature android:name="android.hardware.location1.gps" />
<application>
<service android:name=".services.LocationService" />
<receiver android:name=".BootCompletedIntentReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
I start application and start service, when service is working I restart device. After reboot onReceive method is called in BroadcastReceiver. I can handle break point in first line in this method but the code is stop being executing after call start service. I tried to stop service before start them in this method but id dost'n change anything. I also tried to start service after launch application after reboot without broadcast receiver but it also doesn't help.
add this on your manifest:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver android:name="BootCompletedIntentReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.HOME" />
</intent-filter>
</receiver>
Oh, I think I have an idea why
You can't run this code inside a Service. It has to be run in an Activity.
if (
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED
){
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
Toasty.warning(this, "Turn on GPS", Toast.LENGTH_SHORT).show();
isPause = true;
}
}
First, you need the permission in your AndroidManifest.xml:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Also, in yourAndroidManifest.xml, define your service and listen for the BOOT_COMPLETED action:
<service android:name=".MyService" android:label="My Service">
<intent-filter>
<action android:name="com.myapp.MyService" />
</intent-filter>
</service>
<receiver
android:name=".receiver.StartMyServiceAtBootReceiver"
android:label="StartMyServiceAtBootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
Then you need to define the receiver that will get the BOOT_COMPLETED action and start your service.
public class StartMyServiceAtBootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
Intent serviceIntent = new Intent(context, MyService.class);
context.startService(serviceIntent);
}
}
}
And now your service should be running when the phone starts up.

BroadcastReceiver doesn't work accurately unless registered Manually

To put it simply; BroadcastReceiver Works when defined in Manifest but it works with a short Delay and it doesn't Always trigger unless Registered Manually.
Here is the BroadcastReceiver I created to capture event when date changes (day is passed):
public class BootBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, intent.getAction(), Toast.LENGTH_LONG).show();
switch (intent.getAction()){
case Intent.ACTION_TIME_TICK:
case Intent.ACTION_TIME_CHANGED:
case Intent.ACTION_TIMEZONE_CHANGED:
case Intent.ACTION_DATE_CHANGED:
case Intent.ACTION_BOOT_COMPLETED:
Log.d("BroadcastReceiver", intent.getAction().toString());
}
}
}
Here registered in Manifest, It works but has a short delay and also doesn't always trigger:
<receiver android:name=".Receivers.BootBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.TIME_TICK" />
<action android:name="android.intent.action.TIME_SET" />
<action android:name="android.intent.action.TIMEZONE_CHANGED" />
<action android:name="android.intent.action.DATE_CHANGED"/>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
But when registered manually via my background service it works just fine:
public class ApplicationService extends Service{
...
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_DATE_CHANGED);
intentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
intentFilter.addAction(Intent.ACTION_TIME_CHANGED);
intentFilter.addAction(Intent.ACTION_TIME_TICK);
registerReceiver(new BootBroadcastReceiver(), intentFilter);
return START_STICKY;
}
}
To investigate this issue further I created two similar app which in one BroadcastReceiver registered in Manifest and in the other one receiver is registered Manually via Service.
In the Manifest one all events are triggered few second after Manual one..
Try this :
<receiver android:name=".Receivers.BootBroadcastReceiver">
<intent-filter
android:enabled="true"
android:exported="true">
<action android:name="android.intent.action.TIME_TICK" />
<action android:name="android.intent.action.TIME_SET" />
<action android:name="android.intent.action.TIMEZONE_CHANGED" />
<action android:name="android.intent.action.DATE_CHANGED"/>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
I guess you can have multiple each one having its action.
https://developer.android.com/guide/components/intents-filters.html
The documentation says that "An app component should declare separate filters for each unique job it can do." This would allow finer grained detail for different actions
The answer was hidden in Intent documentation:
ACTION_TIME_TICK Added in API level 1
public static final String ACTION_TIME_TICK
Broadcast Action: The current time has changed. Sent every minute. You
cannot receive this through components declared in manifests, only by
explicitly registering for it with
Context#registerReceiver(BroadcastReceiver, IntentFilter).
To simply put, you can't receive TIME_TICK through registering the BroadcastReceiver in manifest, it has to be registered in your application components (Service, Activity, etc.)
Define a BootBroadcastReceiver anywhere in Activity/Fragment like this:
mBootBroadcastReceiver = new BootBroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG," BootBroadcastReceiver"); //do something with intent
}
};
mIntentFilter=new IntentFilter("action_name");
Now register the BootBroadcastReceiver in onResume() and Unregister in onPause()
#Override
protected void onResume() {
super.onResume();
registerReceiver(mBootBroadcastReceiver, mIntentFilter);
}
#Override
protected void onPause() {
if(mReceiver != null) {
unregisterReceiver(mBootBroadcastReceiver);
mBootBroadcastReceiver = null;
}
super.onPause();
}
add permission in your Manifest.
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="ANDROID.PERMISSION.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />

Getting Android apk to run after installing (reboot)?

Hello I'm trying to get my Android application (it has no UI, its just supposed to be a background service) to run when it's installed or at least when the device is rebooted. Here's my work so far, anyone have any ideas why it won't start when install the apk and reboot the device?
Android Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="gitlab.project" >
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application android:label="#string/app_name" >
<activity
android:name="gitlab.project.MainActivity"
android:label="#string/app_name"
android:theme = "#android:style/Theme.NoDisplay">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</activity>
<receiver
android:name="gitlab.project.AutoStart"
android:enabled="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
<service android:name="gitlab.project.AlphaService"
android:enabled="true"
android:exported="true" />
</application>
</manifest>
MainActivity:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent(this, AlphaService.class);
this.startService(intent);
}
}
AlphaService:
public class AlphaService extends Service implements
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private Profiler profiler;
private AlphaApiClient alphaApiClient;
private GoogleApiClient googleApiClient;
private int batteryHealth;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(final Intent intent, int flags, int startId) {
batteryHealth = intent.getIntExtra(BatteryManager.EXTRA_HEALTH, 2);
if (googleApiClient == null) {
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
googleApiClient.connect();
return Service.START_STICKY;
}
#Override
public void onConnected(Bundle connectionHint) {
ProcService procService = new DefaultProcService();
SystemInformationService systemInformationService = new SystemInformationService(googleApiClient, getContentResolver());
profiler = new Profiler(procService, systemInformationService);
alphaApiClient = new AlphaApiClient(getString(R.string.USERNAME), getString(R.string.PASSWORD));
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
Log.d("Alpha service", "Profiling system info...");
AndroidSystem androidSystem = profiler.profile(batteryHealth);
String url = getString(R.string.API_URL);
alphaApiClient.doPostRequest(androidSystem, url);
}
});
thread.start();
//Stop service once it finishes its task
stopSelf();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onDestroy() {
AlarmManager alarm = (AlarmManager)getSystemService(ALARM_SERVICE);
alarm.set(
AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + (4000 * 60 * 60),
PendingIntent.getService(this, 0, new Intent(this, AlphaService.class), 0)
);
}
}
AutoStart (Broadcast Receiver):
public class AutoStart extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
context.startService(new Intent(context, AlphaService.class));
}
}
Any ideas why my background service won't run? I'm able to get it to run using adb, but not when trying to install manually from the phone/tablet. Any help is greatly appreciated.
The app won't run any services or broadcast receivers unless it's in started state. It's in started state after it's been run from launcher or via ADB.
1) Make an activity which will a) start your service and b) disable itself (How to enable and disable a component?).
2) Make an on boot receiver (Android BroadcastReceiver on startup - keep running when Activity is in Background).
Your on boot receiver is already starting the service, it does not need to start the activity. The activity only needs to be launched once after install. Here's the correct setup.
AndroidManifest.xml
<activity
android:name="gitlab.project.MainActivity"
android:theme = "#android:style/Theme.NoDisplay">
<intent-filter>
<!-- Activity needs to show up in launcher. -->
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name="gitlab.project.AutoStart"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
AutoStart.java
public class AutoStart extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction()) {
context.startService(new Intent(context, AlphaService.class));
}
}
}
I think the problem is in your AutoStart class:
Intent i = new Intent(context, MainActivity.class);
Your packaging the intent with your MainActivity. Try changing it to AlphaService.

how can I autostart my app in android after reboot?

I have used BootComplete and allow permission and it still cant autostart,then I try to use wake lock but it cannot work. Also, I try to make it as a service but the service does not pop up in my phone.Is there anything I missed?
public class BootComplete extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
{
// This is the Intent to deliver to our service.
Intent serviceIntent = new Intent(context, AutoStartUp.class);
context.startService(serviceIntent);
}
}
public class AutoStartUp extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
// do something when the service is created
}
}
In my manifest file:
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<service android:name=".SimpleWakefulReceiver">
<intent-filter>
<action android:name="com.example.SimpleWakefulReceiver"/>
</intent-filter>
</service>
<receiver
android:name=".MainActivity$BootComplete"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:name=".AutoStartUp">
</service>
Do whatever you intend in onReceive -
public class BootupReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.e("BOOTUP", "received notification ......................");
if(intent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED))
{
Log.e("BOOTUP","RECEIVED BOOT NOTIFICATION ........");
Intent start_service = new Intent(context,MainService.class);
context.startService(start_service);
}
}
in the Manifest add-
<receiver
android:name=".AutoStart"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
add permission-
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Also you need to launch your application from activity atleast once and your block should be outside block in manifest

How to Auto-start an Android Application?

I'm not sure how to autostart an android application after the android emulator completes its booting. Does anyone have any code snippets that will help me?
You have to add a manifest permission entry:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
(of course you should list all other permissions that your app uses).
Then, implement BroadcastReceiver class, it should be simple and fast executable. The best approach is to set an alarm in this receiver to wake up your service (if it's not necessary to keep it running ale the time as Prahast wrote).
public class BootUpReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent pi = PendingIntent.getService(context, 0, new Intent(context, MyService.class), PendingIntent.FLAG_UPDATE_CURRENT);
am.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + interval, interval, pi);
}
}
Then, add a Receiver class to your manifest file:
<receiver android:enabled="true" android:name=".receivers.BootUpReceiver"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
Edit your AndroidManifest.xml to add RECEIVE_BOOT_COMPLETED permission
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Edit your AndroidManifest.xml application-part for below Permission
<receiver android:enabled="true" android:name=".BootUpReceiver"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
Now write below in Activity.
public class BootUpReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, MyActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
If by autostart you mean auto start on phone bootup then you should register a BroadcastReceiver for the BOOT_COMPLETED Intent. Android systems broadcasts that intent once boot is completed.
Once you receive that intent you can launch a Service that can do whatever you want to do.
Keep note though that having a Service running all the time on the phone is generally a bad idea as it eats up system resources even when it is idle. You should launch your Service / application only when needed and then stop it when not required.
I always get in here, for this topic. I'll put my code in here so i (or other) can use it next time. (Phew hate to search into my repository code).
Add the permission:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Add receiver and service:
<receiver android:enabled="true" android:name=".BootUpReceiver"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
<service android:name="Launcher" />
Create class Launcher:
public class Launcher extends Service {
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
new AsyncTask<Service, Void, Service>() {
#Override
protected Service doInBackground(Service... params) {
Service service = params[0];
PackageManager pm = service.getPackageManager();
try {
Intent target = pm.getLaunchIntentForPackage("your.package.id");
if (target != null) {
service.startActivity(target);
synchronized (this) {
wait(3000);
}
} else {
throw new ActivityNotFoundException();
}
} catch (ActivityNotFoundException | InterruptedException ignored) {
}
return service;
}
#Override
protected void onPostExecute(Service service) {
service.stopSelf();
}
}.execute(this);
return START_STICKY;
}
}
Create class BootUpReceiver to do action after android reboot.
For example launch MainActivity:
public class BootUpReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
Intent target = new Intent(context, MainActivity.class);
target.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(target);
}
}

Categories

Resources