tags:

views:

657

answers:

2

hi..

i am starting a service using startService(Intent intent) method. When i call this function it reaches to the onCreate of service but it is unable to call onStartCommand. Here is my code--

@Override
public void onReceive(Context context, Intent intent) {
    // Send a text notification to the screen.
    Log.e("mudit", "Action: " + intent.getAction());

    try {
        ConnectivityManager connManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connManager.getActiveNetworkInfo();
        Log.e("mudit", "getType: " + info.getType());
        Log.e("mudit", "isConnected: " + info.isConnected());
        if (info.isConnected()) {

            Intent newinIntent = new Intent(context, service.class);
            context.startService(newinIntent);
        }

    } catch (Exception e) {
        e.printStackTrace();
        Intent newinIntent = new Intent(context, service.class);
        context.stopService(newinIntent);

    }

}

Service Code --

package com.android.service;

import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.widget.Toast;

public class service extends Service {

@Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public void onCreate() {
    super.onCreate();
    Toast.makeText(this, "Service created...", Toast.LENGTH_LONG).show();
}

@Override
public void onDestroy() {
    super.onDestroy();
    Toast.makeText(this, "Service destroyed ...", Toast.LENGTH_LONG).show();
}

public int onStartCommand(Intent intent, int flags, int startId) {

    Toast.makeText(this, "onStartCommand...", Toast.LENGTH_LONG).show();
    return 1;
}

}

Manifest.xml --

<receiver class=".AReceiver" android:name=".AReceiver">
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        </intent-filter>
    </receiver>
    <service class=".service" android:name=".service"
        android:enabled="true" android:icon="@drawable/icon">
    </service>

Please suggest what i am doing wrong????

+2  A: 

onStartCommand(..) is not a Service life cycle method while public void onStart(Intent intent, int startId) is. @Override annotation would make it clear.

alex
That's not correct, onStart has been deprecated in favor of onStartCommand:http://developer.android.com/reference/android/app/Service.html
Klondike
A: 

First you should add @Override before onStartCommand(..) then make sure that the target for the Android project is higher than 2.0 .

Fevos