【发布时间】:2015-05-01 11:07:27
【问题描述】:
我正在创建一个已启动的服务,但没有通过广播接收到通信。我怀疑 IntentFilter 和名称有问题,但一切似乎都是正确的。
我一直在研究 vogella 的示例(第 8 段)
我做错了什么? 为什么 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>
【问题讨论】:
-
从哪里开始服务?
-
不要使用 Toast 来调试应用程序。使用log看看有没有打印出来
-
你怎么知道
onReceive()没有被调用? -
@DavidWasser 我已经在 onResponse 函数中烤了一个字符串,但从未见过它
-
Toast 不是一种可靠的调试方法。请在调试器中添加日志记录或设置断点。
标签: java android android-intent android-service