I'm trying to create a very simple Service to feed an Activity and provide it with a set of frames.
I followed the Bound Service methodology and created a callback interface to feed the Activity.
Client side (Activity):
public class MainActivity extends AppCompatActivity implements FrameReadyCallBack {
private Intent videoServiceIntent;
private VideoService videoService;
private boolean bound = false;
private ImageView surfaceView_video = null;
private String videoPort = "5002";
private String videoServerAddr = "192.168.10.107";
private ServiceConnection serviceConnection = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
surfaceView_video = findViewById(R.id.surfaceView_video);
serviceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder service) {
VideoService.ImagesCollectorBinder binder = (VideoService.ImagesCollectorBinder) service;
videoService = binder.getService();
bound = true;
videoService.registerCallBack(MainActivity.this); // register
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
bound = false;
}
};
startVideoService();
}
#Override
public void frameReady(byte[] image_data) {
//TODO: create image and update surfaceView_video
}
public void startVideoService()
{
videoServiceIntent = new Intent(this, VideoService.class);
videoServiceIntent.putExtra(VideoService.LOCAL_PORT_KEY, videoPort);
videoServiceIntent.putExtra(VideoService.LOCAL_VIDEOSERVER_ADDR_KEY, videoServerAddr);
startService(videoServiceIntent);
}
#Override
protected void onStart() {
super.onStart();
bindService();
}
#Override
protected void onStop() {
super.onStop();
unbindService();
}
private void bindService() {
bindService(videoServiceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
}
private void unbindService(){
if (bound) {
videoService.registerCallBack(null); // unregister
unbindService(serviceConnection);
bound = false;
}
}
}
Service side:
public class VideoService extends Service {
public static final String LOCAL_PORT_KEY = "video_port";
public static final String LOCAL_VIDEOSERVER_ADDR_KEY = "video_server_addr";
private static final int DEFAULT_VIDEO_PORT = 5002;
private static final int VIDEO_SERVER_RESPAWN = 2000;
private FrameReadyCallBack frameReadyCallBack = null;
private VideoReceiver videoReceiver = null;
private IBinder videoServiceBinder = new VideoServiceBinder();
#Nullable
#Override
public IBinder onBind(Intent intent) {
return videoServiceBinder ;
}
#Override
public boolean onUnbind(Intent intent) {
videoReceiver.kill();
return super.onUnbind(intent);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
final int localVideoPort = intent.getIntExtra(LOCAL_PORT_KEY, DEFAULT_VIDEO_PORT);
final String videoServerAddr = intent.getStringExtra(LOCAL_VIDEOSERVER_ADDR_KEY);
videoReceiver = new VideoReceiver(videoServerAddr, localVideoPort);
videoReceiver.start();
return Service.START_NOT_STICKY;
}
public void registerCallBack(FrameReadyCallBack frameReadyCallBack) {
this.frameReadyCallBack = frameReadyCallBack;
}
public class VideoServiceBinder extends Binder {
public VideoService getService() {
return VideoService.this;
}
}
private class VideoReceiver extends Thread {
private boolean keepRunning = true;
private int VIDEO_SERVER_PORT;
private String VIDEO_SERVER_ADDR;
private int bad_frames;
private int frames;
private int link_respawn;
private FrameDecodingStatus status;
public VideoReceiver(String addr, int listen_port) {
VIDEO_SERVER_PORT = listen_port;
VIDEO_SERVER_ADDR = addr;
}
public void run() {
InetAddress serverAddr;
link_respawn = 0;
try {
serverAddr = InetAddress.getByName(VIDEO_SERVER_ADDR);
} catch (UnknownHostException e) {
Log.e(getClass().getName(), e.getMessage());
e.printStackTrace();
return;
}
Socket socket = null;
DataInputStream stream;
do {
bad_frames = 0;
frames = 0;
status = FrameDecodingStatus.Idle;
try {
socket = new Socket(serverAddr, VIDEO_SERVER_PORT);
stream = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
final byte[] _data = new byte[PACKET_SIZE];
final byte[] _image_data = new byte[IMAGE_SIZE];
int _data_index = 0;
while (keepRunning) {
if (stream.read(_data, 0, _data.length) == 0)
continue;
for (byte _byte : _data) {
if (status == FrameDecodingStatus.Idle) {
//Wait SoM
} else if (status == FrameDecodingStatus.Data) {
//Collect data
} else {
frameReadyCallBack.frameReady(_image_data);
status = FrameDecodingStatus.Idle;
}
}
}
}
link_respawn++;
Thread.sleep(VIDEO_SERVER_RESPAWN);
Log.d(getClass().getName(), "Link respawn: " + link_respawn);
} catch (Throwable e) {
Log.e(getClass().getName(), e.getMessage());
e.printStackTrace();
}
} while (keepRunning);
if (socket != null) {
try {
socket.close();
} catch (Throwable e) {
Log.e(getClass().getName(), e.getMessage());
e.printStackTrace();
}
}
}
public void kill() {
keepRunning = false;
}
}
}
Callback interface:
public interface FrameReadyCallBack {
void frameReady(byte[] image_data);
}
As far as I can see frameReady() callback is never called and the whole mechanism fails.
Where is the error?
Related
I called postValue() but MutableLivdata does not update its value.
When I print Log in UserInfoViewModel at setNetworkObj() and setUserName(), value from parameter nothing wrong(parameter arrived well).
But userName.getValue() print null.
So I tried postValue() in Handler and runOnUiThread but nothing work either.
I'd really appreciate it if you could tell me how to figure it out.
this is my code..
UserInfoViewModel.java
public class UserInfoViewModel extends ViewModel {
private MutableLiveData<NetworkObj> networkObj = new MutableLiveData<>();
private MutableLiveData<String> userName = new MutableLiveData<>();
public MutableLiveData<NetworkObj> getNetworkObj() {
return networkObj;
}
public void setNetworkObj(NetworkObj networkObj) {
this.networkObj.postValue(networkObj);
}
public MutableLiveData<String> getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName.postValue(userName);
}
}
LoginActivity.java
public class LoginActivity extends AppCompatActivity {
private ActivityLoginBinding binding;
private UserInfoViewModel userInfoViewModel;
public Socket socket;
public ObjectInputStream ois;
public ObjectOutputStream oos;
private NetworkUtils networkUtils;
private NetworkObj networkObj;
private String userName ="";
final String ip_addr = "10.0.2.2"; // Emulator PC의 127.0.0.1
final int port_no = 30000;
Handler mHandler = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
binding = ActivityLoginBinding.inflate(getLayoutInflater());
super.onCreate(savedInstanceState);
setContentView(binding.getRoot());
userInfoViewModel = new ViewModelProvider(this).get(UserInfoViewModel.class);
mHandler = new Handler();
binding.btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
userName = binding.etName.getText().toString();
new Thread() {
public void run() {
try {
socket = new Socket(ip_addr, port_no);
oos = new ObjectOutputStream(socket.getOutputStream());
ois = new ObjectInputStream(socket.getInputStream());
networkObj = new NetworkObj(socket, ois, oos);
networkUtils = new NetworkUtils(networkObj);
mHandler.post(new Runnable() {
#Override
public void run() {
userInfoViewModel.setNetworkObj(networkObj);
userInfoViewModel.setUserName(userName);
}
});
ChatMsg obj = new ChatMsg(userName, "100", "Hello");
networkUtils.sendChatMsg(obj, networkObj);
startMainActivity();
} catch (IOException e) {
Log.w("Login", e);
}
}
}.start();
}
});
}
public void startMainActivity() {
startActivity(new Intent(this, MainActivity.class));
}
}
I have an app which automatically fetch data online whenever it is opened. I would like to make it a way that the app will only check for update online when a blacklisted app is not detected.
This is the update core.
public class UpdateCore extends AsyncTask<String, String, String> {
private static final String TAG = "NetGuard.Download";
private Context context;
private Listener listener;
private PowerManager.WakeLock wakeLock;
private HttpURLConnection uRLConnection;
private InputStream is;
private TorrentDetection torrent;
private BufferedReader buffer;
private String url;
public interface Listener {
void onLoading();
void onCompleted(String config) throws Exception;
void onCancelled();
void onException(String ex);
}
public UpdateCore(Context context, String url, Listener listener) {
this.context = context;
this.url = url;
this.listener = listener;
}
#Override
protected void onPreExecute() {
listener.onLoading();
}
#Override
protected String doInBackground(String... args) {
try {
String api = url;
if(!api.startsWith("http")){
api = new StringBuilder().append("http://").append(url).toString();
}
URL oracle = new URL(api);
HttpClient Client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(oracle.toURI());
HttpResponse response = Client.execute(httpget);
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
in, "iso-8859-1"), 8);
//BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
str.append(line);
}
in.close();
return str.toString();
} catch (Exception e) {
return "error";
} finally {
if (buffer != null) {
try {
buffer.close();
} catch (IOException ignored) {
}
}
if (is != null) {
try {
is.close();
} catch (IOException ignored) {
}
}
if (uRLConnection != null) {
uRLConnection.disconnect();
}
}
}
#Override
protected void onCancelled() {
super.onCancelled();
// Log.i(TAG, "Cancelled");
// pd.dismiss();
listener.onCancelled();
}
#Override
protected void onPostExecute(String result) {
// wakeLock.release();
//nm.cancel(1);
// pd.dismiss();
try
{
if (result.equals("error"))
{
listener.onException(result);
}
else {
listener.onCompleted(result);
}
}
catch (Exception e)
{
listener.onException(e.getMessage());
}
}
}
This is the detection code
public class TorrentDetection
{
private Context context;
private String[] items;
private TorrentDetection.TorrentListener listener;
private Timer timer;
private Handler handler;
public interface TorrentListener {
public void detected(ArrayList pkg);
}
public TorrentDetection(Context c, String[] i, TorrentListener listener) {
context = c;
items = i;
this.listener = listener;
}
private boolean check(String uri)
{
PackageManager pm = context.getPackageManager();
boolean app_installed = false;
try
{
pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
app_installed = true;
}
catch (PackageManager.NameNotFoundException e)
{
app_installed = false;
}
return app_installed;
}
void check() {
ArrayList arrayList2 = new ArrayList();
for (String pack : items)
{
if(check(pack)){
arrayList2.add(pack);
}
}
if (arrayList2.size() > 0)
{
listener.detected(arrayList2);
stop();
}
}
public void start() {
handler = new Handler();
timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run()
{
handler.post(new Runnable() {
public void run()
{
check();
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 3000);
}
public void stop() {
if(timer != null){
timer.cancel();
timer = null;
}
if(handler != null){
handler = null;
}
}
}
The torrent detection code checks if the following apps are installed and returns a message that an unsupported app is installed.
public class Constraints
{
public static String updater = "https://pastenord.org/raw/random";
public static String[] torrentList = new String[]{
"com.guoshi.httpcanary",
"com.adguard.android.contentblocker"};
}
In my MainActivity this initiates the detection before the online update is done with torrent.start();
void update() {
torrent.start();
new UpdateCore(this, Constraints.updater, new UpdateCore.Listener() {
#Override
public void onLoading() {
}
#Override
public void onCompleted(final String config) {
try {
final JSONObject obj = new JSONObject(MilitaryGradeEncrypt.decryptBase64StringToString(config, Constraints.confpass));
if (Double.valueOf(obj.getString("Version")) <= Double.valueOf(conts.getConfigVersion())) {
} else {
new SweetAlertDialog(MainActivity.this, SweetAlertDialog.CUSTOM_IMAGE_TYPE)
.setTitleText("Update")
.setContentText("\n" + obj.getString("Message"))
.setConfirmText("Yes,Update it!")
.setCustomImage(R.drawable.ic_update)
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sDialog) {
sDialog.dismissWithAnimation();
welcomeNotif();
restart_app();
try {
db.updateData("1", config);
sp.edit().putString("CurrentConfigVersion", obj.getString("Version")).commit();
} catch (JSONException e) {}
}
})
.show();
}
} catch (Exception e) {
// Toast.makeText(MainActivity.this, e.getMessage() , 0).show();
}
}
#Override
public void onCancelled() {
}
#Override
public void onException(String ex) {
}
}).execute();
}
}
It then makes a popup when an unsupported app is detected with this.
torrent = new TorrentDetection(this, Constraints.torrentList, new TorrentDetection.TorrentListener() {
#Override
public void detected(ArrayList pkg)
{
stopService();
new AlertDialog.Builder(MainActivity.this)
.setTitle("unsupported App!")
.setMessage(String.format("%s", new Object[]{TextUtils.join(", ", (String[]) pkg.toArray(new String[pkg.size()]))}))
.setPositiveButton("OK", null)
//.setAnimation(Animation.SLIDE)
.setCancelable(false)
.create()
//.setIcon(R.mipmap.ic_info, Icon.Visible)
.show();
}
});
I would like the make the app only check for online update only when done of the blacklisted apps are installed. Any form of help is welcomed and appreciated.
use this method to check if an application is installed or not
public boolean isPackageInstalled(String packageName, PackageManager packageManager) {
try {
packageManager.getPackageInfo(packageName, 0);
return true;
} catch (PackageManager.NameNotFoundException e) {
return false;
}
}
then to check, simply call:
PackageManager pm = context.getPackageManager();
boolean isInstalled = isPackageInstalled("com.somepackage.name", pm);
// simply put an if statemement
if(!isInstalled){
//do your update here
}
else{
//display you have installed a blacklisted app
}
sidenote, if you are targeting android 11 and above, you need to provide the information about the packages you want to find out about in the manifest like this
<queries>
<!--Add queries here-->
<package android:name="com.somepackage.name" />
</queries>
I want to play multiple speakers at the same time.
In my apllication I'm getting audio from network, decode from C#, decode by opus and then want to play bytes. But now I can play only one speaker.
My AudioPLayer.class:
public class Player {
private static final String TAG = Player.class.getName();
private AudioTrack audioTrack;
private boolean isWorking;
public Player() {
try {
audioTrack = new AudioTrack(
AudioManager.STREAM_MUSIC,
AudioConsts.SAMPLERATE,
AudioConsts.NUM_CHANNELS == 1 ? AudioConsts.CHANNEL_OUT_MONO : AudioConsts.CHANNEL_OUT_STEREO,
AudioConsts.ENCODING_PCM_16BIT,
AudioConsts.GetPlayerBufferSize(),
AudioTrack.MODE_STREAM);
} catch (Exception e){
Log.e(TAG, e.toString());
}
}
public void play() {
new Thread(new Runnable() {
#Override
public void run() {
isWorking = true;
try {
audioTrack.play();
} catch (Exception e) {
Log.d(e.toString(), "AUDIO EXCEPTION");
return;
}
int bufferSize = AudioConsts.GetPlayerBufferSize();
while (isWorking){
int cursor = audioTrack.getPlaybackHeadPosition();
if (cursor > bufferSize){
cursor %= bufferSize;
audioTrack.flush();
audioTrack.setPlaybackHeadPosition(cursor);
}
}
}
}).start();
}
public void stopReading(){
if (!isWorking)
return;
audioTrack.release();
isWorking = false;
}
public void appendForPlayback(byte[] audioMessage, int size) {
if (size != 0){
int writen = audioTrack.write(audioMessage, 0, size);
if (writen != size) {
//audioTrack.release();
Log.d(TAG, "WTF");
}
}
}
}
Also attach my AudioPlayer's initialization:
#Override
public void onCreate() {
super.onCreate();
...
player = new Player();
player.play();
IntentFilter filter = new IntentFilter();
filter.addAction(ON_UNITY_AUDIO_MESSAGE_RECEIVED);
filter.addAction(AudioConsts.START_RECORDER);
filter.addAction(AudioConsts.STOP_RECORDER);
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ON_UNITY_AUDIO_MESSAGE_RECEIVED)) {
byte[] decryptedBytes = intent.getByteArrayExtra(UNITY_AUDIO_MESSAGE);
onUnityAudioReceivedFromNetwork(decryptedBytes);
} else if (intent.getAction().equals(AudioConsts.START_RECORDER)) {
incrementSessionCount();
recorder.startRecording();
} else if (intent.getAction().equals(AudioConsts.STOP_RECORDER)) {
recorder.stopRecording();
}
}
};
registerReceiver(broadcastReceiver, filter);
decodeMsg = new byte[AudioConsts.FRAME_SIZE * AudioConsts.ENCODING_PCM_16BIT];
opusDecoder = new OpusDecoder();
opusDecoder.init(AudioConsts.SAMPLERATE, AudioConsts.NUM_CHANNELS);
}
...
private void onUnityAudioReceivedFromNetwork(byte[] decryptedBytes) {
UnityAudioMessage audioMessage = UnityAudioMessage.fromBytesSharp(decryptedBytes);
if (audioMessage != null) {
try {
opusDecoder.decode(audioMessage.unityAudioMessage, decodeMsg, AudioConsts.FRAME_SIZE);
} catch (OpusError e) {
e.printStackTrace();
return;
}
player.appendForPlayback(decodeMsg, decodeMsg.length);
}
}
...
Can I release simultaneos playback of multiple speakers?
Also I tried release it with HaspMap of my players. But it works only like 1 audio track.
I tried a lot of things, but my solution use AsyncTask.class
Attach Player.class
public class Player {
private static final String TAG = Player.class.getName();
private AudioTrack audioTrack;
private boolean isWorking;
public Player() {
try {
audioTrack = new AudioTrack(
new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.setLegacyStreamType(AudioManager.STREAM_MUSIC)
.build(),
new AudioFormat.Builder()
.setChannelMask(AudioFormat.CHANNEL_OUT_MONO)
.setEncoding(AudioFormat.ENCODING_PCM_16BIT)
.setSampleRate(AudioConsts.SAMPLERATE)
.build(),
AudioConsts.GetPlayerBufferSize(),
AudioTrack.MODE_STREAM,
AudioManager.AUDIO_SESSION_ID_GENERATE);
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
public void play() {
audioTrack.play();
}
public void stopReading() {
if (!isWorking)
return;
audioTrack.release();
isWorking = false;
}
public void appendForPlayback(byte[] audioMessage, int size) {
new Executor().doInBackground(audioMessage);
}
private class Executor extends AsyncTask<byte[], Void, Void> {
#Override
protected Void doInBackground(byte[]... bytes) {
for (byte[] audioMessage : bytes) {
if (audioMessage.length != 0) {
int writen = audioTrack.write(audioMessage, 0, audioMessage.length);
if (writen != audioMessage.length) {
Log.d(TAG, "WTF");
}
}
}
return null;
}
}}
I have a home class when i open task manager at home class it shows 15 MB of ram.
then on opening BooksDetails class it increases to 29 MB.
on Clicking back memory does not return 15MB
Here is a sample
public class BooksDetails extends Activity
{
private Button btnBack;
private TextView tvBookTitle, tvBookSentences, tvBookInSummary, tvSpecialSentences;
private JustifiedTextView tvBookTxt;
private Button btnFavorite, btnShare, btnRelated;
public book mBook;
private Share ds;
private Button btnShareFacebook, btnShareTwitter, btnShareGooglePlus,btnCancelShare;// bookShare
private int idCount;
private IDGENERATOR idGen;
private String uniqueTag;
// private ProgressBar mProgress;
private ProgressWheel mProgress;
// getBookText getBookTextTask;
public int homeBookId;
private static int count = 0;
public static int ifDidntFindAnId = -1;
public static boolean shouldTerminate = false;
public static int terminateCount = 0;
private int currentTerminateCount = 0;
private boolean isAppRunning = true;
private UiLifecycleHelper uiHelper;
private PendingAction pendingAction = PendingAction.NONE;
private enum PendingAction
{
NONE, POST_PHOTO, POST_STATUS_UPDATE
}
private Session.StatusCallback callback = new Session.StatusCallback()
{
#Override
public void call(Session session, SessionState state,
Exception exception)
{
onSessionStateChange(session, state, exception);
}
};
private String user_id = null;
private int isFavourite = -1;
BooksDetailsHelp booksDetailsHelp;
private FontMan fMan;
public FontMan getFontMan()
{
if (fMan == null)
{
fMan = FontMan.getInstance(this);
}
return fMan;
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
// processing
}
And
#Override
public void onDestroy()
{
super.onDestroy();
if (uiHelper != null)
uiHelper.onDestroy();
destroy();
}
private void destroy()
{
try
{
tvBookTxt.destroy();
Globals.destroy(findViewById(R.id.rootView));
}
catch (Exception e)
{
}
btnBack = null;
tvBookTitle = tvBookSentences = tvBookInSummary = tvSpecialSentences = null;
tvBookTxt = null;
btnFavorite.setOnClickListener(null);
btnShare.setOnClickListener(null);
btnRelated.setOnClickListener(null);
btnFavorite = btnShare = btnRelated = null;
mBook = null;
ds = null;
btnShareFacebook.setOnClickListener(null);
btnShareTwitter.setOnClickListener(null);
btnShareGooglePlus.setOnClickListener(null);
btnCancelShare.setOnClickListener(null);
btnShareFacebook = btnShareTwitter = btnShareGooglePlus = btnCancelShare = null;
idGen = null;
uniqueTag = null;
mProgress = null;
uiHelper = null;
pendingAction = null;
callback = null;
user_id = null;
booksDetailsHelp.destroy();
booksDetailsHelp = null;
fMan = null;
if (getUserSocialIdsTask != null)
{
getUserSocialIdsTask.cancel(true);
}
getUserSocialIdsTask = null;
finish();
System.gc();
}
public synchronized static void destroy(View homeView)
{
try
{
disableListeners(homeView);
}
catch (Exception e)
{
// TODO: handle exception
}
try
{
unbindDrawables(homeView);
}
catch (Exception e)
{
}
}
private static void disableListeners(View view)
{
try
{
view.setOnClickListener(null);
}
catch (Exception e)
{
// TODO: handle exception
}
if (view instanceof ViewGroup)
{
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++)
{
disableListeners(((ViewGroup) view).getChildAt(i));
}
}
}
private static void unbindDrawables(View view)
{
if (view.getBackground() != null)
{
view.getBackground().setCallback(null);
}
if (view instanceof ViewGroup)
{
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++)
{
unbindDrawables(((ViewGroup) view).getChildAt(i));
}
((ViewGroup) view).removeAllViews();
}
}
here is an image after clicking the back button
I have this code and i would like to test if i will set up Handler and called method run with outputstream and inputstream that this class is good working. And i mean by it that i will recieved something on input stream then change it to something else and send it on output stream and then check if message send by Handler is right. How can i do it or can i mock output-input stream and handler?
TestClass that i would like to test.
import android.os.Handler;
import android.util.Log;
public class TestClass {
protected String description;
protected String responce;
protected String valueResponce;
protected int done;
protected Handler listener;
protected int identifier;
protected int target;
public static final int STATE_GOOD = 0;
public static final int STATE_FAILED = 1;
public static final int STATE_ATDPN = 2;
public void addListener(Handler listener) {
this.listener = listener;
}
protected void preparation() {
identifier = Integer.parseInt(this.getRequest(), 16);
target = HandlerLabels.MESSAGE_DATA;
}
protected void send(OutputStream outStream) {
String mes = this.getRequest() + '\r';
byte[] send = mes.getBytes();
try {
outStream.write(send);
} catch (IOException e) {
done = STATE_FAILED;
}
}
protected void read(InputStream inStream) {
try {
int data = inStream.read();
String output = "";
while (data != 62) {
if (data != 10) {
if (data != 13) {
output += (char) data;
}
}
data = inStream.read();
}
responce = output;
} catch (IOException e) {
done = STATE_FAILED;
}
}
protected void noticeListener() {
if (listener == null) {
Log.d(tag, "listener null");
} else {
listener.obtainMessage(target, identifier, -1, valueResponce)
.sendToTarget();
}
}
protected boolean control(String value){
if(value.length() == 0){
done = STATE_FAILED;
return false;
}
return true;
}
public int run(InputStream inStream, OutputStream outStream) {
preparation();
if (done == STATE_GOOD)
send(outStream);
if (done == STATE_GOOD)
read(inStream);
if (control(responce))
valueResponce = calculateValue(responce);
if (done == STATE_GOOD)
noticeListener();
return done;
}
protected String calculateValue(String value) {
String[] arr = value.split(" ");
int A = Integer.parseInt(arr[2], 16);
return String.valueOf(((A*100)/255));
}
public String getRequest() {
return "01041";
}
public String getDescription() {
return description;
}
public int isDone() {
return done;
}
public void setDone(int done) {
this.done = done;
}
public String getResponce() {
return responce;
}
public void setResponce(String responce) {
this.responce = responce;
}
}