我有一个Service类,它是一个从java客户端接收数据的服务器,我能够检索数据但是当我试图将数据从服务广播到MainActivity时,sendBroadcast(intent)给出了一个服务中的NPE并且它没有广播消息..我查看了几个答案,但我无法弄清楚问题..所以我发布了这个问题.. 以下是我的服务部分
public class Service_ extends Service implements Runnable {
BroadcastReceiver broadcaster;
Intent intent;
static final public String BROADCAST_ACTION = "com.mes.broadcast";
private static ServerSocket server;
private static int port = 9800;
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.d("sri", "onCreate---->Service");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("sri","onStartCommand(Intent intent, int flags, int startId)---->Service");
Service_ s = new Service_();
Thread t = new Thread(s);
Log.d("sri","going to start thread---->Service");
t.start();
return super.onStartCommand(intent, flags, startId);
}
@Override
public void run() {
Log.d("sri","run()---->Service");
try {
}catch(Exception e){
// code to connect to java client .......it works fine and also obtained data ..I WANTED THIS DATA TO BE SENT TO THE ACTIVITY
intent = new Intent(BROADCAST_ACTION);Log.d("sri","sendResult----->putExtra");
intent.putExtra("message", message);
Log.d("sri", "sendResult---->SendBroadcast");
sendBroadcast(intent);//THIS LINE GIVES ME NPE LINE:109
}}
我的Stacktrace是
E/AndroidRuntime: FATAL EXCEPTION: Thread-11724
java.lang.NullPointerException
atandroid.content.ContextWrapper.sendBroadcast(ContextWrapper.java:338)
at airhost.server_client_service_.Service_.run(Service_.java:109)
at java.lang.Thread.run(Thread.java:838)
我的主要活动
//imports....
public class MainActivity extends AppCompatActivity {
TextView result;
Button button;
BroadcastReceiver receiver;
Intent serviceIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView) findViewById(R.id.textView);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
serviceIntent = new Intent(getApplicationContext(),
Service_.class);
Log.d("sri", "onResume-->startService-----> Activity");
startService(serviceIntent);
}
});
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("sri", "BroadcastReceiver-->onReceive-----> Activity");
String message = intent.getStringExtra("message");
result.setText(message);
}
};
}
protected void onResume() {
super.onResume();
Log.d("sri", "onResume-->registerReceiver-----> Activity");
registerReceiver(receiver, new IntentFilter(
Service_.BROADCAST_ACTION));
}
@Override
protected void onPause() {
super.onPause();
Log.d("sri", "onPause-------> Activity");
stopService(serviceIntent);
unregisterReceiver(receiver);
}
}