在service中启动线程,使用localbroadcastmanager传递消息无效

Fangyuanshan 2018-05-18 05:34:13
启动服务后,启动一个线程,定时使用localbroadcastmanager向service发送消息,但service却一直收不到消息,不知何故。
类似的使用方式在activity中没有问题。
代码如下:
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

public class LoginService extends Service {

private LocalBroadcastManager localBroadCast1 = null;
private LocalBroadcastReceiver mReceiver1 = null;
private IntentFilter intentFilter1 ;
private LoginThread thr = null;
@Override
public void onCreate() {
super.onCreate();

localBroadCast1 = LocalBroadcastManager.getInstance(LoginService.this);
mReceiver1 = new LoginService.LocalBroadcastReceiver();
intentFilter1 = new IntentFilter("KeepLive");
localBroadCast1.registerReceiver(mReceiver1,intentFilter1);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

if(thr == null)
{
String username = intent.getStringExtra("UserName");
String password = intent.getStringExtra("Password");
thr = new LoginThread();
thr.run();
}

return super.onStartCommand(intent, flags, startId);
}

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

@Override
public void onDestroy() {
thr.exit = true;
try {
thr.join(1000);
} catch (InterruptedException e) {
}
super.onDestroy();
}

public class LocalBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction() ;
if ( "KeepLive".equals( action )){
Log.d("MSG=",intent.getStringExtra("MSG"));
}
}
}

public class LoginThread extends Thread {
private boolean exit = false;
public void run(){
while(!exit)
{
try{
Thread.sleep(1000);
}catch(InterruptedException e){

}
//发送消息
Intent intent = new Intent("KeepLive");
intent.putExtra("MSG","i am alive");
localBroadCast1.sendBroadcast(intent);
Log.d("adb=","broadcast msg");
}
}
}

}
...全文
598 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
Fangyuanshan 2018-05-19
  • 打赏
  • 举报
回复
补充说明:期望在onReceive函数收到并处理消息,但实际上调试时,一直没有收到消息。
Fangyuanshan 2018-05-19
  • 打赏
  • 举报
回复
问题解决了,代码里愚蠢的吧thr.start 写成了thr.run

80,351

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