将数据从活动发送到前台服务 [英] Sending data from activity to foreground service

查看:64
本文介绍了将数据从活动发送到前台服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过蓝牙从微控制器接收数据.这些数据不断发送到应用程序,我正在使用前台服务在后台实现此线程.

I am receiving data from a microcontroller via Bluetooth in an activity. This data is continuously sent to the app and I am using a foreground service to implement this thread in the background.

在MainActivity4中接收到数据,然后将意图与接收到的数据一起发送到前台服务类,然后将其重定向到MainActivity5,并在其中进行图形化处理.

Data is received in MainActivity4, the an intent is sent to a foreground service class with the data received which then redirects the data to MainActivity5 where it will be graphed.

我不确定如何正确实现发送给MainActivity4的意图,因为前台服务正在不断处理数据,但并没有将其不断重定向到MainActivity5.意图第一次使屏幕转到MainActivity5,这很好,但是没有发送和更新数据.

I am not sure how to implement the intent properly that is sent to the MainActivity4 because the data is continuously being processed by the foreground service but is not redirecting it constantly to MainActivity5. The first time the intent makes the screen go to the MainActivity5 which is good but the data is not being sent and updated.

这是MainActivity4中的代码:

Here is the code in MainActivity4:

@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
        super.onCharacteristicChanged(gatt, characteristic);

        String value = String.valueOf(characteristic.getValue());
        Intent serviceIntent = new Intent(MainActivity4.this, ForegroundService.class);
        serviceIntent.putExtra("inputExtra", value);
        ContextCompat.startForegroundService(MainActivity4.this, serviceIntent);
}

这是ForegroundService中的代码:

Here is the code in the ForegroundService:

public class ForegroundService extends Service {

//private static final int ID_SERVICE = 101;
public static final String CHANNEL_ID = "ForegroundServiceChannel";

@Override
public void onCreate(){
    super.onCreate();

    createNotificationChannel();
    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("Foreground Service")
            .setContentIntent(pendingIntent)
            .build();

    startForeground(1, notification);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    //super.onStartCommand(intent, flags, startId);

    String input = intent.getStringExtra("inputExtra");
    Log.i("Tag", input);
    sendData(input);

    createNotificationChannel();
    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this,
            0, notificationIntent, 0);
    Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("Foreground Service")
            .setContentText(input)
            .setContentIntent(pendingIntent)
            .build();
    startForeground(1, notification);
    //do heavy work on a background thread
    //stopSelf();
    return START_NOT_STICKY;
    //return START_REDELIVER_INTENT;
}
@Override
public void onDestroy() {
    super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent)
{
        return null;
}

private void sendData(String input){
    Log.i("Tag", "inside sendData");
    Intent intent2 = new Intent(ForegroundService.this, MainActivity5.class);
    intent2.putExtra("inputExtra", input);
    intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    //intent2.setFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
    //intent2.putExtra("inputExtra", input);
    startActivity(intent2);
}

private void createNotificationChannel() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel serviceChannel = new NotificationChannel(CHANNEL_ID, "Foreground Service Channel", NotificationManager.IMPORTANCE_DEFAULT);
        NotificationManager manager = getSystemService(NotificationManager.class);
        manager.createNotificationChannel(serviceChannel);
    }
}
}

这是MainActivity5中的代码:

Here is the code in the MainActivity5:

Intent intent = getIntent();
    String data = intent.getStringExtra("inputString");
    Log.i(TAG, "data sending");
    dataText = (TextView) findViewById(R.id.data2);
    dataText.setText(data);

我如何能够连续接收MainActivity5中的数据?也许Intent设置标志是我弄错了.数据在后台接收,并发送到前台服务,但不发送到其他活动,尽管在运行代码时该活动的屏幕会自动打开.任何帮助和建议,将不胜感激.谢谢

How am I able to receive the data in the MainActivity5 continuously? Perhaps the Intent set flags is what I am getting wrong. The data is received in the background and is sent to the foreground service but not to the other activity despite that activity's screen is automatically opened when the code is run. Any help and advice would be appreciated. Thanks

