I am new to Android, I added Modbus client library to receive data from modbus device its successfully working in foreground, Using broadcast receiver sent to UI, Pass the data to recyclerview item below image (Change data Text1,Text2,Text3,Text4,Text5)
Below Code
Foreground Service.java
public class ForegroundService extends Service {
public static final String CHANNEL_ID = "ForegroundServiceChannel";
public static final String NOTIFICATION_CHANNEL_ID = "10001" ;
private final static String default_notification_channel_id = "default" ;
MyServiceThread myServiceThread;
final static String KEY_INT_FROM_SERVICE = "KEY_INT_FROM_SERVICE";
final static String KEY_INT_FROM_SERVICE2 = "KEY_INT_FROM_SERVICE2";
final static String KEY_INT_FROM_SERVICE3 = "KEY_INT_FROM_SERVICE3";
final static String KEY_INT_FROM_SERVICE4 = "KEY_INT_FROM_SERVICE4";
final static String KEY_INT_FROM_SERVICE5 = "KEY_INT_FROM_SERVICE5";
final static String ACTION_UPDATE_CNT = "UPDATE_CNT";
int cnt;
String ret = "";
int val1 = 0;
int val2 = 0;
int val3 = 0;
int val4 = 0;
int val5 = 0;
@Override
public void onCreate() {
ModbusReq.getInstance().setParam(new ModbusParam()
.setHost("10.0.2.2")
.setPort(502)
.setEncapsulated(false)
.setKeepAlive(true)
.setTimeout(2000)
.setRetries(0))
.init(new OnRequestBack<String>() {
@Override
public void onSuccess(String s) {
Log.d("TAG", "onSuccess " + s);
}
@Override
public void onFailed(String msg) {
Log.d("TAG", "onSuccess " + msg);
}
});
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String input = intent.getStringExtra("inputExtra");
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)
.setSmallIcon(R.drawable.notification)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
myServiceThread = new MyServiceThread();
myServiceThread.start();
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
myServiceThread.setRunning(false);
super.onDestroy();
}
private class PlcReader extends AsyncTask<String,Void,String> {
@Override
protected String doInBackground(String... strings) {
try{
ModbusReq.getInstance().readHoldingRegisters(new OnRequestBack<short[]>() {
@Override
public void onSuccess(short[] data) {
val1 = data[0];
val2 = data[1];
val3 = data[2];
val4 = data[3];
val5 = data[4];
}
@Override
public void onFailed(String msg) {
Log.e("TAG", "readHoldingRegisters onFailed " + msg);
}
}, 1, 0, 8);
}
catch (Exception e)
{
ret= "Exe"+e.toString();
Thread.interrupted();
}
return "Executed";
}
@Override
protected void onPostExecute(String s) {
Intent intent = new Intent();
intent.setAction(ACTION_UPDATE_CNT);
intent.putExtra(KEY_INT_FROM_SERVICE, val1);
intent.putExtra(KEY_INT_FROM_SERVICE2, val2);
intent.putExtra(KEY_INT_FROM_SERVICE3, val3);
intent.putExtra(KEY_INT_FROM_SERVICE4, val4);
intent.putExtra(KEY_INT_FROM_SERVICE5, val5);
sendBroadcast(intent);
}
} , delayInMilliseconds) ;
}
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
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);
}
}
private class MyServiceThread extends Thread{
private boolean running;
public void setRunning(boolean running){
this.running = running;
}
@Override
public void run() {
cnt = 0;
running = true;
while (running){
try {
Thread.sleep(1000);
cnt++;
new PlcReader().execute("");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
TextAdapter.java
public class TextAdapter extends RecyclerView.Adapter<TextAdapter.ItemViewHolder> {
private Context context;
private String[] Values = {"Text 1", "Text 2","Text 3","Text 4","Text 5"};
private String[] City = {"Dubai", "Italy","India","USA","UK"};
public TextAdapter(Context context) {
this.context = context;
}
@NonNull
@Override
public ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item_layout,parent,false);
return new ItemViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ItemViewHolder holder, int position) {
holder.txtView.setText(Values[position]);
holder.txtView2.setText(City[position]);
}
@Override
public int getItemCount() {
return Values.length;
}
class ItemViewHolder extends RecyclerView.ViewHolder{
private TextView txtView;
private TextView txtView2;
public ItemViewHolder(@NonNull View itemView) {
super(itemView);
txtView = itemView.findViewById(R.id.txtView);
txtView2 = itemView.findViewById(R.id.cities);
}
}
}
RecycerActivity.java
public class RecyclerActivity extends AppCompatActivity {
private RecyclerView recyclerView;
MyMainReceiver myMainReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
TextAdapter textAdapter = new TextAdapter(getApplicationContext());
recyclerView.setAdapter(textAdapter);
}
@Override
protected void onStart() {
myMainReceiver = new MyMainReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ForegroundService.ACTION_UPDATE_CNT);
registerReceiver(myMainReceiver, intentFilter);
super.onStart();
}
private class MyMainReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals(ForegroundService.ACTION_UPDATE_CNT)){
int int_from_service = intent.getIntExtra(ForegroundService.KEY_INT_FROM_SERVICE, 0);
int int_from_service2 = intent.getIntExtra(ForegroundService.KEY_INT_FROM_SERVICE2, 0);
int int_from_service3 = intent.getIntExtra(ForegroundService.KEY_INT_FROM_SERVICE3, 0);
int int_from_service4 = intent.getIntExtra(ForegroundService.KEY_INT_FROM_SERVICE4, 0);
int int_from_service5 = intent.getIntExtra(ForegroundService.KEY_INT_FROM_SERVICE5, 0);
Toast.makeText(getApplicationContext(),String.valueOf(int_from_service3), Toast.LENGTH_LONG).show();
}
}
}
}
Thread running every 1 second in Foreground service, the data from foreground service to Recycler view item every second help me to solve this problem