trying to find when CH34xAndroidDriver.isConnected() is becomes true - java

I am trying to find when and where CH34xAndroidDriver.isConnected() value becomes true.
I have tried to find out and display its value in a toast. can anybody explain it clearly.
public class UartLoopBackActivity extends Activity {
public static final String TAG = "com.wch.wchusbdriver";
private static final String ACTION_USB_PERMISSION = "com.wch.wchusbdriver.USB_PERMISSION";
/* thread to read the data */
public readThread handlerThread;
protected final Object ThreadLock = new Object();
/* declare UART interface variable */
public CH34xAndroidDriver uartInterface;
// byte timeout; // time out
public Context global_context;
public boolean isConfiged = false;
public boolean READ_ENABLE = false;
public SharedPreferences sharePrefSettings;
Drawable originalDrawable;
public String act_string;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/* create editable text objects */
readText = (EditText) findViewById(R.id.ReadValues);
// writeText = (EditText) findViewById(R.id.WriteValues);
global_context = this;
configButton = (Button) findViewById(R.id.configButton);
originalDrawable = configButton.getBackground();
readBuffer = new char[512];
baudRate = 9600;
stopBit = 1;
dataBit = 8;
parity = 0;
flowControl = 0;
configButton.setOnClickListener(new OpenDeviceListener());
// writeButton.setOnClickListener(new OnClickedWriteButton());
// writeButton.setEnabled(false);
//
uartInterface = new CH34xAndroidDriver(
(UsbManager) getSystemService(Context.USB_SERVICE), this,
ACTION_USB_PERMISSION);
act_string = getIntent().getAction();
if (-1 != act_string.indexOf("android.intent.action.MAIN")) {
Log.d(TAG, "android.intent.action.MAIN");
} else if (-1 != act_string
.indexOf("android.hardware.usb.action.USB_DEVICE_ATTACHED")) {
Log.d(TAG, "android.hardware.usb.action.USB_DEVICE_ATTACHED");
}
if (!uartInterface.UsbFeatureSupported()) {
Toast.makeText(this, "No Support USB host API", Toast.LENGTH_SHORT)
.show();
readText.setText("No Support USB host API");
uartInterface = null;
Toast.makeText(global_context,
"148k" + ((Boolean) uartInterface.isConnected()),
Toast.LENGTH_SHORT).show();
}
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
if (READ_ENABLE == false) {
READ_ENABLE = true;
handlerThread = new readThread(handler);
handlerThread.start();
Toast.makeText(global_context,"155k" + ((Boolean) uartInterface.isConnected()),Toast.LENGTH_SHORT).show();
}
}
public class OpenDeviceListener implements View.OnClickListener {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
boolean flags;
Toast.makeText(global_context,"170" + ((Boolean) uartInterface.isConnected()),Toast.LENGTH_SHORT).show();
Log.d("onClick", "12");
if (false == isConfiged) {
Log.d("onClick", "58");
isConfiged = true;
Log.d("onClick", "98");
// writeButton.setEnabled(true);
if (uartInterface.isConnected()) {
Log.d("onClick", "100");
flags = uartInterface.UartInit();
if (!flags) {
Log.d(TAG, "Init Uart Error");
Toast.makeText(global_context, "Init Uart Error",
Toast.LENGTH_SHORT).show();
} else {
if (uartInterface.SetConfig(baudRate, dataBit, stopBit,
parity, flowControl)) {
Log.d(TAG, "Configed");
}
}
}
if (isConfiged == true) {
Toast.makeText(global_context,"193" + ((Boolean) uartInterface.isConnected()),Toast.LENGTH_SHORT).show();
Log.d("onClick", "200");
configButton.setEnabled(false);
}
}
}
}
public void onHomePressed() {
onBackPressed();
}
public void onBackPressed() {
super.onBackPressed();
}
protected void onResume() {
super.onResume();
if (2 == uartInterface.ResumeUsbList()) {
uartInterface.CloseDevice();
Log.d(TAG, "Enter onResume Error");
}
}
protected void onPause() {
super.onPause();
}
protected void onStop() {
if (READ_ENABLE == true) {
READ_ENABLE = false;
}
super.onStop();
}
protected void onDestroy() {
if (uartInterface != null) {
if (uartInterface.isConnected()) {
uartInterface.CloseDevice();
}
uartInterface = null;
}
super.onDestroy();
}
final Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (actualNumBytes != 0x00) {
readText.append(String.copyValueOf(readBuffer, 0,
actualNumBytes));
Toast.makeText(global_context,"269k" + ((Boolean) uartInterface.isConnected()),Toast.LENGTH_SHORT).show();
actualNumBytes = 0;
}
}
};
/* usb input data handler */
private class readThread extends Thread {
Handler mHandler;
/* constructor */
Handler mhandler;
readThread(Handler h) {
mhandler = h;
this.setPriority(Thread.MIN_PRIORITY);
}
public void run() {
while (READ_ENABLE) {
Message msg = mhandler.obtainMessage();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
// Log.d(TAG, "Thread");
synchronized (ThreadLock) {
if (uartInterface != null) {
actualNumBytes = uartInterface.ReadData(readBuffer, 64);
if (actualNumBytes > 0) {
mhandler.sendMessage(msg);
}
}
}
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.uart_loop_back, menu);
return true;
}
}
upto line 74 (Toast.makeText(global_context,"155k" + ((Boolean) uartInterface.isConnected()),Toast.LENGTH_SHORT).show();) i found it returns false but when the onClick() is called it return true. why if any body has answer pls check it.
Thanks

