public class MainActivity extends Activity implements SurfaceHolder.Callback
{
private Intent intent;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (activityReceiver != null)
{
IntentFilter intentFilter = new IntentFilter();
registerReceiver(activityReceiver, intentFilter);
}
intent = new Intent(this, Service.class);
startService(intent);
}
private BroadcastReceiver activityReceiver = new BroadcastReceiver(){
public void onReceive(Context context, Intent intent) {
int value=intent.getIntExtra("VALUE", 0);
txtData.setText(""+value);
}}
}
服务
public class Service extends IOIOService {
//Intent intent=new Intent(this, MainActivity.class);
private final int BUTTON_PIN = 34;
@Override
protected IOIOLooper createIOIOLooper() {
return new BaseIOIOLooper() {
private DigitalOutput led_;
private DigitalInput mButton;
int oneTime = 0;
@Override
protected void setup() throws ConnectionLostException,
InterruptedException {
led_ = ioio_.openDigitalOutput(IOIO.LED_PIN);
mButton = ioio_.openDigitalInput(BUTTON_PIN, DigitalInput.Spec.Mode.PULL_UP);
}
@Override
public void loop() throws ConnectionLostException,
InterruptedException {
final boolean reading1 = mButton.read();
if (reading1)
{
led_.write(false);
if(oneTime == 0)
{
Intent intent = new Intent();
intent.putExtra("VALUE", 100);
sendBroadcast(intent);
oneTime = 1;
}
}
else
{
led_.write(true);
}
Thread.sleep(100);
}
};
}
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (intent != null && intent.getAction() != null
&& intent.getAction().equals("stop")) {
// User clicked the notification. Need to stop the service.
nm.cancel(0);
stopSelf();
} else
{
// Service starting. Create a notification.
Notification notification = new Notification(
R.drawable.ic_launcher, "IOIO service running",
System.currentTimeMillis());
notification
.setLatestEventInfo(this, "IOIO Service", "Click to stop",
PendingIntent.getService(this, 0, new Intent(
"stop", null, this, this.getClass()), 0));
notification.flags |= Notification.FLAG_ONGOING_EVENT;
nm.notify(0, notification);
}
}
@Override
public IBinder onBind(Intent arg0) {
return(null);
}
我正在尝试使用广播将整数值从服务发送到活动,并将该整数显示到活动中的文本框中。这是一件简单的事情,但我的程序仍然崩溃。这是我的代码的一部分,我在其中添加了广播代码。谁能告诉我这有什么问题?还有什么要补充的吗?