【问题标题】:How send and receive string among activity an service in Android如何在Android中的服务活动之间发送和接收字符串
【发布时间】:2014-05-06 15:42:30
【问题描述】:

在我的应用程序中,我使用连接到指定设备并以字符串形式接收一些数据的服务。

当它得到一些特殊字符串时,它会向用户抛出一个通知。

当用户点击通知时,它会将他带到一个新活动,其中显示从蓝牙接收到的值。我想要做的是用从蓝牙接收到的值更新 textView。

我在网上查了一下,发现我最好的方法是 BroadcastReceiver。我在 onCreate 中有这个处理程序,它处理从蓝牙接收到的消息。我想要做的是当我收到一个新字符串以将其传递给我的活动时:

 mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 1) {
                    connectStat = true;
                }else if(msg.what == MESSAGE_RECEIVE){
                    byte[] readBuf = (byte[]) msg.obj; 
                    String strIncom = new String(readBuf, 0, msg.arg1);
                     sb.append(strIncom); 
                     int endOfLineIndex = sb.indexOf("/");
                     if (endOfLineIndex > 0) {
                         String sbprint = sb.substring(0, endOfLineIndex);
                         Intent in = new Intent();
                         in.setAction(BROADCAST_ACTION);
                         in.putExtra(AlarmService.CO_CONSENTRATION_NUMBER, sbprint);
                         sendBroadcast(in);
                         if(sbprint.equals("4")){
                             NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                             notificationManager.cancel(9999);
                             Notification notification = new Notification(R.drawable.gasmask, "New Message", System.currentTimeMillis());
                             notification.when = System.currentTimeMillis();
                             Intent notificationIntent = new Intent(AlarmService.this, ActivityCOConsentration.class);
                             String value = sbprint;
                             notificationIntent.putExtra(AlarmService.CO_CONSENTRATION_NUMBER, value);
                             notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                             PendingIntent pendingIntent = PendingIntent.getActivity(AlarmService.this, 0,notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                             notification.flags |= Notification.FLAG_AUTO_CANCEL;
                             notification.setLatestEventInfo(AlarmService.this, "Alarming CO level", "Level of CO is alarming. Take action.", pendingIntent);
                             notificationManager.notify(9999, notification);
                             myclip.start();
                             sb.delete(0, sb.length());
                         }else if(sbprint.equals("8")){
                             NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                             notificationManager.cancel(9999);
                             Notification notification = new Notification(R.drawable.gasmask, "New Message", System.currentTimeMillis());
                             notification.when = System.currentTimeMillis();
                             Intent notificationIntent = new Intent(AlarmService.this, ActivityCOConsentration.class);
                             String value = "8";
                             notificationIntent.putExtra(AlarmService.CO_CONSENTRATION_NUMBER, value);
                             notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                             PendingIntent pendingIntent = PendingIntent.getActivity(AlarmService.this, 0,notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                             notification.flags |= Notification.FLAG_AUTO_CANCEL;
                             notification.setLatestEventInfo(AlarmService.this, "Alarming CO level", "Level of CO is life endagering. Sending out SOS sms.", pendingIntent);
                             notificationManager.notify(9999, notification);
                             myclip.start();
                             disconnect();
                             try {
                                TimeUnit.SECONDS.sleep(3);
                            } catch (InterruptedException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                             sb.delete(0, sb.length());
                         }            
                     }
                }
            }
        };

这是我应该接收数据的活动:

public class ActivityCOConsentration extends Activity{
private TextView co_concentration;
private MyReceiver mMyReceiver;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_activity_coconsentration);
    co_concentration = (TextView) findViewById(R.id.co_number);
    onNewIntent(getIntent());
    mMyReceiver = new MyReceiver();
    registerIntents();

}

public void onNewIntent(Intent intent){
    Bundle extras = intent.getExtras();
    String covalue = extras.getString(AlarmService.CO_CONSENTRATION_NUMBER);
    co_concentration.setText(covalue);
    if(covalue.equals("8")){
        Intent i = new Intent(this, AlarmService.class);
        stopService(i);
    }
}
private void registerIntents(){
    IntentFilter filter = new IntentFilter();
    filter.addAction(AlarmService.BROADCAST_ACTION);
    getApplicationContext().registerReceiver(mMyReceiver, filter);
}

public class MyReceiver extends BroadcastReceiver {

       @Override
       public void onReceive(Context context, Intent intent) {
              if (intent.getAction().equalsIgnoreCase(AlarmService.BROADCAST_ACTION)) {

                String v = intent.getExtras().getString(AlarmService.CO_CONSENTRATION_NUMBER);
                co_concentration.setText(v);
              }

       }

}

public void onDestroy(){
    super.onDestroy();
    stopService(new Intent(AlarmService.ALARM_SERVICE));
    getApplicationContext().unregisterReceiver(mMyReceiver);

}

} 发生的情况是我只得到一个新字符串,然后什么都没有。

任何帮助都会非常有用。

【问题讨论】:

  • 您的意思是在 MyReceiver 上没有发送或接收广播消息吗?

标签: android service android-activity broadcastreceiver


【解决方案1】:

在班级ActivityCOConsentration

您必须按如下方式过滤广播动作(在 onCreate 之后调用 registerInetents() 并记住在销毁之前取消注册(getApplicationcontext().unregisterReceiver(receiver);):

private void registerIntents() {
    IntentFilter filter = new IntentFilter();

    filter.addAction(BROADCAST_ACTION);

    getApplicationcontext().registerReceiver(receiver, filter);
}

并用作接收器:

public class MyReceiver extends BroadcastReceiver {

           @Override
           public void onReceive(Context context, Intent intent) {
              if (intent.getAction().equalsIgnoreCase(AlarmService.BROADCAST_ACTION)) {

                String v = intent.getExtras().getString(CO_CONSENTRATION_NUMBER);
                co_concentration.setText(v);
             }
           }

}

【讨论】:

  • 你能看看这个新问题吗?再次感谢您的宝贵时间。
猜你喜欢
  • 1970-01-01
  • 2017-08-24
  • 1970-01-01
  • 2016-01-29
  • 1970-01-01
  • 2017-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多