the method ResumeUsbList() enables usb connection and changes isConnected() to true. if ResumeUsbList() fails it returns 2
Check your Activity's onResume()

Related

Camera is not working in one android app for Poco X3

// Camera activity code
public class CamActivity extends AppCompatActivity implements
ActivityCompat.OnRequestPermissionsResultCallback,
AspectRatioFragment.Listener {
public static boolean activityStatus;
private Handler handler = new Handler();
private FirebaseAnalytics mFirebaseAnalytics;
private static final String TAG = "CamActivity";
private static final int REQUEST_CAMERA_PERMISSION = 1;
private static final String FRAGMENT_DIALOG = "dialog";
private static final int SELECT_PICTURE = 1;
private static final int[] FLASH_OPTIONS = {
CameraView.FLASH_AUTO,
CameraView.FLASH_OFF,
CameraView.FLASH_ON,
};
private static final int[] FLASH_ICONS = {
R.drawable.ic_flash_auto,
R.drawable.ic_flash_off,
R.drawable.ic_flash_on,
};
private static final int[] FLASH_TITLES = {
R.string.flash_auto,
R.string.flash_off,
R.string.flash_on,
};
private int mCurrentFlash;
private CameraView mCameraView;
private Handler mBackgroundHandler;
private FloatingActionButton fab;
private ImageView open_gallery;
private View.OnClickListener mOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.take_picture:
if (mCameraView != null) {
try {
mCameraView.takePicture();
/*handler.postDelayed(() ->
mCameraView.takePicture(),
500);*/
}catch (Exception e){
Log.e(TAG,"mCameraView"+e.toString());
}
}
break;
case R.id.open_gallery:
openGallery();
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
Bundle bundle1 = new Bundle();
bundle1.putString(TAG, TAG);
bundle1.putString(TAG, TAG);
mFirebaseAnalytics.logEvent(TAG, bundle1);
setContentView(R.layout.activity_camera_renderer);
mCameraView = findViewById(R.id.camera);
open_gallery = findViewById(R.id.open_gallery);
if (open_gallery!=null)
open_gallery.setOnClickListener(mOnClickListener);
activityStatus = true;
if (mCameraView != null) {
mCameraView.addCallback(mCallback);
}
fab = findViewById(R.id.take_picture);
if (fab != null) {
fab.setOnClickListener(mOnClickListener);
}
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayShowTitleEnabled(false);
}
//toolbar.setTitle("Camera");
toolbar.setNavigationIcon(R.drawable.ic_back_arrow);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
closeCamera();
}
});
//Listen for capture image and close camera
registerReceiver(syncCamReceiver, new IntentFilter("Camera"));
}
#Override
public void onBackPressed() {
closeCamera();
super.onBackPressed();
}
/**CLose camera**/
private void closeCamera(){
try{
unregisterReceiver(syncCamReceiver);
}
catch (Exception e){
Log.d(TAG,"Error while unregistering");
}
SN88Constant.getIk6Obj(getApplicationContext()).sendPhotoSwitch(false);
CamActivity.this.finish();
}
BroadcastReceiver syncCamReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent intent) {
if (intent.getAction().equalsIgnoreCase("Camera")) {
//0 for open cam, 1 take picture 2 close camera
if(intent.getIntExtra(Constants.CAMERA_REQUEST_TYPE,-1)==1){
fab .performClick();
}
else if(intent.getIntExtra(Constants.CAMERA_REQUEST_TYPE,-1)==2){
CamActivity.this.finish();
}
}
}
};
#Override
protected void onResume() {
activityStatus = true;
try {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
== PackageManager.PERMISSION_GRANTED) {
if (mCameraView != null)
mCameraView.start();
} else if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CAMERA)) {
ConfirmationDialogFragment
.newInstance(R.string.camera_permission_confirmation,
new String[]{Manifest.permission.CAMERA},
REQUEST_CAMERA_PERMISSION,
R.string.camera_permission_not_granted)
.show(getSupportFragmentManager(), FRAGMENT_DIALOG);
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},
REQUEST_CAMERA_PERMISSION);
}
}catch (Exception e){
Log.d(TAG,"Camera_onresume"+e.toString());
}
super.onResume();
}
#Override
protected void onPause() {
mCameraView.stop();
super.onPause();
}
#Override
protected void onDestroy() {
closeCamera();
activityStatus = false;
if (mBackgroundHandler != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
mBackgroundHandler.getLooper().quitSafely();
} else {
mBackgroundHandler.getLooper().quit();
}
mBackgroundHandler = null;
}
super.onDestroy();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_CAMERA_PERMISSION:
if (permissions.length != 1 || grantResults.length != 1) {
throw new RuntimeException("Error on requesting camera permission.");
}
if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, R.string.camera_permission_not_granted,
Toast.LENGTH_SHORT).show();
}
// No need to start camera here; it is handled by onResume
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.aspect_ratio:
FragmentManager fragmentManager = getSupportFragmentManager();
if (mCameraView != null
&& fragmentManager.findFragmentByTag(FRAGMENT_DIALOG) == null) {
final Set<AspectRatio> ratios = mCameraView.getSupportedAspectRatios();
final AspectRatio currentRatio = mCameraView.getAspectRatio();
AspectRatioFragment.newInstance(ratios, currentRatio)
.show(fragmentManager, FRAGMENT_DIALOG);
}
return true;
case R.id.switch_flash:
if (mCameraView != null) {
mCurrentFlash = (mCurrentFlash + 1) % FLASH_OPTIONS.length;
item.setTitle(FLASH_TITLES[mCurrentFlash]);
item.setIcon(FLASH_ICONS[mCurrentFlash]);
mCameraView.setFlash(FLASH_OPTIONS[mCurrentFlash]);
}
return true;
case R.id.switch_camera:
if (mCameraView != null) {
try {
int facing = mCameraView.getFacing();
mCameraView.setFacing(facing == CameraView.FACING_FRONT ?
CameraView.FACING_BACK : CameraView.FACING_FRONT);
}catch (Exception e){
e.printStackTrace();
}
}
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onAspectRatioSelected(#NonNull AspectRatio ratio) {
if (mCameraView != null) {
//Toast.makeText(this, ratio.toString(), Toast.LENGTH_SHORT).show();
try {
mCameraView.setAspectRatio(ratio);
}catch (Exception e){
Log.d(TAG,"onAspectRatioSelected"+e.toString());
}
}
}
private Handler getBackgroundHandler() {
if (mBackgroundHandler == null) {
HandlerThread thread = new HandlerThread("background");
thread.start();
mBackgroundHandler = new Handler(thread.getLooper());
}
return mBackgroundHandler;
}
private CameraView.Callback mCallback
= new CameraView.Callback() {
#Override
public void onCameraOpened(CameraView cameraView) {
Log.d(TAG, "onCameraOpened");
}
#Override
public void onCameraClosed(CameraView cameraView) {
Log.d(TAG, "onCameraClosed");
}
#Override
public void onPictureTaken(CameraView cameraView, final byte[] data) {
Log.d(TAG, "onPictureTaken " + data.length);
Toast.makeText(cameraView.getContext(), R.string.picture_taken, Toast.LENGTH_SHORT)
.show();
getBackgroundHandler().post(new Runnable() {
#Override
public void run() {
String folderPath = Environment.getExternalStorageDirectory() + "/DCIM/Camera";
File folder = new File(folderPath);
if (!folder.exists()) {
File wallpaperDirectory = new File(folderPath);
wallpaperDirectory.mkdir();
}
File file = new File(folderPath,"/Img"+System.currentTimeMillis()+ ".png");
OutputStream os = null;
try {
os = new FileOutputStream(file);
os.write(data);
os.close();
scanFile(file.getAbsolutePath());
} catch (IOException e) {
Log.w(TAG, "Cannot write to " + file, e);
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
// Ignore
}
}
}
}
});
}
};
public static class ConfirmationDialogFragment extends DialogFragment {
private static final String ARG_MESSAGE = "message";
private static final String ARG_PERMISSIONS = "permissions";
private static final String ARG_REQUEST_CODE = "request_code";
private static final String ARG_NOT_GRANTED_MESSAGE = "not_granted_message";
public static ConfirmationDialogFragment newInstance(#StringRes int message,
String[] permissions, int requestCode, #StringRes int notGrantedMessage) {
ConfirmationDialogFragment fragment = new ConfirmationDialogFragment();
Bundle args = new Bundle();
args.putInt(ARG_MESSAGE, message);
args.putStringArray(ARG_PERMISSIONS, permissions);
args.putInt(ARG_REQUEST_CODE, requestCode);
args.putInt(ARG_NOT_GRANTED_MESSAGE, notGrantedMessage);
fragment.setArguments(args);
return fragment;
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Bundle args = getArguments();
return new AlertDialog.Builder(getActivity())
.setMessage(args.getInt(ARG_MESSAGE))
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String[] permissions = args.getStringArray(ARG_PERMISSIONS);
if (permissions == null) {
throw new IllegalArgumentException();
}
ActivityCompat.requestPermissions(getActivity(),
permissions, args.getInt(ARG_REQUEST_CODE));
}
})
.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getActivity(),
args.getInt(ARG_NOT_GRANTED_MESSAGE),
Toast.LENGTH_SHORT).show();
}
})
.create();
}
}
//Scans the saved file so it appears in the gallery
private void scanFile(String path) {
MediaScannerConnection.scanFile(this,
new String[] { path }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("TAG", "Finished scanning " + path);
}
});
}
/*
* open gallery for image preview
* */
private void openGallery(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
}
}
// Getting error :
E/CamActivity: mCameraViewjava.lang.NullPointerException: Attempt to invoke virtual method 'void android.hardware.camera2.CaptureRequest$Builder.set(android.hardware.camera2.CaptureRequest$Key, java.lang.Object)' on a null object reference

