簡體   English   中英

引導設備后服務未啟動

[英]Service not starting after boot device

我在運行服務時遇到問題。 在日志中,看不到該服務正在運行。 所以我不知道她在工作。 Toast也不會顯示在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
    }

}

廣播接收器

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>

您不必驗證意圖類型,因為Receiver僅注冊了一種意圖類型(Intent.ACTION_BOOT_COMPLETED)。 因此,無需檢查接收方的意圖動作是否為Intent.ACTION_BOOT_COMPLETED。 我認為接收器中的條件不正確,因此啟動您的服務的代碼未執行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM