Android服务对意图没有反应

时间:2013-12-12 20:05:38

标签: android android-intent service

我正在尝试使用LocalBroadcastManager和BroadcastReceiver进行第一次服务。服务启动但它对发送给它的意图没有反应。真的我不知道出了什么问题我已经尽力了。

这是我用意图

开始服务的方式
Intent i = new Intent(this, VikimgService.class);
    i.setAction(VikimgService.ACTION);
    startService(i);

清单中的注释

<service android:name="pl.alemac.vikimg.service.VikimgService" />

我的服务

public class VikimgService extends Service {

public static final String ACTION = "pl.alemac.vikimg.service.VikimgService.action";
public static final String REACTION = "pl.alemac.vikimg.service.VikimgService.reaction";
public static final String REREACTION = "pl.alemac.vikimg.service.VikimgService.rereaction";

private String user;
private Looper sServiceLooper;
private ServiceHandler sServiceHandler;
private long mHandlerThreadId;

private class ServiceHandler extends Handler {
    public ServiceHandler(Looper looper) {
        super(looper);
    }

    @Override
    public void handleMessage(android.os.Message msg) {
        onHandleIntent((Intent) msg.obj, msg.arg1);
    }
}

void onHandleIntent(final Intent intent, int id) {
    if (Thread.currentThread().getId() != mHandlerThreadId) {
        throw new IllegalThreadStateException();
    }
    String test = intent.getAction();
    if (test.equals(ACTION)) {
        Log.d("test", "onHandleIntent called ACTION");
        Intent in = new Intent();
        in.setAction(REACTION);
        in.putExtra("user", user);
        Log.d("test", "sending broadcast REACTION");
        LocalBroadcastManager.getInstance(this).sendBroadcast(in);
    }
}

@Override
public void onCreate() {
    super.onCreate();
    user = "test333";

    HandlerThread thread = new HandlerThread("pl.alemac.vikimg.service.VikimgService");
    thread.start();
    mHandlerThreadId = thread.getId();
    sServiceLooper = thread.getLooper();
    sServiceHandler = new ServiceHandler(sServiceLooper);

}

public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
    return START_STICKY;
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onDestroy() {
    super.onDestroy();
    Log.e("test", "service destroyed");
}}

提前致谢!


将onStartCommand方法更改为粘贴在下面后,我实现了我想要做的事情 - 服务和活动之间存在沟通,我不知道它是否是完美的解决方案但是它有效。

此主题的有趣方法发布在此处 - &gt; Register a broadcast receiver from a service in a new thread

public int onStartCommand(Intent intent, int flags, int startId) {
String test = intent.getAction();
if (test.equals(ACTION)) {
    Log.d("test", "onHandleIntent called ACTION");
    Intent in = new Intent();
    in.setAction(REACTION);
    in.putExtra("user", user);
    Log.d("test", "sending broadcast REACTION");
    LocalBroadcastManager.getInstance(this).sendBroadcast(in);
}
return START_STICKY;

}

1 个答案:

答案 0 :(得分:0)

方法onHandleIntent仅适用于IntentService,您正在扩展Service