How can I make SeekBar indicate current position even when the app is resumed?

When the audio player app is resumed while playing audio, the SeekBar resets to 0. During audio playback, the SeekBar updates progress. However, when the screen is resumed, the SeekBar starts from the beginning without indicating the player's current position. When you press the pause button and then press the play button, it plays at the current position again. In updateProgress() method, there is long currentPosition = mLastPlaybackState.getPosition(); I think this code doesn't indicate the current position when resumed.
I implemented SeekBar update progress based on the UAMP FullScreenActivity
This is my NowPlayingAcitivy.java:
private PlaybackStateCompat mLastPlaybackState;
private final Handler mHandler = new Handler();
private final Runnable mUpdateProgressTask = new Runnable() {
#Override
public void run() {
updateProgress();
}
};
private final ScheduledExecutorService mExecutorService =
Executors.newSingleThreadScheduledExecutor();
private ScheduledFuture<?> mScheduledFuture;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNowPlayingBinding = DataBindingUtil.setContentView(
this, R.layout.activity_now_playing);
createMediaBrowserCompat();
mNowPlayingBinding.playingInfo.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
mNowPlayingBinding.playingInfo.tvStart.setText(DateUtils.formatElapsedTime(
progress/1000));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// Cancel the future returned by scheduleAtFixedRate() to stop the SeekBar from progressing
stopSeekbarUpdate();
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
MediaControllerCompat.getMediaController(NowPlayingActivity.this)
.getTransportControls().seekTo(seekBar.getProgress());
// Create and execute a periodic action to update the SeekBar progress
scheduleSeekbarUpdate();
}
});
}
private void createMediaBrowserCompat() {
mMediaBrowser = new MediaBrowserCompat(this,
new ComponentName(this, PodcastService.class),
mConnectionCallbacks,
null);
}
#Override
protected void onStart() {
super.onStart();
mMediaBrowser.connect();
}
#Override
protected void onResume() {
super.onResume();
setVolumeControlStream(AudioManager.STREAM_MUSIC);
}
#Override
protected void onStop() {
super.onStop();
if (MediaControllerCompat.getMediaController(this) != null) {
MediaControllerCompat.getMediaController(this).unregisterCallback(controllerCallback);
}
mMediaBrowser.disconnect();
}
#Override
protected void onDestroy() {
super.onDestroy();
stopSeekbarUpdate();
mExecutorService.shutdown();
}
private final MediaBrowserCompat.ConnectionCallback mConnectionCallbacks =
new MediaBrowserCompat.ConnectionCallback() {
#Override
public void onConnected() {
MediaSessionCompat.Token token = mMediaBrowser.getSessionToken();
MediaControllerCompat mediaController = null;
try {
mediaController = new MediaControllerCompat(NowPlayingActivity.this, token);
} catch (RemoteException e) {
Timber.e("Error creating media controller");
}
MediaControllerCompat.setMediaController(NowPlayingActivity.this,
mediaController);
buildTransportControls();
}
#Override
public void onConnectionSuspended() {
super.onConnectionSuspended();
}
#Override
public void onConnectionFailed() {
super.onConnectionFailed();
}
};
void buildTransportControls() {
mNowPlayingBinding.playingInfo.ibPlayPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PlaybackStateCompat pbState =
MediaControllerCompat.getMediaController(NowPlayingActivity.this).getPlaybackState();
if (pbState != null) {
MediaControllerCompat.TransportControls controls =
MediaControllerCompat.getMediaController(NowPlayingActivity.this).getTransportControls();
switch (pbState.getState()) {
case PlaybackStateCompat.STATE_PLAYING: // fall through
case PlaybackStateCompat.STATE_BUFFERING:
controls.pause();
stopSeekbarUpdate();
break;
case PlaybackStateCompat.STATE_PAUSED:
case PlaybackStateCompat.STATE_STOPPED:
controls.play();
scheduleSeekbarUpdate();
break;
default:
Timber.d("onClick with state " + pbState);
}
}
}
});
MediaControllerCompat mediaController =
MediaControllerCompat.getMediaController(NowPlayingActivity.this);
MediaMetadataCompat metadata = mediaController.getMetadata();
PlaybackStateCompat pbState = mediaController.getPlaybackState();
updatePlaybackState(pbState);
if (metadata != null) {
// Get the episode duration from the metadata and sets the end time to the textView
updateDuration(metadata);
}
// Set the current progress to the current position
updateProgress();
if (pbState != null && (pbState.getState() == PlaybackStateCompat.STATE_PLAYING ||
pbState.getState() == PlaybackStateCompat.STATE_BUFFERING)) {
scheduleSeekbarUpdate();
}
mediaController.registerCallback(controllerCallback);
}
MediaControllerCompat.Callback controllerCallback = new MediaControllerCompat.Callback() {
#Override
public void onMetadataChanged(MediaMetadataCompat metadata) {
super.onMetadataChanged(metadata);
if (metadata != null) {
updateDuration(metadata);
}
}
#Override
public void onPlaybackStateChanged(PlaybackStateCompat state) {
super.onPlaybackStateChanged(state);
// Update the playback state
updatePlaybackState(state);
}
};
/**
* Creates and executes a periodic action that becomes enabled first after the given initial delay,
* and subsequently with the given period;that is executions will commence after initialDelay
* then initialDelay + period, then initialDelay + 2 * period, and so on.
*/
private void scheduleSeekbarUpdate() {
stopSeekbarUpdate();
if (!mExecutorService.isShutdown()) {
mScheduleFuture = mExecutorService.scheduleAtFixedRate(
new Runnable() {
#Override
public void run() {
mHandler.post(mUpdateProgressTask);
}
}, 100,
1000, TimeUnit.MILLISECONDS);
}
}
/**
* Cancels the future returned by scheduleAtFixedRate() to stop the SeekBar from progressing.
*/
private void stopSeekbarUpdate() {
if (mScheduledFuture != null) {
mScheduledFuture.cancel(false);
}
}
/**
* Gets the episode duration from the metadata and sets the end time to be displayed in the TextView.
*/
private void updateDuration(MediaMetadataCompat metadata) {
if (metadata == null) {
return;
}
int duration = (int) metadata.getLong(MediaMetadataCompat.METADATA_KEY_DURATION)
* 1000;
mNowPlayingBinding.playingInfo.seekBar.setMax(duration);
mNowPlayingBinding.playingInfo.tvEnd.setText(
DateUtils.formatElapsedTime(duration / 1000));
}
/**
* Calculates the current position (distance = timeDelta * velocity) and sets the current progress
* to the current position.
*/
private void updateProgress() {
if (mLastPlaybackState == null) {
return;
}
long currentPosition = mLastPlaybackState.getPosition();
if (mLastPlaybackState.getState() == PlaybackStateCompat.STATE_PLAYING) {
// Calculate the elapsed time between the last position update and now and unless
// paused, we can assume (delta * speed) + current position is approximately the
// latest position. This ensure that we do not repeatedly call the getPlaybackState()
// on MediaControllerCompat.
long timeDelta = SystemClock.elapsedRealtime() -
mLastPlaybackState.getLastPositionUpdateTime();
currentPosition += (int) timeDelta * mLastPlaybackState.getPlaybackSpeed();
}
mNowPlayingBinding.playingInfo.seekBar.setProgress((int) currentPosition);
}
private void updatePlaybackState(PlaybackStateCompat state) {
if (state == null) {
return;
}
mLastPlaybackState = state;
switch (state.getState()) {
case PlaybackStateCompat.STATE_PLAYING:
hideLoading();
mNowPlayingBinding.playingInfo.ibPlayPause.setImageResource(R.drawable.exo_controls_pause);
scheduleSeekbarUpdate();
break;
case PlaybackStateCompat.STATE_PAUSED:
hideLoading();
mNowPlayingBinding.playingInfo.ibPlayPause.setImageResource(R.drawable.exo_controls_play);
stopSeekbarUpdate();
break;
case PlaybackStateCompat.STATE_NONE:
case PlaybackStateCompat.STATE_STOPPED:
hideLoading();
mNowPlayingBinding.playingInfo.ibPlayPause.setImageResource(R.drawable.exo_controls_play);
stopSeekbarUpdate();
break;
case PlaybackStateCompat.STATE_BUFFERING:
showLoading();
mNowPlayingBinding.playingInfo.ibPlayPause.setImageResource(R.drawable.exo_controls_play);
stopSeekbarUpdate();
break;
default:
Timber.d("Unhandled state " + state.getState());
}
}
This is my PodcastService.java:
public class PodcastService extends MediaBrowserServiceCompat implements Player.EventListener {
#Override
public void onCreate() {
super.onCreate();
initializeMediaSession();
}
private void initializeMediaSession() {
mMediaSession = new MediaSessionCompat(PodcastService.this, TAG);
mMediaSession.setFlags(
MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS |
MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
mStateBuilder = new PlaybackStateCompat.Builder()
.setActions(
PlaybackStateCompat.ACTION_PLAY |
PlaybackStateCompat.ACTION_PAUSE |
PlaybackStateCompat.ACTION_REWIND |
PlaybackStateCompat.ACTION_FAST_FORWARD |
PlaybackStateCompat.ACTION_PLAY_PAUSE);
mMediaSession.setPlaybackState(mStateBuilder.build());
mMediaSession.setCallback(new MySessionCallback());
setSessionToken(mMediaSession.getSessionToken());
mMediaSession.setSessionActivity(PendingIntent.getActivity(this,
11,
new Intent(this, NowPlayingActivity.class),
PendingIntent.FLAG_UPDATE_CURRENT));
}
private void initializePlayer() {
if (mExoPlayer == null) {
DefaultRenderersFactory defaultRenderersFactory = new DefaultRenderersFactory(this);
TrackSelector trackSelector = new DefaultTrackSelector();
LoadControl loadControl = new DefaultLoadControl();
mExoPlayer = ExoPlayerFactory.newSimpleInstance(this, defaultRenderersFactory,
trackSelector, loadControl);
mExoPlayer.addListener(this);
// Prepare the MediaSource
Uri mediaUri = Uri.parse(mUrl);
MediaSource mediaSource = buildMediaSource(mediaUri);
mExoPlayer.prepare(mediaSource);
mExoPlayer.setPlayWhenReady(true);
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent == null || intent.getAction() == null) {
Timber.e("intent in onStartCommand is null");
return START_STICKY;
}
// Check if the old player should be released
if (intent.getAction() != null && intent.getAction().equals(ACTION_RELEASE_OLD_PLAYER)) {
if (mExoPlayer != null) {
mExoPlayer.stop();
releasePlayer();
}
}
Bundle b = intent.getBundleExtra(EXTRA_ITEM);
if (b != null) {
mItem = b.getParcelable(EXTRA_ITEM);
mUrl = mItem.getEnclosures().get(0).getUrl();
}
initializePlayer();
// Convert hh:mm:ss string to seconds to put it into the metadata
long duration = PodUtils.getDurationInMilliSeconds(mItem);
MediaMetadataCompat metadata = new MediaMetadataCompat.Builder()
.putLong(MediaMetadataCompat.METADATA_KEY_DURATION, duration).build();
mMediaSession.setMetadata(metadata);
return START_STICKY;
}
private void releasePlayer() {
mExoPlayer.release();
mExoPlayer = null;
}
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
if (mExoPlayer != null) {
mExoPlayer.stop(true);
}
stopSelf();
}
#Override
public void onDestroy() {
mMediaSession.release();
releasePlayer();
super.onDestroy();
}
private MediaSource buildMediaSource(Uri mediaUri) {
String userAgent = Util.getUserAgent(this, getString(R.string.app_name));
DefaultDataSourceFactory dataSourceFactory = new DefaultDataSourceFactory(
this, userAgent);
CacheDataSourceFactory cacheDataSourceFactory =
new CacheDataSourceFactory(
DownloadUtil.getCache(this),
dataSourceFactory,
CacheDataSource.FLAG_IGNORE_CACHE_ON_ERROR);
return new ExtractorMediaSource.Factory(cacheDataSourceFactory).createMediaSource(mediaUri);
}
#Nullable
#Override
public BrowserRoot onGetRoot(#NonNull String clientPackageName, int clientUid,
#Nullable Bundle rootHints) {
return new BrowserRoot("pod_root_id", null);
}
#Override
public void onLoadChildren(#NonNull String parentMediaId,
#NonNull Result<List<MediaBrowserCompat.MediaItem>> result) {
// Browsing not allowed
if (TextUtils.equals("empty_root_id", parentMediaId)) {
result.sendResult(null);
return;
}
List<MediaBrowserCompat.MediaItem> mediaItems = new ArrayList<>();
// Check if this is the root menu:
if ("pod_root_id".equals(parentMediaId)) {
// Build the MediaItem objects for the top level,
// and put them in the mediaItems list...
} else {
// Examine the passed parentMediaId to see which submenu we're at,
// and put the children of that menu in the mediaItems list...
}
result.sendResult(mediaItems);
}
private class MySessionCallback extends MediaSessionCompat.Callback {
#Override
public void onPlay() {
startService(new Intent(getApplicationContext(), PodcastService.class));
mMediaSession.setActive(true);
// Start the player
if (mExoPlayer != null) {
mExoPlayer.setPlayWhenReady(true);
}
}
#Override
public void onPause() {
mExoPlayer.setPlayWhenReady(false);
stopForeground(false);
}
#Override
public void onRewind() {
mExoPlayer.seekTo(Math.max(mExoPlayer.getCurrentPosition() - 10000, 0));
}
#Override
public void onFastForward() {
long duration = mExoPlayer.getDuration();
mExoPlayer.seekTo(Math.min(mExoPlayer.getCurrentPosition() + 30000, duration));
}
#Override
public void onStop() {
stopSelf();
mMediaSession.setActive(false);
mExoPlayer.stop();
stopForeground(true);
}
#Override
public void onSeekTo(long pos) {
super.onSeekTo(pos);
if (mExoPlayer != null) {
mExoPlayer.seekTo((int) pos);
}
}
}
// Player Event Listeners
#Override
public void onTimelineChanged(Timeline timeline, #Nullable Object manifest, int reason) {
}
#Override
public void onPlayerError(ExoPlaybackException error) {
}
#Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
if (playbackState == Player.STATE_IDLE) {
mStateBuilder.setState(PlaybackStateCompat.STATE_PAUSED,
mExoPlayer.getCurrentPosition(), 1f);
} else if (playbackState == Player.STATE_BUFFERING) {
mStateBuilder.setState(PlaybackStateCompat.STATE_BUFFERING,
mExoPlayer.getCurrentPosition(), 1f);
} else if (playbackState == Player.STATE_READY && playWhenReady) {
mStateBuilder.setState(PlaybackStateCompat.STATE_PLAYING,
mExoPlayer.getCurrentPosition(), 1f);
Timber.d("onPlayerStateChanged: we are playing");
} else if (playbackState == Player.STATE_READY) {
mStateBuilder.setState(PlaybackStateCompat.STATE_PAUSED,
mExoPlayer.getCurrentPosition(), 1f);
Timber.d("onPlayerStateChanged: we are paused");
} else if (playbackState == Player.STATE_ENDED) {
mStateBuilder.setState(PlaybackStateCompat.STATE_PAUSED,
mExoPlayer.getCurrentPosition(), 1f);
} else {
mStateBuilder.setState(PlaybackStateCompat.STATE_NONE,
mExoPlayer.getCurrentPosition(), 1f);
}
mMediaSession.setPlaybackState(mStateBuilder.build());
}
}
Edit: The full source code is available here.
To set the state progress based on value should use setProgress(value) method.
when paused the music save value from seekBar as an Integer, then when resume it get that value and put it as a parameter in setProgress() method.
when you pause music to save the value:
#Override
protected void onPause() {
super.onPause();
mSeekBarRate.setOnSeekBarChangeListener(
new SeekBar.OnSeekBarChangeListener() {
int progress = 0;
#Override
public void onProgressChanged(SeekBar mSeekBarRate, int progressValue, boolean fromUser) {
progress = progressValue;
}
#Override
public void onStartTrackingTouch(SeekBar mSeekBarRate) {
}
#Override
public void onStopTrackingTouch(SeekBar mSeekBarRate) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("value", progress);
}
});
}
when you resume music retrieve that value:
#Override
protected void onStart() {
super.onStart();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
int value = prefs.getInt("value", 0);
mSeekBarRate.setProgress(value);
}
Hope it Helps you.

