in the below code i am trying to start a service as shown. but at run time
serviceCtrl.isMyServiceRunning()
returns false and the toast doesnt show up despite the service is added to the manifest file.
i am starting the service wrongly?! why the service does not start
code:
if (mIsBonded) {
mSB.append("Pairing Completed" + "\n");
Intent intSPPService = new Intent(getApplicationContext(), SPPService.class);
intSPPService.putExtra("key", "starting SPP Service");
startService(intSPPService);
ServiceCtrl serviceCtrl = new ServiceCtrl(getApplicationContext(), ActMain.class);
if (serviceCtrl.isMyServiceRunning()) {
Toast.makeText(getApplicationContext(), "Starting SPP Service", Toast.LENGTH_SHORT).show();
}
//mATRFCConn = new ATRFCConn();
//mATRFCConn.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
mSB.append("Pairing Failed" + "\n");
}
...
...
...
public boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) this.mCtx.getSystemService(this.mCtx.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (this.mClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
service:
public class SPPService extends Service {
private final String TAG = this.getClass().getSimpleName();
final static String SPP_SERVICE_ACTION = "SPP_ACTION";
#Override
public void onCreate() {
Log.w(TAG, "onCreate");
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.w(TAG, "onStartCommand");
String str = intent.getStringExtra("key");
Log.v(TAG, "Act->Service : " + str);
return Service.START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Update
at run time i receive
W/ActivityManager: Unable to start service Intent {
cmp=com.example.com.myapplication/com.example.com.servicebt_01.SPPService
(has extras) } U=0: not found
manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.com.servicebt_01" >
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity android:name=".ActMain" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<service
android:enabled="true"
android:name=".SPPService"
android:icon="#mipmap/ic_launcher"
android:label="#string/service_name"
>
</service>
Please check this answer :
Unable to start service Intent
It says you have not given the name of the service in the manifest correctly. Please verify it.
Try to enter the Service name along with the entire package name in which it is present.
Your service name in manifest is error,not
<service
android:name="SPPService"
android:icon="#mipmap/ic_launcher"
android:label="#string/service_name"
>
</service>
If your SSPService is located in your application package,you can specify it like this:
<service
android:name=".SPPService"
android:icon="#mipmap/ic_launcher"
android:label="#string/service_name"
>
</service>
If not,you should specify its full path.
Related
Good evening community, I am reaching with the hopes of being educated about the following problem.
My intention with this code is to be able to handle USB permission intents in a receiver registered in a manifest file. The receiver gets USB Attached and detached actions, but not USB permissions when the user either accepts or declines the prompt.
Here is the code for the manifest, receiver and an activity to send the permissions request to the USB manager. And Finally, my target SDK is 28.
Any help is very much appreciated. Thank you very much.
public class BroadcastReceiver extends android.content.BroadcastReceiver{
public static final String USB_DEVICE_ATTACHED = "android.hardware.usb.action.USB_DEVICE_ATTACHED";
public static final String USB_DEVICE_DETACHED = "android.hardware.usb.action.USB_DEVICE_DETACHED";
public static final String USB_PERMISSION ="com.android.example.USB_PERMISSION";
#Override
public void onReceive(Context context, Intent intent) {
Context applicationContext = context.getApplicationContext();
try{
if (intent != null) {
String action = intent.getAction();
if (!TextUtils.isEmpty(action)) {
if (action.equals(USB_DEVICE_ATTACHED) || action.equals(USB_PERMISSION)){
UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
UsbManager usbManager = (UsbManager) applicationContext.getSystemService(Context.USB_SERVICE);
if (action.equals(USB_DEVICE_ATTACHED)){
if (!usbManager.hasPermission(device)){
intent.setAction(USB_PERMISSION);
intent.putExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false);
intent.setClass(applicationContext, PermissionActivity.class);
applicationContext.startActivity(intent);
Toast.makeText(applicationContext, "Device Attached.", Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(applicationContext, "Permissions already assigned", Toast.LENGTH_LONG).show();
}
}
else if (action.equals(USB_PERMISSION)){
if (usbManager.hasPermission(device)){
Toast.makeText(applicationContext, "USB Permissions are granted.", Toast.LENGTH_LONG).show();
}
}
}
else if (action.equals(USB_DEVICE_DETACHED)) {
Toast.makeText(applicationContext, "Device Detached.", Toast.LENGTH_LONG).show();
}
}
}
}
catch(Exception e){
Toast.makeText(applicationContext, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
Here is the activity:
public class PermissionActivity extends android.support.v7.app.AppCompatActivity {
public static final String USB_PERMISSION ="com.android.example.USB_PERMISSION";
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Context applicationContext = this.getApplicationContext();
Intent intent = getIntent();
if (intent != null )
{
if (intent.getAction().equals(USB_PERMISSION)){
if (!intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false )) {
UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (device != null) {
UsbManager mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
PendingIntent mPermissionIntent = PendingIntent.getBroadcast(applicationContext, 0, new Intent(USB_PERMISSION), 0);
mUsbManager.requestPermission(device, mPermissionIntent);
Toast.makeText(applicationContext, "Requesting Permission", Toast.LENGTH_LONG).show();
}
}
}
}
finish();
}
#Override
protected void onResume() {
super.onResume();
}
}
And finally, the manifest file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.user.usbtest">
<uses-feature android:name="android.hardware.usb.host"/>
<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"
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=".PermissionActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize"
android:excludeFromRecents="true"
android:exported="true"
android:noHistory="true"
android:process=":UsbEventReceiverActivityProcess"
android:taskAffinity="com.example.taskAffinityUsbEventReceiver"
android:theme="#style/Theme.AppCompat.Translucent">
<intent-filter>
<action android:name="com.android.example.USB_PERMISSION"/>
</intent-filter>
</activity>
<receiver android:name=".BroadcastReceiver"
android:exported="true">
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"/>
<action android:name="android.hardware.usb.action.USB_DEVICE_DETACHED"/>
<action android:name="com.android.example.USB_PERMISSION"/>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
</application>
</manifest>
I found the problem. Since Android 8.0, there are more restrictions with manifest-declared
broadcast receivers and the type of actions that can be received. The USB Permissions action is not part of the limited list of actions that can be received. Here are some links regarding this issue.
https://developer.android.com/guide/components/broadcasts#context-registered-recievers
https://developer.android.com/guide/components/broadcast-exceptions
I am trying to create an Android app that uses the pedometer. Currently having trouble getting the service to start up when the user restarts/turns their phone on and off. I am using 5.1, and testing has been done on a simulator. I am not sure if it is working since the logs have not been appearing in the console.
Any help is much appreciated!
App Manifest Class:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"package="app.apphub.devon.walkingquest">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".WalkingQuestSplashScreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".BootReceiver" android:exported="true" android:enabled="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filtering>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filtering>
</receiver>
<service android:name=".StepCounterSensorRegister" android:enabled="true" android:exported="true"/>
</application>
</manifest>
Boot Receiver Class:
public class BootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
Log.i("BROADCAST", "WALKING_QUEST_BOOT");
Intent _intent = new Intent("app.apphub.devon.walkingquest.StepCounterSensorRegister");
intent.setClass(context, StepCounterSensorRegister.class);
context.startService(_intent);
//context.startService(_intent);
//Toast.makeText(context,"Airplane mode on",Toast.LENGTH_LONG).show();
}
else {
Log.i("FAIL","BROADCAST FAILED");
}
}
StepCounterSensorRegister Class:
public class StepCounterSensorRegister extends Service implements SensorEventListener {
SensorManager sensorManager;
Sensor sensor;
long globalSteps;
boolean flag = false;
#Override
public void onCreate(){
}
public int onStartCommand(Intent intent, int flags, int startId) {
//Must run in background thread
Log.i("START","STEP_COUNTER_STARTED");
registerSensor(sensorManager.SENSOR_DELAY_UI);
return START_STICKY;
}
public void onSensorChanged(SensorEvent event) {
if(!flag){
}
if(event.sensor.getType() == Sensor.TYPE_STEP_COUNTER){
Log.i("STEPS DETECTED",""+globalSteps);
globalSteps++;
}
}
public boolean registerSensor(int accuracy) {
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
try {
sensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
}catch (Exception e){
Log.i("ERROR", e.getMessage());
}
if(sensor == null) {
Log.i("FAILED","Sensor returned null");
return false;
}
else {
Log.i("SUCCESS", "Successfully registered sensor");
sensorManager.registerListener(this, sensor, accuracy);
return true;
}
}
Two things I see is that you declared something wrong in your manifest:
<receiver android:name=".BootReceiver" android:exported="true" android:enabled="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filtering>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filtering>
</receiver>
intent-filtering doesn´t exist, it is intent-filter
the permissions android:permission="android.permission.RECEIVE_BOOT_COMPLETED" is misplaced here, don´t put it inside receiver tag. You have already defined it above.
And be sure you set the correct filter in your Logcat, you are using two different tags "BROADCAST" and "FAIL", maybe also this is going wrong.
I've the same issue described here but i can't understand whats wrong.
My issue is: Unable to start service Intent { act=.connections.MoodyService } U=0: not found
EDIT
I've changed my package from connections to service in the source code, sorry for the confusion
My manifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.moody"
android:installLocation="auto"
android:versionCode="0"
android:versionName="0.6.7 alpha" >
<uses-sdk
android:maxSdkVersion="18"
android:minSdkVersion="14"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:allowClearUserData="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="activities.MainActivity"
android:label="#string/app_name" >
</activity>
<activity
android:name="activities.Menu_esq"
android:label="#string/title_activity_menu_esq" >
</activity>
<activity
android:name="activities.BaseActivity"
android:label="#string/title_activity_base" >
</activity>
<activity
android:name="activities.MainView"
android:label="#string/title_activity_main_view" >
</activity>
<activity
android:name="activities.LoginActivity"
android:label="#string/app_name"
android:noHistory="true"
android:windowSoftInputMode="adjustResize|stateVisible" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.moody.LeftActivity"
android:label="#string/title_activity_left" >
</activity>
<activity
android:name="com.example.moody.RightActivity"
android:label="#string/title_activity_right" >
</activity>
<activity
android:name="activities.UserDetailsActivity"
android:label="#string/title_activity_user_details" >
</activity>
<activity
android:name="fragments.TopicsPreview"
android:label="#string/title_activity_copy_of_topics_preview" >
</activity>
<activity android:name="activities.Loading" >
</activity>
<service
android:name=".service.MoodyService"
android:icon="#drawable/ic_launcher"
android:label="#string/moody_service" >
</service>
</application>
service is the package and MoodyService is the class name
My service class
public class MoodyService extends Service {
public MoodyService() {
// TODO Auto-generated constructor stub
}
private boolean isRunning = false;
Object getContent;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
// Announcement about starting
Toast.makeText(this, "Starting the Demo Service", Toast.LENGTH_SHORT)
.show();
// Start a Background thread
isRunning = true;
Thread backgroundThread = new Thread(new BackgroundThread());
backgroundThread.start();
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
// Stop the Background thread
isRunning = false;
// Announcement about stopping
Toast.makeText(this, "Stopping the Demo Service", Toast.LENGTH_SHORT)
.show();
}
private class BackgroundThread implements Runnable {
int counter = 0;
public void run() {
try {
counter = 0;
while (isRunning) {
System.out.println("" + counter++);
new Contents().getAll(getResources(),
getApplicationContext());
Thread.currentThread().sleep(5000);
}
System.out.println("Background Thread is finished.........");
} catch (Exception e) {
e.printStackTrace();
}
}
}
And in my main Intent.
Intent start = new Intent(".service.MoodyService");
this.startService(start);
and also tried
Intent intent = new Intent(this, MoodyService.class);
this.startService(intent);
and tried with the full path
<service
android:name="com.example.moody.service.MoodyService"
android:icon="#drawable/ic_launcher"
android:label="#string/moody_service" >
Solved
I deleted the period in the beginning of the package name in the manifest and it worked, in another words:
This doesn't work:
.yourPackage.YourClass
But this does work:
yourPackage.YourClass
And in the main:
Intent intent = new Intent(this, MoodyService.class);
this.startService(intent);
But it goes against what is written in the documentation:
android:name The name of the Service subclass that implements the service. This should be a fully qualified class name (such as,
"com.example.project.RoomService"). However, as a shorthand, if the
first character of the name is a period (for example, ".RoomService"),
it is appended to the package name specified in the
element. Once you publish your application, you should not change this
name (unless you've set android:exported="false").
There is no default. The name must be specified.
The service must be also be included in the Manifest:
<service android:name="com.x.x.serviceclass"></service>
Make sure you have declared your service in the manifest file.
<service
android:name=".MyService"
android:enabled="true" >
</service>
and try writing getApplicationContext() instead of "this" keyword
startService(new Intent(getApplicationContext(), MoodyService.class));
I don't know why you are using that package-like name for your service name, but why don't you use class name for starting the service?
Intent intent = new Intent(context, YourService.class);
context.startService(intent);
I think in manifest package name for service is wrong as you said your package name is connections so it should be like this
android:name ="connections.MoodyService"
or
android:name="com.example.moody.connections.MoodyService"
to invoke service do
Intent intent = new Intent(this, MoodyService.class);
this.startService(intent);
my service is in "service" package and my manifest service enrty like this;
<service
android:name="service.TimerService"
android:exported="false" >
</service>
Did you create an empty constructor in the service?
If not, try that.
Also uncertain if you can use the Intent like that. You could try the 'new Inten(this, MoodyService.class)' construction.
Did you try to use the android:name that you specified in the Manifest?
Android Manifest:
<service
android:enabled="true"
android:name="UploadService" />
The call would be sth like this:
Intent intent = new Intent("UploadService");
I am having difficulty getting a BroadcastReceiver to process my IntentService response. The service processes multiple different actions and returns an action type. The receiver will never seem to pick it up, however. The intent does get called as I can debug and set a breakpoint in the IntentService and see the action get processed successfully. I just never see the textbox updated with the appropriate data or see the BroadcastReceiver evein being called.
IntentService
protected void onHandleIntent(Intent intent) {
String action = intent.getAction();
// Data the service was called with.
Bundle incomingData = intent.getExtras();
String key = incomingData.getString(KEY_APPKEY);
String secret = incomingData.getString(KEY_SECRET);
String collection = incomingData.getString(KEY_COLLECTION);
CheckinManager cm = new CheckinManager(this.getApplicationContext(),key,secret,collection);
Intent broadcastIntent = new Intent();
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
if (action == ACTION_GET_POI) {
Double lat = incomingData.getDouble(KEY_LATITUDE);
Double lon = incomingData.getDouble(KEY_LONGITUDE);
ArrayList<POI> nearbyPOIs = new ArrayList<POI>();
//broadcastIntent.setAction(ACTION_GET_POI_PROCESSED);
broadcastIntent.setAction("com.msalinger.checkinmanager.CheckinService.getPOIProcessed");
try {
nearbyPOIs = cm.getPOI(lat, lon);
broadcastIntent.putExtra(OUT_KEY_RESULT, true);
broadcastIntent.putExtra(OUT_KEY_ERROR, "");
broadcastIntent.putParcelableArrayListExtra(OUT_KEY_POILIST, nearbyPOIs);
} catch (JSONException ex) {
Log.d(TAG,ex.getMessage() + "\n" + ex.getStackTrace());
broadcastIntent.putExtra(OUT_KEY_RESULT, false);
broadcastIntent.putExtra(OUT_KEY_ERROR, ex.getMessage());
}
}
else if (action == ACTION_CHECK_IN) {
// Do something
}
else if (action == ACTION_GET_CHECKINS) {
// Do Something
}
else if (action == ACTION_FIND_NEARBY_POIS_WITH_CHECKINS) {
// Do Something
}
sendBroadcast(broadcastIntent);
}
Broadcast Receiver as sub-class of Main Activity
public class CheckinReceiver extends BroadcastReceiver {
private final static String INTENT_BASE_URI = "com.msalinger.checkinmanager.CheckinService";
private final static String ACTION_GET_POI_PROCESSED = ".getPOIProcessed";
private final static String ACTION_CHECK_IN_PROCESSED = ".checkInProcessed";
private final static String ACTION_GET_CHECKINS_PROCESSED = ".getCheckinsProcessed";
private final static String ACTION_FIND_NEARBY_POIS_WITH_CHECKINS_PROCESSED = ".findNearbyPOIsWithCheckinsProcessed";
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("com.msalinger.checkinmanager.CheckinService.getPOIProcessed")) {
tv = (TextView)findViewById(R.id.textBox1);
Bundle incomingData = intent.getExtras();
String st = "";
if (incomingData.getBoolean("result")) {
ArrayList<POI> poiList = incomingData.getParcelableArrayList("poList");
st = printPOI(poiList);
}
else {
st = incomingData.getString("error");
}
}
else if (intent.getAction().equals(INTENT_BASE_URI + ACTION_CHECK_IN_PROCESSED)) {
}
else if (intent.getAction().equals(INTENT_BASE_URI + ACTION_GET_CHECKINS_PROCESSED)) {
}
else if (intent.getAction().equals(INTENT_BASE_URI + ACTION_FIND_NEARBY_POIS_WITH_CHECKINS_PROCESSED)) {
}
}
}
Manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.msalinger.checkinmanagerdemo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:enabled="true"
android:name="com.msalinger.checkinmanager.CheckinService" />
<receiver
android:name=".CheckinReceiver">
<intent-filter>
<action android:name="com.msalinger.checkinmanager.CheckinService.getPOIProcessed" />
</intent-filter>
<intent-filter>
<action android:name="com.msalinger.checkinmanager.CheckinService.checkInProcessed" />
</intent-filter>
<intent-filter>
<action android:name="com.msalinger.checkinmanager.CheckinService.getCheckinsProcessed" />
</intent-filter>
<intent-filter>
<action android:name="com.msalinger.checkinmanager.CheckinService.findNearbyPOIsWithCheckinsProcessed" />
</intent-filter>
</receiver>
</application>
</manifest>
What am I doing wrong? Note that the IntentService exists as part of an Android class library with a different package than the Main activity.
Because the receiver exists to update data in the activity, it should be registered when the activity resume and unregistered when the activity pause. And it should not be in the manifest (see the doc for this).
If it's not the case, it shouldn't be a subclass of your activity.
In all cases, I think your Receiver is not called because it has not the right name in the manifest. It may be something like this : .MainActivity$CheckinReceiver.
My English is poor. I cannot start an android service in a boot time and I do not know the problem. I was trying example codes, but without success. Can somebody send me a project in Java that runs? Other code works for other people but on my tablet smartphone emulator it does not work. Does a problem exist in android 4.0?
This is my code:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.service22"
android:versionCode="1"
android:versionName="1.0"
android:installLocation="internalOnly"
>
<supports-screens android:largeScreens="false" android:normalScreens="true" android:smallScreens="false"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application android:icon="#drawable/ic_launcher" android:label="#string/app_name">
<service android:name="com.example.MyService">
<intent-filter>
<action android:name="com.example.MyService">
</action>
</intent-filter>
</service>
<receiver android:name="com.example.MyReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED">
</action>
<category android:name="android.intent.category.HOME">
</category>
</intent-filter>
</receiver>
</application>
</manifest>
public class MyService 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);
for (int i = 0 ; i < 20 ; i++)
{
mensaje();
}
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;
}
public void mensaje()
{
Toast.makeText(this, "Hola", Toast.LENGTH_LONG).show();
}
}
public class MyReceiver extends BroadcastReceiver
{
public MyReceiver()
{
}
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("com.example.MyService");
context.startService(i);
}
}
}
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class OnBootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("OnBootReceiver", "Hi, Mom!");
}
}
and manifest file
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application android:icon="#drawable/cw"
android:label="#string/app_name">
<receiver android:name=".OnBootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
I think:
Intent i = new Intent();
i.setAction("com.example.MyService");
context.startService(i);
is not enough,you must set intent class name like that:
Intent i = new Intent();
i.setClassName("com.example", "com.example.MyService");
i.setAction("com.example.MyService");
context.startService(i);
pls try that.
IMPORTANT: Android OS 3.1+ remains ignorent about your broadcast receivers in following cases:
1.User has never started the application explicitly at least once.
2.User has "force closed" the application.
Issue has nothing to do to your implementation. This is a potential security hole in Android that Google has closed :)