在service中启动线程,使用localbroadcastmanager传递消息无效
启动服务后,启动一个线程,定时使用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");
}
}
}
}