服务不与活动通信

时间:2015-05-01 11:07:28

标签: java android android-intent android-service

我正在创建一个已启动但未通过广播接收通信的服务。我怀疑IntentFilter和名称有问题,但这一切似乎都是正确的。

我一直在研究vogella(第8段)

的例子

我做错了什么? 为什么MainActivity不接收广播?

MainActivity

package com.jackslastssid;

import ...

public class MainActivity extends ActionBarActivity {

    class MainActivityAfterCaller extends AfterCaller {
        public void callback() {
            update_something();
        }
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(MainActivity.this, "Daemon called back! :)", Toast.LENGTH_LONG).show(); // never happend
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(receiver, new IntentFilter(SayHelloDaemon.NOTIFICATION));
    }
    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(receiver);
    }
}

SayHelloDaemon:

public class SayHelloDaemon extends IntentService {

    public static final String NOTIFICATION = "com.jackslastssid.SayHelloDaemon";

    public SayHelloDaemon() {
        super("SayHelloDaemon");
    }

    class SayHelloDaemonAfterCaller extends AfterCaller {
        public void callback() {
            Intent intent = new Intent(NOTIFICATION);
            sendBroadcast(intent);
        }
    }
    // will be called asynchronously by Android
    @Override
    protected void onHandleIntent(Intent intent) {
        new SayHelloAsyncTask().execute(new Pair<AfterCaller, Map>(new SayHelloDaemonAfterCaller(), Data.getInstance().getQueryMap()));
    }
}

AndroidManifest:

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

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

    <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" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name=".SayHelloDaemon"
            android:icon="@drawable/icon"
            android:label="@string/service_name"
            android:exported="false"/>

    </application>

</manifest>

1 个答案:

答案 0 :(得分:0)

看起来您尚未在活动中启动该服务。

Intent intent = new Intent(this, SayHelloDaemon.class);
startService(intent);