2017-09-27 167 views
0

我對Android仍然陌生,正在努力教我如何使用Intent Service在非UI線程上工作。但是,當我致電意向服務時,似乎沒有任何事情發生。Android意圖服務不被稱爲

這裏是MainActivity的意圖服務調用

startIntentService = (Button) findViewById(R.id.button4); 
startIntentService.setOnClickListener(new View.OnClickListener() 
{ 
    @Override 
    public void onClick (View v){ 
     Intent delayIntent = new Intent(getApplicationContext(), 
     DelayIntentService.class); 
     startService(delayIntent); 

這裏是DelayIntentService代碼

public class DelayIntentService extends IntentService { 
    public static final String ACTION_DELAY = 
      "hinz.don.hour5.action.DELAY"; 
    public static final String EXTRA_MESSAGE = 
      "hinz.don.hour5.extra.MESSAGE"; 
    public DelayIntentService() { 
     super("DelayIntentService"); 
    } 

    @Override 
    protected void onHandleIntent (Intent intent){ 
     SystemClock.sleep(5000); 
     Intent broadcastIntent = new Intent(); 
     broadcastIntent.setAction(ACTION_DELAY); 
     broadcastIntent.putExtra(EXTRA_MESSAGE, "UPDATED USING INTENT SERVICE"); 
     sendBroadcast(broadcastIntent); 

,這裏是從清單文件中的服務聲明:

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="hinz.don.hour5"> 

    <service android:name="hinz.don.Hour5.DelayIntentService"></service> 

我在Intent Service代碼中放置了一個調試中斷,但它從不執行它

+0

設置startService斷點在MainActivity,它打破呢?當你點擊按鈕(R.id.button4) – chornge

+0

時,它應該在那裏突然出現,還有一個錯字,你的清單中你的包名稱與完整的服務名稱不匹配 - 在這裏有一個大寫的H(Hour5)全服務名稱。 – chornge

回答

0

在您的代碼中,存在與package =「hinz.don.hour5」和「hinz.don.Hour5.DelayIntentService」的未命中匹配。用作hours5的包和用作Hours5的服務名稱。 最好使用此 <service android:name=".DelayIntentService" /> 這將消除歧義

0

需要在清單文件的底部的主要活動聲明之後放置的服務聲明。一旦我移動它一切正常。

0

你的XML應該是這樣

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="hinz.don.hour5"> 
<applcation .......> 

    <service android:name="hinz.don.hour5.DelayIntentService"></service> 
</application> 

如果這行不通 指

https://stackoverflow.com/a/15772151/8416317