***这是对到目前为止我在Foreground Service类中具有的功能的更新:

*** Here is an update to what I have so far a function in Foreground Service class:

private void sendData(String input){
    Log.i("Tag", "inside sendData");
    Intent intent = new Intent();
    intent.setAction("com.example.Pillwoah.sendbroadcast");
    intent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
    intent.putExtra("inputExtra", input);
    sendBroadcast(intent);
}

***这是到目前为止我在MainActivity5中具有的功能的更新:

*** Here is an update to what I have so far a function in MainActivity5:

public class MainActivity5 extends AppCompatActivity {

protected static final String TAG = "TAG";

TextView dataText;

BroadcastReceiver receiver;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main5);

    GraphView move = (GraphView) findViewById(R.id.move);
    GraphView sound = (GraphView) findViewById(R.id.sound);

    LineGraphSeries<DataPoint> series = new LineGraphSeries<>(new DataPoint[] {
            new DataPoint(0, 1),
            new DataPoint(1, 5),
            new DataPoint(2, 3),
            new DataPoint(3, 2),
            new DataPoint(4, 6)
    });
    move.addSeries(series);
    series.setColor(Color.GREEN);
    series.setDrawDataPoints(true);
    series.setAnimated(true);
    series.setDrawBackground(true);

    move.setTitle("Movement");
    move.setTitleTextSize(90);
    move.setTitleColor(Color.WHITE);

    LineGraphSeries<DataPoint> series2 = new LineGraphSeries<>(new DataPoint[] {
            new DataPoint(0, 1),
            new DataPoint(1, 5),
            new DataPoint(2, 4),
            new DataPoint(3, 9),
            new DataPoint(4, 6)
    });
    sound.addSeries(series);
    series2.setColor(Color.YELLOW);
    series2.setDrawDataPoints(true);
    series2.setAnimated(true);
    series2.setDrawBackground(true);

    sound.setTitle("Sound");
    sound.setTitleTextSize(90);
    sound.setTitleColor(Color.WHITE);

    Log.i(TAG, "data sending");
    configureReceiver();
}
class DataBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String message = "Broadcast intent detected " + intent.getAction();
        Log.i(TAG, message);
    }
}

private void configureReceiver(){
    IntentFilter filter = new IntentFilter();
    filter.addAction("com.example.Pillwoah.sendbroadcast");
    receiver = new DataBroadcastReceiver();
    registerReceiver(receiver, filter);
}

}

我没有收到任何错误,但是我知道我缺少一些功能.如果有人能看到我想念的东西,那就太好了.

I am getting no errors but I know that I am missing some bit of functionality. If anyone could see what I am missing that would be great.

推荐答案

有一个带有广播接收器的示例

There is a sample with broadcast receiver

class MainActivity : Activity() {
    companion object {
        const val ACTION_DATA = "package.your.app.DATA"
        private val filters = arrayOf(ACTION_DATA)
        private val intentFilter: IntentFilter by lazy {
            IntentFilter().apply {
                filters.forEach { addAction(it) }
            }
        }

    }
    inner class DataBroadcastReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            when (intent.action) {
                ACTION_DATA -> showData(intent)
            }
        }
    }

    fun showData(intent: Intent) {
        //TODO extract data from intent
    }

    private lateinit var broadcastReceiver: MainActivity.DataBroadcastReceiver

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        broadcastReceiver = DataBroadcastReceiver()
        applicationContext.registerReceiver(broadcastReceiver, intentFilter)
    }

    override fun onDestroy() {
        super.onDestroy()
        applicationContext.unregisterReceiver(broadcastReceiver)
    }
}

class ForegroundService: Service() {
    ...
    private fun sendData(input: String) {
        Intent().run {
            action = MainActivity.ACTION_DATA
            putExtra("inputExtra", input)
            applicationContext.sendBroadcast(this)
        }
    }
    ...
}

这篇关于将数据从活动发送到前台服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