Java 将数据从活动发送到前台服务

Java 将数据从活动发送到前台服务,java,android-studio,android-intent,android-activity,android-service,Java,Android Studio,Android Intent,Android Activity,Android Service,我在活动中通过蓝牙从微控制器接收数据。这些数据被连续发送到应用程序,我正在使用前台服务在后台实现这个线程 数据在MainActivity4中接收,意图与接收到的数据一起发送到前台服务类,然后前台服务类将数据重定向到MainActivity5,并在那里对其进行图形化 我不知道如何正确地实现发送到MainActivity4的意图,因为前台服务正在不断地处理数据,但没有不断地将其重定向到MainActivity5。第一次意图使屏幕转到MainActivity5,这很好,但数据没有被发送和更新 以下是M

我在活动中通过蓝牙从微控制器接收数据。这些数据被连续发送到应用程序,我正在使用前台服务在后台实现这个线程

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

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

以下是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中的代码:

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中的代码:

Intent intent = getIntent();
    String data = intent.getStringExtra("inputString");
    Log.i(TAG, "data sending");
    dataText = (TextView) findViewById(R.id.data2);
    dataText.setText(data);
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);
}

}
我如何能够连续接收Main Activity 5中的数据?也许意图设置标志是我错的地方。数据在后台接收,并发送到前台服务,但不发送到其他活动,尽管该活动的屏幕在代码运行时自动打开。任何帮助和建议都将不胜感激。谢谢

***以下是我目前在前台服务类中拥有的函数的更新:

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中拥有的功能的更新:

Intent intent = getIntent();
    String data = intent.getStringExtra("inputString");
    Log.i(TAG, "data sending");
    dataText = (TextView) findViewById(R.id.data2);
    dataText.setText(data);
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);
}

}
公共类MainActivity5扩展了AppCompatActivity{
受保护的静态最终字符串TAG=“TAG”;
文本视图数据文本;
广播接收机;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main5);
GraphView-move=(GraphView)findViewById(R.id.move);
GraphView声音=(GraphView)FindView声音id(R.id.sound);
LineGraphSeries=新的LineGraphSeries(新数据点[]){
新数据点(0,1),
新数据点(1,5),
新数据点(2,3),
新数据点(3,2),
新数据点(4,6)
});
move.addSeries(系列);
系列。设置颜色(颜色。绿色);
series.setDrawDataPoints(真);
系列。设置动画(真);
系列。设置牵引杆接地(真实);
移动。设置标题(“移动”);
move.setTitleTextSize(90);
move.setTitleColor(Color.WHITE);
LineGraphSeries系列2=新的LineGraphSeries(新数据点[]){
新数据点(0,1),
新数据点(1,5),
新数据点(2,4),
新数据点(3,9),
新数据点(4,6)
});
声音。添加系列(系列);
系列2.setColor(颜色为黄色);
序列2.setDrawDataPoints(真);
序列2.设置动画(真);
系列2.设置牵引地面(真实);
声音。设置标题(“声音”);
声音。setTitleTextSize(90);
声音。设置颜色(颜色。白色);
Log.i(标签“数据发送”);
配置接收器();
}
类DataBroadcastReceiver扩展了BroadcastReceiver{
@凌驾
公共void onReceive(上下文、意图){
String message=“检测到广播意图”+intent.getAction();
Log.i(标签、消息);
}
}
私有void configureReceiver(){
IntentFilter=newintentfilter();
filter.addAction(“com.example.Pillwoah.sendbroadcast”);
接收器=新的数据接收器();
寄存器接收器(接收器、过滤器);
}
}

我没有收到任何错误,但我知道我缺少一些功能。如果有人能看到我遗漏了什么,那就太好了。

有一个带有广播接收器的样品

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)
        }
    }
    ...
}

您可以使用广播接收器将数据从服务发送到MainActivity4Thanks@guest我如何实现这一点?我需要一个广播接收器类,还是可以是MainActivity4中的函数?上面的代码在Kotlin中,对吗?我试着用java为我的代码实现其中的一些功能,但是我遇到了一些错误。我用我在服务Classic中的内容编辑了这篇文章。我仍然很难理解在java中如何理解代码java@RomkoSmuk很抱歉Kotlin编程语言现在是Android应用程序开发人员的首选语言。应该解释样本的哪一部分?我相信我能够理解。基本上,它是私有的lateinit行、内部函数onReceive和内部同伴对象