starting background service while phone turn on with example code - android

I need an app which will run always in the background and apps will start while phone is turn on. Please help me with example code.
I already tried several code but it run on background while pressing button after start the apps

You need to receive BOOT_COMPLETED of the phone, then start the service.
Follow the following steps
Step 1: create your service
public class myService extends Service{
public myService(){}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
}
Step 2: Create your boot receiver
public class BootReceiver extends BroadcastReceiver {
public void onReceive(final Context context, Intent intent) {
Intent i = new Intent(context, RemindersService.class);
context.startService(i);
}
}
Step 3: add them to manifest inside application
<service
android:name=".services.RemindersService"
android:enabled="true"
android:exported="true" />
<receiver
android:name=".services.BootReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
Step 4: add permission in manifest
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Thats it. Happy coding.
Please note that in android Oreo, you will want to start service as foreground
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(i);
}

Related

How to make a screen not fall asleep if the app runs on boot?

I have the app which must start on device' boot. It works well but the problem is that when the app finishes booting, the screen is already dark. How can I make it not fall asleep?
My Receiver:
<receiver
android:enabled="true"
android:exported="true"
android:name=".view.receivers.BootReceiver"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
public class BootReceiver extends BroadcastReceiver {
private final static String LOG_TAG = BootReceiver.class.getSimpleName();
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
Log.i(LOG_TAG, "Loading after booting...");
Intent startCalendarActivityIntent = new Intent(context, CalendarActivity.class);
startCalendarActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(startCalendarActivityIntent);
} else {
Log.e(LOG_TAG, "Error while restarting after boot.");
}
}
}
On this device is Android 6.0 .
You can either use wakelocks, which need certain permissions, or you can put a flag in your onCreate method, which according to the docs does not require a permission.
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
The wakelock documentation gave the example above.

why Broadcast Receiver Don't work for service application android?

I have a project which is only a service and it has no activity and user interface. I want to start my application background service when phone boot completely. but I never receive the "BOOT_COMPLETED" Message from OS. these are my code:
Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.droid.arghaman.location_tracker">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<receiver android:name=".BootBroadcastReceiver"
android:enabled="true"
android:exported="false"
android:label="StartServiceAtBootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
<category android:name="android.intent.category.DEFAULT"></category>
</intent-filter>
</receiver>
</application>
<service android:name=".mySevice"></service>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>
</manifest>
Broadcast Receiver:
public class BootBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.i("boot Received", intent.getAction());
Intent serviceLuncher = new Intent(context, myService.class);
context.startService(serviceLuncher);
}
}
myService:
public class LocationNotifierService extends Service {
Timer timer ;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate(){
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
Toast.makeText(getBaseContext(),"Location",Toast.LENGTH_SHORT).show();
}
},3000);
}
#Override
public void onDestroy(){
}
#Override
public int onStartCommand(Intent intent, int flagId, int startId){
return START_STICKY;
}
}
but I never get "boot Received" log.
is there any mistake and is there any way to debug my program?
I Recommend that my project must have only this Service and it cannot have any UI.
I never receive the "BOOT_COMPLETED" Message from OS
Partly, that is because you do not have a <receiver> set up to receive android.intent.action.BOOT_COMPLETED broadcasts.
Partly, that is because your app will not receive broadcasts until something on the device uses an explicit Intent to start one of your components. The way your app is set up — without an activity that the user can run — it is unlikely that any app will do this, and so your code will never run.
Also, please bear in mind that Android O has changes designed specifically to prevent background services from running for very long and to limit your ability to get background location updates (which your location_tracker name suggests that you want to add in the future). You may wish to reconsider whether writing this app the way that you are is a wise course.
try this in your manifest
<receiver android:name=".BootBroadcastReceiver"
android:enabled="true"
android:exported="false"
android:label="StartServiceAtBootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>

Priority two apps use bootcompletedReceiver on android

recently I use BOOT_COMPLETED 2 app (A app, and B app)
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
A app is activity and B app is service app
when my device boot,
first A app launch and B app launch
so, show B app screen.
I want
first B app launch and A app launch showing A app screen
perhaps, Can I give BOOT_COMPLETED Priority is possible?
finally, I want when I boot my device, show A app screen
Thanks!
add
I try
B app(service)
public class BootCompletedReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED) {
Intent i = new Intent("A app package name.BOOT_COMPLETED");
context.sendBroadcast(i);
}
}
}
<receiver android:name=".BootCompletedReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
A app(activity)
public class BootSendReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context,Intent intent) {
if( intent.getAction().equals("B app packagename.BOOT_COMPLETED"));
Intent i = new Intent (context, MainActivity.class);
context.startActivity(i);
}
}
<receiver android:name=".BootSendReceiver">
<intent-filter>
<action android:name="blackeyeonandroid.iosystem.co.kr.simpleserviceexample.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
and I try boot .. but showing B app screen
I think you can not control that..
Instead, you can make APP1 start the APP2. This way, only APP1 receives the BOOT_COMPLETE message. Then, APP1 is responsible to send a new intent to start APP2:
Maybe, you can do as follows (note that APP2 does not receive android's default BOOT_COMPLETED message):
APP1
Manifest:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver android:name=".AppToStartFirstBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
Receiver
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
Intent i = new Intent("com.example.mytestapp.BOOT_COMPLETED");
context.sendBroadcast(i);
}
}
APP2
Manifest:
<receiver android:name=".AppToStartLaterBroadcastReceiver">
<intent-filter>
<action android:name="com.example.mytestapp.BOOT_COMPLETED" />
</intent-filter>
</receiver>
Receiver
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("com.example.mytestapp.BOOT_COMPLETED")) {
// Do what you want in secundary APP
}
}
Note
This is an suggestion and you should adjust to your case. Since I don't have more details about your code, you may need to modify it to your case.. But you can use the idea.

How to start an activity via a service after rebooting

I need my app to start running (in the background) after rebooting the device. Here's what I've come up with till now (after taking a lot of help from here...)
This is my BootUpReceiver making use of broadcastreceiver:
public class BootUpReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent serviceIntent = new Intent(context, RebootService.class);
serviceIntent.putExtra("caller", "RebootReceiver");
context.startService(serviceIntent);
}
}
This is the service class:
public class RebootService extends IntentService{
public RebootService(String name) {
super(name);
// TODO Auto-generated constructor stub
}
protected void onHandleIntent(Intent intent) {
Intent i = new Intent(getBaseContext(), MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
String intentType = intent.getExtras().getString("caller");
if(intentType == null)
return;
if(intentType.equals("RebootReceiver"))
getApplication().startActivity(i);
}
}
THis is my android manifest:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver
android:name=".BootUpReceiver"
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=".RebootService"/>
</application>
The problem is, When I install this on my phone and reboot, the app crashes: It says, "Transfer has stopped working". After I press the OK button, when I check the app info, the app is running.
I'm new to android and I'm not sure what is going on. Am I supposed to add any more permissions?
Kindly help.
TIA
I think your problem lies with your RebootService constructor. When the system invokes it, it doesn't provide any arguments, so it's going to crash. If you look in the logs you'll probably see something to the effect of "Unable to instantiate service..."
Try replacing your constructor with:
public RebootService() {
super( "Reboot Service" );
}

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