Error on the second listen SpeechRecognizer

I have a problem with SpeechRecognizer on android. Here's my code:
public class MyRecognizerListener implements RecognitionListener {
String id;
MyRecognizerListener(String id){
this.id = id;
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onBeginningOfSpeech() {
Log.d("Speech", "Inizia ad Ascoltare");
}
#Override
public void onReadyForSpeech(Bundle params) {
Log.d("Speech", "E' pronto ad Ascoltare");
}
#Override
public void onPartialResults(Bundle results) {
matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
if(matches.size() > 1) {
Log.d("Speech", "Risultati Parziali = " + Integer.toString(matches.size()));
for (int i = 0; i < matches.size(); i++) {
Log.d("Speech", matches.get(i));
}
if (matches.contains("si") || matches.contains("sì") || matches.contains("Sì")
|| matches.contains("yes") || matches.contains("ES")) {
Opera opera = createOpera(id);
startAudio(opera);
}
matches = null;
turnSpeechOff = false;
speechRecognizer.cancel();
speechRecognizer.destroy();
speechRecognizer = null;
}
}
#Override
public void onEvent(int eventType, Bundle params) {
}
#Override
public void onError(int error) {
if(turnSpeechOff) {
Log.d("Speech", Integer.toString(error));
turnSpeechOff = false;
speechRecognizer.cancel();
speechRecognizer.destroy();
speechRecognizer = null;
}
}
#Override
public void onRmsChanged(float rmsdB) {
}
#Override
public void onBufferReceived(byte[] buffer) {
}
#Override
public void onResults(Bundle results) {
matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
for (int i = 0; i < matches.size(); i++){
Log.d("Parole", matches.get(i));
}
if(matches.contains("si") || matches.contains("sì") || matches.contains("Sì")
|| matches.contains("yes") || matches.contains("ES")){
Opera opera = createOpera(id);
startAudio(opera);
}
matches = null;
turnSpeechOff = false;
speechRecognizer.cancel();
speechRecognizer.destroy();
speechRecognizer = null;
}
}
public void startAudioAsk(final String art_id){
if(speechRecognizer != null) {
return;
}
if(audioPlayer == null || !audioPlayer.isPlaying() ) {
if(operaAudioAsk != null && operaAudioAsk.equals(art_id)){
return;
}
operaAudioAsk = art_id;
if(language.equals("IT")) {
audioPlayer = MediaPlayer.create(this, R.raw.chiedi);
} else {
audioPlayer = MediaPlayer.create(this, R.raw.ask);
}
audioPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
audioPlayer.reset();
audioPlayer.release();
int audioTitle;
if(language.equals("IT")){
audioTitle = getResources().getIdentifier(art_id + "_title" + "_it", "raw", getPackageName());
audioPlayer = MediaPlayer.create(MainActivity.this, audioTitle);
} else {
audioTitle = getResources().getIdentifier(art_id + "_title" + "_en", "raw", getPackageName());
audioPlayer = MediaPlayer.create(MainActivity.this, audioTitle);
}
audioPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
askVoice(art_id);
audioPlayer.reset();
audioPlayer.release();
audioPlayer = null;
}
});
audioPlayer.start();
}
});
audioPlayer.start();
}
}
public void askVoice(String art_id){
if(speechRecognizer == null) {
speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
speechRecognizer.setRecognitionListener(new MyRecognizerListener(art_id));
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getPackageName());
intent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 3);
intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
if(language.equals("IT")){
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "it");
} else {
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en_US");
}
speechRecognizer.startListening(intent);
voiceTimer = new Timer();
voiceTimer.schedule(new StopVoiceManager(), 2000);
Log.d("Speech", "Starta");
}
}
public void stopVoice(){
if(speechRecognizer != null){
Log.d("Speech", "Cancello");
turnSpeechOff = true;
speechRecognizer.stopListening();
}
}
public class StopVoiceManager extends TimerTask{
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
stopVoice();
Log.d("Speech", "Prova a Cancellare");
}
});
}
}
As you can see, there's also a task that, after 2 seconds, calls speechRecognizer.stoplistening().
The first listening is ok, I say "yes" and it recognizes it, but the second listening raises the ERROR_CLIENT and it doesn't recognize anything, then the third listening returns to be ok, the fourth doesn't recognize anything and so.
How can i fix this bug?

