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);
}
}
Related
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);
}
I used this permission:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
and the receiver is:
<receiver android:name=".auth.NotificationBroadcast" android:enabled="true" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
and receiver in code is:
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("BroadcastReceiverBroadcast--------------------ReceiverBroadcastReceiverBroadcastReceiver----------------BroadcastReceiver");
if (intent != null) {
String action = intent.getAction();
switch (action) {
case Intent.ACTION_BOOT_COMPLETED:
System.out.println("Called on REBOOT");
// start a new service and repeat using alarm manager
break;
default:
break;
}
}
}
After reboot it's still not getting called in lollipop, but on marshmallow it's running.
try to put this line in your receiver's intent-filter.
<action android:name="android.intent.action.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE" />
If your application is installed on the SD card, you should register this to get the android.intent.action.BOOT_COMPLETED event.
Updated: Since your app is using alarm service, it should not be installed on external storage. Reference: http://developer.android.com/guide/topics/data/install-location.html
Whenever the platform boot is completed, an intent with android.intent.action.BOOT_COMPLETED action is broadcasted. You need to register your application to receive this intent. For registering add this to your AndroidManifest.xml
<receiver android:name=".ServiceManager">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
So you will have ServiceManager as broadcast receiver to receive the intent for boot event. The ServiceManager class shall be as follows:
public class ServiceManager extends BroadcastReceiver {
Context mContext;
private final String BOOT_ACTION = "android.intent.action.BOOT_COMPLETED";
#Override
public void onReceive(Context context, Intent intent) {
// All registered broadcasts are received by this
mContext = context;
String action = intent.getAction();
if (action.equalsIgnoreCase(BOOT_ACTION)) {
//check for boot complete event & start your service
startService();
}
}
private void startService() {
//here, you will start your service
Intent mServiceIntent = new Intent();
mServiceIntent.setAction("com.bootservice.test.DataService");
mContext.startService(mServiceIntent);
}
}
Since we are starting the Service, it too must be mentioned in AndroidManifest:
<service android:name=".LocationService">
<intent-filter>
<action android:name="com.bootservice.test.DataService"/>
</intent-filter>
</service>
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
I have a onBootCompleted broadcast receiver registered in the manifest.
It runs starts MyService. My service in the onCreate registers 3 more broadcast receivers dynamically.
The 3 new receivers filter on the following intent actions
LOCALE_CHANGED,
TIMEZONE_CHANGED and
CONNECTIVITY_CHANGED.
These works correctly when I run the application from Eclipse but, after I reboot the device and my service starts up none of receivers work.
I have a work around implementation but, I would like to know why this is happening?
Manifest:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver android:name=".receiver.BootCompletedReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.HOME" />
</intent-filter>
</receiver>
<service
android:name=".MyService"
android:enabled="true"
android:exported="false"
android:stopWithTask="false" >
</service>
Service:
public class MyService()
{
LocationTimeZoneChangedReceiver mLocationTimeZoneChangedReceiver = new LocationTimeZoneChangedReceiver()
NetworkChangedReceiver mNetworkChangedReceiver = new NetworkChangedReceiver()
public void onCreate()
{
registerReceiver(mLocationTimeZoneChangedReceiver, new IntentFilter(Intent.ACTION_LOCALE_CHANGED));
registerReceiver(mLocationTimeZoneChangedReceiver, new IntentFilter(Intent.ACTION_TIMEZONE_CHANGED));
registerReceiver(mNetworkChangedReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
}
BootCompletedReceiver:
public class BootCompletedReceiver extends BroadcastReceiver
{
public void onReceive(Context context, Intent intent){}
}
MyApplication:
public class MyApplication extends Application
{
ServiceConnection mServiceConnection = new ServiceConnection() { anonymous class...}
public void onCreate()
{
bindService(new Intent(this, MyService.class), mServiceConnection,Context.BIND_AUTO_CREATE);
}
}
Edited:
Edited code for Plinio.Santos.
It's a big app with many moving parts so at best I can post small code snippets.
Following are the steps I am following for testing:
Push app via Eclipse,
test that network change receiver is working
leave wifi off
Now restart the device
wait for the process to start and turn on wifi.
I believe that the service is not started or bound due errors. Unfortunately I can not say it for sure without all binding/starting code.
Anyway, you can see bellow a code that worked fine after I rebooted (the app started, registered the receiver and is receiving the CONNECTIVITY_CHANGED broadcast.
AndroidManifest.xml:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver android:name=".TestReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service
android:name=".TestService"
android:exported="true" />
Receiver class:
public class TestReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent != null && Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
Toast.makeText(context, "Intent.ACTION_BOOT_COMPLETED receiverd !", Toast.LENGTH_SHORT).show();
context.startService(new Intent(context, TestService.class));
}
}
}
Service class:
public class TestService extends Service {
private BroadcastReceiver mConnectivityChangedReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent != null && ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Toast.makeText(context, "ConnectivityManager.CONNECTIVITY_ACTION receiverd !", Toast.LENGTH_SHORT).show();
}
}
};
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
registerReceiver(mConnectivityChangedReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
}
I have run into a snag, I can't get my alarms properly setup again after a boot.
public void onReceive(Context context, Intent intent) {
if(Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())){
if(fm.getAlarmBool()){
time = fm.getAlarmTimeLong();
reminder.startAlarm(time);
}
}
This is my method that I want to run after it boots up. I have added permissions in the android manifest but I can't get it to work. Whats wrong?
You should do it like
public class BootReceiver extends BroadcastReceiver {
Context context;
#Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, NotificationService.class));
}
}
in manifest
<receiver android:process=":remote" android:name="BootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.MAIN" />
</intent-filter>
</receiver>
so here in your service collect all the reminders and reschedule them.
for this you can store it in shared pref or database for persistent storage