Android:Service as Subclass如何启动?

时间:2016-05-05 09:26:21

标签: android service

在MainActivity中,我为服务创建了一个子类。服务没有启动,我很确定它是因为清单文件。我尝试了几种方法,但它不起作用。有任何想法吗?

MainActivity

public class MainActivity extends AppCompatActivity {

private EditText editTextUsername;
private SharedPreferences savepoint;
private SharedPreferences.Editor editor;
private String sUsername;

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

    /**
     * Speicher und Savepoint username initialisieren
     */
    savepoint = getSharedPreferences("Data", Context.MODE_PRIVATE);
    editor = savepoint.edit();

    /**
     * Username einrichten
     */
    editTextUsername = (EditText) findViewById(R.id.editTextUsername);
    editTextUsername.setText(savepoint.getString("username","Username"));
    sUsername = editTextUsername.getText().toString();

    /**
     * Position laden und hochladen
     */
    Intent locationService2 = new Intent(MainActivity.this, LocationService2.class);
    startService(locationService2);
}

public class LocationService2 extends IntentService {

    public LocationService2() {
        super("My Thread");
    }

    @Override
    protected void onHandleIntent(Intent intent) {

        new Location2(MainActivity.this, sUsername);

    }
}

清单

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme">

    <activity
        android:name=".MainActivity"
        android:label="@string/app_name">
        <service android:enabled="true" android:name="ch.web2page.stefano.trackme.MainActivity.LocationService2" />
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

    </activity>

</application>

2 个答案:

答案 0 :(得分:1)

您是否尝试在清单中注册活动标记以外的服务:

<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>

<service android:enabled="true" android:name="ch.web2page.stefano.trackme.MainActivity.LocationService2" />

答案 1 :(得分:0)

在具体实现中,您必须声明一个默认构造函数,该构造函数调用您扩展的抽象IntentService类的公共IntentService(String name)超级构造函数:

public MyService () {
  super("YourService");
}