Android Studio - Sending a Bluetooth PIN automatically

I am looking at the following code by Lorensius W. L. T
I have seen other posts about sending a PIN automatically (e.g. 1234) to the device when it pairs so that there is no user prompt. I can't figure it out how to add their code fragments to get it to work.
How is the following code modified to achieve this?
/**
* Device list.
*
* #author Lorensius W. L. T <lorenz#londatiga.net>
*
*/
public class DeviceListActivity extends Activity {
private ListView mListView;
private DeviceListAdapter mAdapter;
private ArrayList<BluetoothDevice> mDeviceList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_paired_devices);
mDeviceList = getIntent().getExtras().getParcelableArrayList("device.list");
mListView = (ListView) findViewById(R.id.lv_paired);
mAdapter = new DeviceListAdapter(this);
mAdapter.setData(mDeviceList);
mAdapter.setListener(new DeviceListAdapter.OnPairButtonClickListener() {
#Override
public void onPairButtonClick(int position) {
BluetoothDevice device = mDeviceList.get(position);
if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
unpairDevice(device);
} else {
showToast("Pairing...");
pairDevice(device);
}
}
});
mListView.setAdapter(mAdapter);
registerReceiver(mPairReceiver, new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED));
}
#Override
public void onDestroy() {
unregisterReceiver(mPairReceiver);
super.onDestroy();
}
private void showToast(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
private void pairDevice(BluetoothDevice device) {
try {
Method method = device.getClass().getMethod("createBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
}
private void unpairDevice(BluetoothDevice device) {
try {
Method method = device.getClass().getMethod("removeBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
}
private final BroadcastReceiver mPairReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
final int prevState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR);
if (state == BluetoothDevice.BOND_BONDED && prevState == BluetoothDevice.BOND_BONDING) {
showToast("Paired");
} else if (state == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDED){
showToast("Unpaired");
}
mAdapter.notifyDataSetChanged();
}
}
};
}

