mika
mika

Reputation: 57

Service starts on emulator but on device not

I'am trying to learn how to create services in Android and I've made very simple one. The problem is that is works like a charm on an AVD but on physical device it is not. Simply it not starting on boot...

Have a look at the code:

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.example.myservice" android:versionCode="1" android:versionName="1.0">
  <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
  <application android:icon="@drawable/ic_launcher" android:label="@string/app_name">
        <receiver android:name=".ServiceStarter" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
        <service android:enabled="true" android:name=".MyService" />
  </application>
  <uses-sdk android:minSdkVersion="3" />
</manifest> 

Service starter:

package com.example.myservice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.example.myservice.MyService;

public class ServiceStarter extends BroadcastReceiver {   
    @Override
    public void onReceive(Context context, Intent intent) {  
          if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())){  
           Intent pushIntent = new Intent(context, MyService.class);  
           //pushIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
           context.startService(pushIntent);  
          }  
    }  
}

and service it self:

package com.example.myservice;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service {
    private static final String TAG = "MyService";

    @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");
    }

    @Override
    public void onDestroy() {
        Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onDestroy");
    }

    @Override
    public void onStart(Intent intent, int startid) {
        Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onStart");
    }
}

I'am running it on android 4.0.3

Upvotes: 1

Views: 211

Answers (1)

CommonsWare
CommonsWare

Reputation: 1007554

You need to add an activity to your application, and the user must launch that activity manually first, before your app will function on Android 3.1+. Until that time, your <receiver> will be ignored. I blogged about this ~9 months ago.

Upvotes: 1

Related Questions