2016-06-26 13 views
0

サービスの実行に問題があります。ログには、サービスが実行されていることは表示されません。だから私は彼女が働いているのか分からない。トーストはMainActivityにも表示されません。私は多くの記事を読んでいて、何の仕事もしていません。それを修正するには?起動後にサービスが起動しない

サービス

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

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

    @Override 
    public void onCreate() { 
     super.onCreate(); 
     Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show(); 
     // do something when the service is created 
    } 

} 

BroadcastReceiver

import android.content.Context; 
import android.content.BroadcastReceiver; 
import android.content.Intent; 

public class BootComplete extends BroadcastReceiver { 
    @Override 
    public void onReceive(Context context, Intent intent) { 

     if (intent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED)) { 
      Intent serviceIntent = new Intent(context, AutoStartUp.class); 
      context.startService(serviceIntent); 
     } 

    } 
} 

たManifest.xml

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="kamiszczu.ovh.servicetest3"> 
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" > 
    </uses-permission> 
    <application 
     android:allowBackup="true" 
     android:icon="@mipmap/ic_launcher" 
     android:label="@string/app_name" 
     android:supportsRtl="true" 
     android:theme="@style/AppTheme"> 
     <receiver 
      android:name="kamiszczu.ovh.servicetest3.BootComplete" 
      android:enabled="true" 
      android:exported="false" > 
      <intent-filter> 
       <action android:name="android.intent.action.BOOT_COMPLETED" /> 
      </intent-filter> 
     </receiver> 
     <service 
      android:name="kamiszczu.ovh.servicetest3.AutoStartUp" 
      android:enabled="true"> 
     </service> 
     <activity 
      android:name=".MainActivity" 
      android:label="@string/app_name" 
      android:theme="@style/AppTheme.NoActionBar"> 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 
       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 
    </application> 
</manifest> 

答えて

1

あなたがする必要はありません レシーバが1つのインテントタイプ(Intent.ACTION_BOOT_COMPLETED)のみで登録されているため、インテントタイプを確認してください。インテントアクションがIntent.ACTION_BOOT_COMPLETEDである場合、レシーバをチェックインする必要はありません。 私は受信機の状態が真ではないと思うので、あなたのサービスを開始するコードは実行されません。

+0

もっと明瞭に書くことができますか? – kamiszczu

+0

私の回答を編集しました – user3215142

+0

あなたは正しいです。私はACTION_POWER_CONNECTEDに変更し、Toastを表示します。 – kamiszczu

関連する問題