Android Bluetooth connection error

I'm developing a bluetooth app to control an Arduino board, but now I made some mistakes: when I try to make a connection from my phone, it displays an AlertDialog (it is OK) and a lot of Toasts (they're called from onSensorChanged).
The BT module connected to the board is OK (tested with other apps), so the problem is Java: I can't make a connection to my BT module. Unfortunately, Android Studio doesn't give me any logcat or errors.
This is my code:
/* imports... */
public class MainActivity extends AppCompatActivity implements SensorEventListener {
/* Bluetooth */
private static final int REQUEST_ENABLE_BT = 1;
private String selectedDevice = "";
static final UUID defaultUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //This SPP UUID should work for most devices.
//private boolean isConnected = false;
BluetoothAdapter bluetoothAdapter;
BluetoothSocket bluetoothSocket;
/* Is in full screen = ? */
private boolean FullScreenState = true;
/* Views */
private SeekBar steeringWheel;
private SeekBar forwardsSpeed;
private SeekBar backwardsSpeed;
private Toolbar toolbar;
/* Dialogs */
AlertDialog.Builder errorDialog;
AlertDialog.Builder listDialog;
ProgressDialog progressDialog;
/* Accelerometer managers */
Sensor accelerometer;
SensorManager sensorManager;
float Y = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
(...)
/* Views */
steeringWheel = (SeekBar) findViewById(R.id.Steering_wheel);
forwardsSpeed = (SeekBar) findViewById(R.id.Forwards_speed);
backwardsSpeed = (SeekBar) findViewById(R.id.Backwards_speed);
/* listDialogs */
listDialog = new AlertDialog.Builder(this);
listDialog.setCancelable(true);
listDialog.setTitle(R.string.app_name);
//listDialog.setMessage("Select a device:");
listDialog.setIcon(R.drawable.launcher_icon);
//listDialog.setView(devicesListView);
listDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
/* errorDialog */
errorDialog = new AlertDialog.Builder(this);
errorDialog.setCancelable(false);
errorDialog.setTitle(R.string.app_name);
errorDialog.setIcon(R.drawable.error_material);
errorDialog.setPositiveButton("I got it", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
/* Set the full screen and keep the screen always on... */
/* Accelerometer initializer... */
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
...
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
...
if (id == R.id.toolbar_connect) {
initializeBT();
return true;
} else if (id == R.id.toolbar_settings) {
/* Settings activity. Coming soon. */
return true;
} else if (id == R.id.toolbar_disconnect) {
if (bluetoothSocket != null) {
try {
bluetoothSocket.close();
} catch (IOException e) {
errorDialog.setMessage("Disconnection error!");
errorDialog.show();
}
}
return true;
}
...
}
#Override
public void onSensorChanged(SensorEvent event) {
/* Get the axes */
Y = event.values[1];
/* Set the steering wheel position */
steeringWheel.setProgress((int)Y + 10);
send(String.valueOf(steeringWheel.getProgress()));
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
...
}
private class connect extends AsyncTask<Void, Void, Void> {
private boolean connectionSuccess = false;
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(MainActivity.this, "Connecting...", "Creating bluetooth connection");
}
#Override
protected Void doInBackground(Void... devices) {
try {
if (bluetoothSocket == null) {
//if ((bluetoothSocket == null) || (!isConnected)) {
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice arduino = bluetoothAdapter.getRemoteDevice(selectedDevice);
bluetoothSocket = arduino.createInsecureRfcommSocketToServiceRecord(defaultUUID);
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
bluetoothSocket.connect();
connectionSuccess = true;
}
} catch (IOException e) {
connectionSuccess = false;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (!connectionSuccess) {
errorDialog.setMessage("Connection error!");
errorDialog.show();
bluetoothSocket = null;
} else {
Toast.makeText(getApplicationContext(), "Successfully connected", Toast.LENGTH_LONG).show();
//isConnected = true;
}
progressDialog.dismiss();
}
}
void initializeBT() {
/* Check for Bluetooth support */
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
errorDialog.setMessage("Unfortunately, Bluetooth connection isn't supported on your device.");
errorDialog.show();
} else if (!bluetoothAdapter.isEnabled()) {
/* Bluetooth disables -> enable it */
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
} else {
devicesPrompt();
}
}
void devicesPrompt() {
//final ArrayList<String> devicesList = new ArrayList()<String>;
Set<BluetoothDevice> pairedDevices;
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
pairedDevices = bluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for(BluetoothDevice bluetoothDevice : pairedDevices) {
/* Get the device's name and the address */
//devicesList.add(bt.getName() + "\n" + bt.getAddress());
adapter.add(bluetoothDevice.getName() + "\n" + bluetoothDevice.getAddress());
}
} else {
Toast.makeText(getApplicationContext(), "No paired Bluetooth devices found!", Toast.LENGTH_LONG).show();
}
listDialog.setAdapter(adapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Log.d("RoverBluetooth!!", String.valueOf(which));
//;
String info = adapter.getItem(which);
selectedDevice = info.substring(info.length() - 17);
new connect().execute();
dialog.dismiss();
}
});
listDialog.show();
}
public void send(String message) {
message = message + "/r";
if (bluetoothSocket != null) {
try {
bluetoothSocket.getOutputStream().write(message.getBytes());
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Error during sending", Toast.LENGTH_SHORT).show();
Log.d("RoverBluetooth errors", e.toString());
}
}
}
public void buttonsActions(View view) {
int viewId = view.getId();
if (viewId == R.id.Forwards_button) { //ON
send(String.valueOf(forwardsSpeed.getProgress() + 1000));
} else if (viewId == R.id.Stop_button) { //OFF
send("21");
} else if (viewId == R.id.Backwards_button) { //Backwards
send(String.valueOf(backwardsSpeed.getProgress() + 1500));
} else if (viewId == R.id.Light_ON) { //Light ON
send("22");
} else if (viewId == R.id.Light_OFF) { //Light OFF
send("23");
}
}
}
I already wrote a class to make a bluetooth connection between Android and Arduino. I suppose you're using a HC-06 (or -05 ?). My code is on github:
https://github.com/omaflak/Bluetooth-Android
I also wrote a tutorial on my blog, you may want to take a look at it:
https://causeyourestuck.io/2015/12/14/communication-between-android-and-hc-06-module/
Good luck!

Categories