简体   繁体   中英

Nothing happens on service call

I created a fresh new simple project (on Android Studio 0.8.2) to test Service, but not sure why is it not working.

MyActivity.java

import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class MyActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my);

    startService(new Intent(this, TestService.class));
}

TestService.java

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

public class TestService extends Service {
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onCreate() {
    super.onCreate();
    // do something when the service is created
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // TODO Auto-generated method stub
    super.onStartCommand(intent, flags, startId);

    return START_REDELIVER_INTENT;
}
}

I also have added in AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android"     
package="..." >         
<application         ...     
</application>     
<service         
android:name=".TestService">
</service> 
</manifest>

By right, base on these, the service should start upon run/debug, but nothing happened. I placed a breakpoint at onStartCommand, but it didn't reach it. Please help. Is it because I set the minSDK = 8? My older projects has service working though.

You've declared <service android:name=".TestService"> outside of the <application> element. It's supposed to go inside with the rest of your components:

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="..." >         
    <application     
        <service         
            android:name=".TestService">
        </service> 
        ...
    </application>     
</manifest>

The build in Eclipse fails if the AndroidManifest.xml is invalid; doesn't Android Studio complain about it?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM