My girlfriend has a problem with her Samsung Galaxy S with Cyanogenmod 10.2. Every time she restarts her phone, the APN list is empty and she can't add new (which means she can't use mobile internet nor send/receive MMS). To temporarily fix it until next reboot, she needs to turn airplane mode on, wait few seconds, and then turn airplane mode off again.
To ease things up, I've written a simple application which is supposed to do it instead of her. But it doesn't work - I see in logs that the app was started, but it doesn't toggle Airplane mode.
Permissions should be set correctly, I even installed the app into /system/app to make Android think it's a system app. The permissions are displayed correctly when I look at the application in Applications list.
Here's my code:
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cz.berzeger.autoflightmode"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="18"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<service android:name=".AutoFlightModeService" android:label="AutoFlightMode Service" />
<receiver
android:name=".ServiceReceiver"
android:enabled="true"
android:exported="true"
android:label="ServiceReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>
ServiceReceiver.java
package cz.berzeger.autoflightmode;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class ServiceReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
Intent serviceIntent = new Intent(context, AutoFlightModeService.class);
context.startService(serviceIntent);
}
}
}
AutoFlightModeService.java:
package cz.berzeger.autoflightmode;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.provider.Settings;
public class AutoFlightModeService extends Service {
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Turn AirPlane mode on
Settings.Global.putString(getContentResolver(), "airplane_mode_on", "1");
// All services run in one thread. We need to explicitly create a new thread,
// if we want to implement non-blocking wait.
new Thread( new Runnable() {
public void run() {
try { Thread.sleep( 5000 ); }
catch (InterruptedException ie) {}
// After 5 seconds, turn Airplane mode off
Settings.Global.putString(getContentResolver(), "airplane_mode_on", "0");
}
}).start();
return START_NOT_STICKY;
}
}
Any ideas what I'm doing wrong? Thanks.
adb shell ls system/
addon.d
app
bin
blobs
build.prop
etc
extras
fonts
framework
lib
lost+found
media
***priv-app***
recovery-from-boot.p
tts
usr
vendor
xbin
The app needs to be installed in priv-app to take the system permissions.
Related
I am trying to catch the event from the pairing process with the android via Broadcast receiver. As it seems, the BluetoothDevice.BOND_BONDING is works, but the BluetoothDevice.BOND_BONDED not.
In the old android versions this worked (tried with Android 6 and 7), however with the newer ones (tried Android 9, several devices) this does not work. In order to reproduce the problem I've made a simple program:
Java file:
package com.example.bluetoothtest;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
BroadcastReceiver receiver;
BluetoothDevice mDevice;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)){
mDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (mDevice.getBondState() == BluetoothDevice.BOND_BONDED) {
//means device paired
Log.d("bt", "bonded");
}
else if(mDevice.getBondState() == BluetoothDevice.BOND_BONDING) {
Log.d("bt", "bonding");
}
}
}
};
}
#Override
protected void onStart() {
super.onStart();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(receiver, filter);
}
#Override
protected void onStop() {
super.onStop();
unregisterReceiver(receiver);
}
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.bluetoothtest">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
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>
</application>
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
</manifest>
Did anybody else notice this problem? Am I missing a permission? Couldn't find anything relevant on the net.
You should try to retrieve the EXTRA_BOND_STATE like that :
val state = intent.extras?.get(BluetoothDevice.EXTRA_BOND_STATE) as Int
I have faced a similar problem. I have noticed one thing with devices such as HeadPhone, mouse or keyboard is that when you pair such devices, it is immediately connected to our Android device.
So android send us
android.bluetooth.device.action.ACL_CONNECTED
connected broadcast immediately. In case we receive this broadcast, it is safe to assume that Bluetooth device is already paired.
I would recommend adding this permission for Android 12 and above devices to listen to the connected broadcast.
android.permission.BLUETOOTH_CONNECT
I want to create an Android application which performs some action periodically (every minute) in the background. The application shall have no user interface, therefore there will be no Action-Class. It shall start automatially after boot.
I have coded my Application as shown below, but it just does not start after boot? Can anyone help?
I am using a Samsung Tablet GT-P5200 with Android 4.4.2
Many thanks for your help in advance.
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.somecompany.justoneservice" >
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<receiver
android:name=".BootReceiver"
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=".MyService"
android:enabled="true"
android:exported="true" >
</service>
</application>
</manifest>
BootReceiver.java
package com.somecompany.justoneservice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.text.format.DateUtils;
import android.util.Log;
public class BootReceiver extends BroadcastReceiver {
public BootReceiver() {
}
#Override
public void onReceive(Context context, Intent intent) {
Log.d("TAG", "BOOT");
long interval = DateUtils.MINUTE_IN_MILLIS * 1;
long firstStart = System.currentTimeMillis() + interval;
Intent mainServiceIntent = new Intent(context, MyService.class);
PendingIntent mainServicePendingIntent = PendingIntent.getService(context, 0, mainServiceIntent, 0);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.setInexactRepeating(AlarmManager.RTC, firstStart, interval, mainServicePendingIntent);
}
}
MySevice.java
package com.somecompany.justoneservice;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class MyService extends Service {
public MyService() {
}
#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. (" + startId + ")");
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;
}
}
The application shall have no user interface, therefore there will be no Action-Class.
Newly-installed apps' manifest-registered receivers are disabled until something uses an explicit Intent to start one of your components. Usually, this is the user tapping on the icon for one of your activities in a home screen's launcher. And usually that is not a problem, because all apps need an activity, to allow the user to configure the behavior of the app, get help, read the license agreement terms, etc.
In some scenarios, something other than a home screen launcher icon can start up one of your components with an explicit Intent. For example, if you are a plugin to some other app, that other app might detect your installation and start up one of your components.
But, if nothing will start one of your components with an explicit Intent, then your BOOT_COMPLETED receiver will never get control, even after a reboot.
I have stuck with an issue of running a service when force stop is clicked and when i restart my mobile the service should be invoked.I have followed some examples but i cant able to achieve the task.Can any one guide me to achieve the task.
Required:
1.Service should run when force stop has been clicked from settings
2.Service should run when mobile has been restarted.
TestActivity.java
package com.testsearching;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class TestActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
startService(new Intent(this, ServiceTest.class));
}
}
ServiceTest.java
package com.testsearching;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class ServiceTest extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mTimer = new Timer();
mTimer.schedule(timerTask, 2000, 2 * 1000);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
} catch (Exception e) {
e.printStackTrace();
}
return super.onStartCommand(intent, flags, startId);
}
private Timer mTimer;
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
Log.e("Log", "Running");
}
};
public void onDestroy() {
try {
mTimer.cancel();
timerTask.cancel();
} catch (Exception e) {
e.printStackTrace();
}
Intent intent = new Intent("com.android.techtrainner");
intent.putExtra("yourvalue", "torestore");
sendBroadcast(intent);
}
}
ReceiverCall.java
package com.testsearching;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
public class ReceiverCall extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
Log.i("Service Stops", "Ohhhhhhh");
context.startService(new Intent(context, ServiceTest.class));;
Toast.makeText(context, "My start", Toast.LENGTH_LONG).show();
}
}
}
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.testsearching"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:theme="#style/AppTheme" >
<activity
android:name="com.testsearching.TestActivity"
android:label="#string/app_name"
android:theme="#android:style/Theme.NoTitleBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".ServiceTest" >
<intent-filter>
<action android:name="com.testsearching.ServiceTest" />
</intent-filter>
</service>
<receiver
android:name="ReceiverCall"
android:enabled="true"
android:exported="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >
<intent-filter>
<action android:name="com.android.techtrainner" />
<action android:name="android.intent.action.SCREEN_ON" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>
In theory, this is not possible; according to the Android security model.
As Panaj Kumar points out in the comments:
When user does force stop, means he does not want to run this
application (any component). he is not interested anymore, and this
is rights of user. SO android does not gives a way to keep running
your service, even after forced close your app.
Android will prevent the app from restarting using the START_STICKY flag, and will disable the RECEIVE_BOOT_COMPLETED receiver. The system will also disable all Alarms that have been set for this app.
Before the system will allow the app to run again, the user must run an Activity of the app themselves.
That said, it seems that certain apps are still able to break the rules in this way. This should be considered incorrect and would be taking advantage of a security hole, however it shows that it is still possible, even on KitKat.
The Discovery Insure driving app seems to be able to restart itself when it has been force stopped, and will restart on boot:
Discovery Insure Driving Challenge on Play Store
However, this functionality should not be relied on - hopefully this security flaw will be fixed in future system updates.
Write this on in your OnCreate of the main launching activity
if(!isMyServiceRunning(ServiceClass.class))
context.startService(new Intent(context.getApplicationContext(),ServiceClass.class));
here is the running service check function
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
and Create your service with this architecture.Observe the return START_STICKY
public class ServiceClass extends IntentService {
public ServiceClass()
{
super("null");
}
public Context context;
public Intent intent;
public Date currentTime;
#Override
public int onStartCommand(#Nullable Intent intent, int flags, int startId) {
onHandleIntent(intent);
return START_STICKY;
}
#Override
protected void onHandleIntent(#Nullable Intent intnt) {
currentTime = Calendar.getInstance().getTime();
context = getApplicationContext();
this.intent = intnt;
Log.d("ServiceClass","Service class running "+ currentTime);
}
}
I'm writing an Android app that has two major components: a service which starts up at boot time, and a GUI that I want to start only when I manually launch it via its icon, not when the device boots. I know how to start the service at boot time, but it also launches the GUI at boot time, which I don't want.
I presume that this has something to do with the settings in my manifest, but despite trying a number of things, I haven't figured out how to prevent the GUI from also starting at boot time.
I should add that I do not programmatically launch the GUI at boot time. I do reference static public variables within the GUI's activity class, but I do not make any method calls or send any intents to the GUI's activity.
Here is my manifest. What am I doing wrong? Thank you very much.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="my.package.name"
android:versionCode="0"
android:versionName="0.1.0">
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="17"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.WRITE_SMS"/>
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.MANAGE_ACCOUNTS" />
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application android:icon="#drawable/icon"
android:label="#string/app_name"
android:allowBackup="true" >
<!-- XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
I want MainActivity to only start when I
select its icon, NOT at boot time. However,
it always starts up at boot.
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
-->
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:launchMode="singleTop">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
MyBootReceiver properly starts up at boot time,
and it properly invokes MyBootService. At
the appropriate time, MyBootService invokes
RegisterActivity.
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
-->
<activity android:name=".RegisterActivity"
android:label="#string/app_name">
</activity>
<receiver
android:name=".MyBootReceiver"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="my.package.name" />
</intent-filter>
</receiver>
<service android:name=".MyBootService" />
</application>
</manifest>
Adding broadcast receiver class:
package my.package.name;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class MyBootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent bootIntent = new Intent(context, MyBootService.class);
bootIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startService(bootIntent);
}
}
Adding service class ...
package my.package.name;
import java.util.ArrayList;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.telephony.TelephonyManager;
public class MyBootService extends Service {
private static final String GOOGLE_ACCOUNT_TYPE = "com.google";
private static final String GOOGLE_ACCOUNT_FEATURE = "service_ah";
private Context context = null;
#Override
public IBinder onBind(Intent intent) {
this.display("onBind");
return (null);
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
AccountManager am = AccountManager.get(this);
am.getAccountsByTypeAndFeatures(GOOGLE_ACCOUNT_TYPE, new String[]{GOOGLE_ACCOUNT_FEATURE},
new AccountManagerCallback<Account[]>() {
#Override
public void run(AccountManagerFuture<Account[]> acclist) {
MyBootService parent = MyBootService.this;
Intent regIntent = new Intent(parent.getApplicationContext(), RegisterActivity.class);
try {
ArrayList<String> accountNameList = new ArrayList<String>();
for (Account a: acclist.getResult()) {
accountNameList.add(a.name);
}
regIntent.putStringArrayListExtra("accountNames", accountNameList);
try {
TelephonyManager tmgr = (TelephonyManager) parent.getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
String phoneNo = tmgr.getLine1Number();
regIntent.putExtra("phoneNumber", phoneNo);
}
catch (Throwable t) {
}
}
catch (Throwable t) {
// put error message here
}
regIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
parent.startActivity(regIntent);
}
}, null);
return (START_STICKY);
}
#Override
public void onDestroy() {
this.display("onDestroy");
super.onDestroy();
}
}
MORE INFO
I figured out some of what is going on. First of all, I was mistaken in saying that my MainActivity was starting. Upon more detailed debugging, I see that its onCreate() and onResume() methods were not being called. However, the app's view was showing up: a black screen with the name of the app and the default icon. I originally mistook that for an indication of a full startup.
This, of course, raises the question of why that view showed up on boot, in the first place. I have some info about this, although I'm still confused as to what is going on. I stripped down the onCreate() method of the RegisterActivity class that gets invoked by MyBootService. When this.getIntent() is called, the application's view shows up on boot. When this.getIntent() is commented out, the application's view does not show up on boot.
Note that this is onCreate() of the RegisterActivity class, NOT of MainActivity.
Do any of you know what could be causing the application's view to show up when this.getIntent() is called?
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// If the following line is commented out, the
// application's view does not show up on boot;
// if the following line is not commented out,
// the application's view shows up.
Intent intent = this.getIntent();
}
I think what you are seeing is the preview used by Android to make the app startup seems faster. This preview is made based on the theme of your activity.
Try setting a custom theme for your RegisterActivity which more closely looks like the final result. For example, if your activity is a dialog, create a theme extending Theme.Dialog or Theme.Light.Dialog
You can get more information on this blog post from Cyril Mottier: Android App Launching Made Gorgeous
EDIT: changed to actually answer the question
THE REAL, ACTUAL ANSWER
Because of the help and feedback I got here, I finally figured out my problem and solved it:
I was wrong in using an Activity in the first place (my RegisterActivity class), because I don't want the functionality that I originally put into RegisterActivity to be associated with a GUI. Due to inexperience with the Android model and lack of sufficient documentation reading, I didn't realize Activity always has a view associated with it.
Now that I know this, I refactored my app so that all the functionality formerly in RegisterActivity has been moved to MyBootService. Now, no view pops up on boot, and my app does what I want.
Thanks to all for your help and patience.
I am currently trying to make a broadcast receiver which will invoke after android device boots and then will run a background service. I have tried many examples but don't know where I'm going wrong. I am following this example:
https://github.com/commonsguy/cw-advandroid/tree/master/SystemEvents/OnBoot
I have imported this whole project in my workspace and tried to run. But the receiver didn't invoked or so.
Please help me out.
My Testing Device is: Motorolla Xoom with ICS 4.0.3
EDIT
Manifest
<uses-sdk android:minSdkVersion="8" />
<supports-screens
android:anyDensity="true"
android:largeScreens="true"
android:normalScreens="true"
android:smallScreens="true" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.REBOOT" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<service
android:name="awais.soft.MyService"
android:enabled="true" >
<intent-filter>
<action android:name="awais.soft.MyService" >
</action>
</intent-filter>
</service>
<receiver android:name="awais.soft.ServicesDemoActivity" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" >
</action>
<category android:name="android.intent.category.HOME" >
</category>
</intent-filter>
</receiver>
</application>
Broadcast Receiver
package awais.soft;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
public class ServicesDemoActivity extends BroadcastReceiver {
static final int idBut = Menu.FIRST + 1, idIntentID = Menu.FIRST + 2;
#Override
public void onReceive(Context context, Intent intent) {
Log.e("Awais", "onReceive:");
if (intent.getAction().equals(Intent.ACTION_POWER_CONNECTED)) {
Intent i = new Intent();
i.setAction("awais.kpsoft.MyService");
context.startService(i);
}
}
}
Service
package awais.soft;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class MyService extends Service {
private static final String TAG = "MyService";
MediaPlayer player;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
player = MediaPlayer.create(this, R.raw.is);
player.setLooping(false); // Set looping
}
#Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
player.stop();
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
player.start();
}
}
I am something like this in My app and Its Working for me.
public class DeviceBootReceiver extends BroadcastReceiver {
#Override
public final void onReceive(final Context context, final Intent intent) {
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
// CustomLog.i("Boot Completed");
}
}
}
Android Manifset
<receiver android:name=".model.service.DeviceBootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
<category android:name="android.intent.category.HOME"></category>
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>
<uses-permission android:name="android.permission.REBOOT" />
Please check if you have given permission for RECEIVE_BOOT_COMPLETED
see i am posting you eample that will help you
For some applications, you will need to have your service up and running when the device is started, without user intervention. Such applications mainly include monitors (telephony, bluetooth, messages, other events).
At least this feature is currently allowed by the exaggeratedly restrictive Android permissions policy.
Step 1: First you'll need to create a simple service, defined in Monitor.java:
public class Monitor extends Service {
private static final String LOG_TAG = "::Monitor";
#Override
public void onCreate() {
super.onCreate();
Log.e(LOG_TAG, "Service created.");
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.e(LOG_TAG, "Service started.");
}
#Override
public void onDestroy() {
super.onDestroy();
Log.e(LOG_TAG, "Service destroyed.");
}
#Override
public IBinder onBind(Intent intent) {
Log.e(LOG_TAG, "Service bind.");
return null;
}
}
Step 2: Next we need to create a Broadcast receiver class, StartAtBootServiceReceiver.java:
public class StartAtBootServiceReceiver extends BroadcastReceiver
{
private static final String LOG_TAG=StartAtBootServiceReceiver";
#Override
public void onReceive(Context context, Intent intent)
{
Log.e(LOG_TAG, "onReceive:");
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
Intent i = new Intent();
i.setAction("test.package.Monitor");
context.startService(i);
}
}
}
Step 3: Finally, your AndroidManifest.xml file must contain the following:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="test.package.Monitor"
android:versionName="1.0"
android:versionCode="100"
android:installLocation="internalOnly">
<supports-screens android:smallScreens="true" android:normalScreens="true" android:largeScreens="true" android:anyDensity="true" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>
<uses-sdk android:minSdkVersion="7" android:targetSdkVersion="8"/>
<application android:icon="#drawable/icon" android:label="#string/app_name">
<service android:name="test.package.Monitor">**
<intent-filter>
<action android:name="test.package.Monitor">
</action>
</intent-filter>
</service>
<receiver android:name="test.package.StartAtBootServiceReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED">
</action>
<category android:name="android.intent.category.HOME">
</category>
</intent-filter>
</receiver>
</application>
I need to highlight some of the most important aspects, key factors for possible errors in implementation:
1) The permission android.permission.RECEIVE_BOOT_COMPLETED must be provided (in the manifest xml)
2) The installation must be performed in internal storage, not on SDCARD! To enforce this use android:installLocation="internalOnly" in the manifest
Everything was fine..:S
The problem was with device..(i.e. Motorolla Zoom ICS 4.0.3)
Now tested on Galaxy Tab With 2.2 and Working fine..
Thanks all for your time
If your phone is rooted then you will have trouble in Android Boot-Up BroadCast invoking otherwise you have to ensure your app has required root permissions
The problem persists in the case of devices having android version more than 3.0, by the way its not the problem it has been done for security purposes by google i guess..If u have to run the service on boot you have to make a custom intent & broadcast it. For making custom intent you have to make a service file from where u have to broadcast that intent on boot complete & your service file(that u want to run) will receive that intent on its onReceive method & your service will run.One more thing the service file you will create to call your service that you want to run should be kept on system/app folder of file explorer of device, if your file system shows sorry read only file system then from command prompt do just adb remount & then push the file on device,restart your system your service will run..Cheers!!