Failed to send data from arduino - java

I have connected the android application to the arduino successfully but it seems that i can't get the data even though I used the input stream ... I dont know whats wronge been looking and trying other solution for couple of days ..
Android Studio Code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bluetooth = new BluetoothSPP(this);
text = (TextView) findViewById(R.id.textView2);
connect = (Button) findViewById(R.id.connect);
on = (Button) findViewById(R.id.on);
BluetoothSocket socket = null;
mAdapter = BluetoothAdapter.getDefaultAdapter();
if (!bluetooth.isBluetoothAvailable()) {
Toast.makeText(getApplicationContext(), "Bluetooth is not available", Toast.LENGTH_SHORT).show();
finish();
}
bluetooth.setBluetoothConnectionListener(new BluetoothSPP.BluetoothConnectionListener() {
public void onDeviceConnected(String name, String address) {
connect.setText("Connected to " + name);
}
public void onDeviceDisconnected() {
connect.setText("Connection lost");
}
public void onDeviceConnectionFailed() {
connect.setText("Unable to connect");
}
});
connect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (bluetooth.getServiceState() == BluetoothState.STATE_CONNECTED) {
bluetooth.disconnect();
} else {
Intent intent = new Intent(getApplicationContext(), DeviceList.class);
startActivityForResult(intent, BluetoothState.REQUEST_CONNECT_DEVICE);
}
}
});
on.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
/*off.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bluetooth.send(OFF, true);
}
});*/
}
public void onStart() {
super.onStart();
if (!bluetooth.isBluetoothEnabled()) {
bluetooth.enable();
} else {
if (!bluetooth.isServiceAvailable()) {
bluetooth.setupService();
bluetooth.startService(BluetoothState.DEVICE_OTHER);
}
}
}
< /* class ConnectedThread extends Thread {
private InputStream mInStream;
public ConnectedThread(BluetoothSocket socket) throws IOException {
InputStream tmpIn = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
} catch (IOException e) {
}
mInStream = tmpIn;
}
}
public void run() {
BufferedReader r = new BufferedReader(new InputStreamReader(mInStream));
while (true) {
try {
int a = r.read();
Log.d(TAG, Integer.toString(a));
} catch (IOException e) {
break;
}
}
}
}*/
void beginListenForData() {
final Handler handler = new Handler();
final byte delimiter = 10; //This is the ASCII code for a newline character
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable() {
public void run() {
while (!Thread.currentThread().isInterrupted() && !stopWorker) {
try {
int bytesAvailable = mmInputStream.available();
if (bytesAvailable > 0) {
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);
for (int i = 0; i < bytesAvailable; i++) {
byte b = packetBytes[i];
if (b == delimiter) {
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable() {
public void run() {
text.setText(data);
}
});
} else {
readBuffer[readBufferPosition++] = b;
}
}
}
} catch (IOException ex) {
stopWorker = true;
}
}
}
});
workerThread.start();
}
void closeBT() throws IOException {
stopWorker = true;
mmOutputStream.close();
mmInputStream.close();
text.setText("Bluetooth Closed");
}
public void onDestroy() {
super.onDestroy();
bluetooth.stopService();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == BluetoothState.REQUEST_CONNECT_DEVICE) {
if (resultCode == Activity.RESULT_OK)
bluetooth.connect(data);
} else if (requestCode == BluetoothState.REQUEST_ENABLE_BT) {
if (resultCode == Activity.RESULT_OK) {
bluetooth.setupService();
} else {
Toast.makeText(getApplicationContext()
, "Bluetooth was not enabled."
, Toast.LENGTH_SHORT).show();
finish();
}
}
}
Arduino Code:

You don't need InputStream and OutputStream as you are not using native android RFCOMM bluetooth api. I googled BluetoothSPP class and find out you were using this github library for blutooth spp communication: akexorcist/Android-BluetoothSPPLibrary
Your code seem to work for connecting / disconnecting to your arduino device. So, I deem you proprely integrated the library. What is missing is the code to send / receive bluetooth data. I updated your code as following:
on.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bluetooth.send("ON", true);
}
});
off.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bluetooth.send("OFF", true);
}
});
bluetooth.setOnDataReceivedListener(new OnDataReceivedListener() {
public void onDataReceived(byte[] data, String message) {
Toast.makeText(getApplicationContext(), String.format("Data Received: %s", message), Toast.LENGTH_SHORT).show();
}
});

Related

How to have a single instance of exoPlayer in a background?

I have almost a week figuring out how should I have one instance of exoplayer in background.
I want to use this instance in a playerview and in notification as well. Problem I am facing now, the player plays well, after a time it pauses (to release resource I guess), but when i click play it plays again, when i click other oudio, I get two audio playing at same time.
Here are my codes.
------------------------ BACKGROUND SERVICE --------------------------------------
public class BackgroundPlayingService extends Service {
public static PlayerNotificationManager playerNotificationManager;
public static ExoPlayer exoPlayer;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (this.exoPlayer == null){
createPlayer();
}
/////////////////THIS WAS ADDED LATER
return START_STICKY;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onDestroy() {
super.onDestroy();
exoPlayer.pause();
exoPlayer = null;
playerNotificationManager.setPlayer(null);
}
private void createPlayer(){
exoPlayer = new ExoPlayer.Builder(this).build();
MediaItem mediaItem;
try {
mediaItem = MediaItem.fromUri(Uri.parse(DataUtility.playingUrl));
}catch (Exception e){
mediaItem = MediaItem.fromUri(Uri.parse("https://server13.mp3quran.net/husr/062.mp3"));
}
exoPlayer.setMediaItem(mediaItem);
exoPlayer.prepare();
exoPlayer.addListener(new Player.Listener() {
#Override
public void onPlaybackStateChanged(int playbackState) {
Player.Listener.super.onPlaybackStateChanged(playbackState);
try {
if (ThePlayingActivity.dialog.isShowing()){
ThePlayingActivity.dialog.dismiss();}
}catch (Exception ignore){
}
if (playbackState==Player.STATE_READY){
try {
ThePlayingActivity.downloadBtn.setVisibility(View.VISIBLE);
showNotification();
}catch (Exception ignore){
}
}
if (playbackState == Player.STATE_BUFFERING) {
try {
ThePlayingActivity.myProgress.setVisibility(View.VISIBLE);
}catch (Exception e){
}
} else {
try {
ThePlayingActivity.myProgress.setVisibility(View.GONE);
}catch (Exception e){
}
}
}
#Override
public void onIsLoadingChanged(boolean isLoading) {
Player.Listener.super.onIsLoadingChanged(isLoading);
}
#Override
public void onPlayerError(PlaybackException error) {
Player.Listener.super.onPlayerError(error);
try {
if (ThePlayingActivity.dialog.isShowing()){
ThePlayingActivity.dialog.dismiss();
}
playerNotificationManager.setPlayer(null);
}catch (Exception ignore){
}
}
});
exoPlayer.play();
try {
ThePlayingActivity.myPlayerView.setPlayer(exoPlayer);
}catch (Exception e){
Log.d("background", "createPlayer: set player to view"+e.getLocalizedMessage());
}
}
public static void setNewPlayeData(){
MediaItem mediaItem = MediaItem.fromUri(Uri.parse(DataUtility.playingUrl));
exoPlayer.setMediaItem(mediaItem);
exoPlayer.prepare();
ThePlayingActivity.myPlayerView.setPlayer(exoPlayer);
try {
ThePlayingActivity.myPlayerView.setPlayer(exoPlayer);
}catch (Exception e){
Log.d("background", "createPlayer: set player to view"+e.getLocalizedMessage());
}
}
public void showNotification() {
playerNotificationManager = new PlayerNotificationManager.Builder(this, 151,
this.getResources().getString(R.string.app_name))
.setChannelNameResourceId(R.string.app_name)
.setChannelImportance(IMPORTANCE_HIGH)
.setMediaDescriptionAdapter(new PlayerNotificationManager.MediaDescriptionAdapter() {
#Override
public CharSequence getCurrentContentTitle(Player player) {
return player.getCurrentMediaItem().mediaMetadata.displayTitle;
}
#Nullable
#Override
public PendingIntent createCurrentContentIntent(Player player) {
return null;
}
#Nullable
#Override
public CharSequence getCurrentContentText(Player player) {
return Objects.requireNonNull(player.getCurrentMediaItem()).mediaMetadata.artist;
}
#Nullable
#Override
public Bitmap getCurrentLargeIcon(Player player, PlayerNotificationManager.BitmapCallback callback) {
return null;
}
}).setNotificationListener(new PlayerNotificationManager.NotificationListener() {
#Override
public void onNotificationCancelled(int notificationId, boolean dismissedByUser) {
}
#Override
public void onNotificationPosted(int notificationId, Notification notification, boolean ongoing) {
PlayerNotificationManager.NotificationListener.super.onNotificationPosted(notificationId, notification, ongoing);
}
})
.build();
playerNotificationManager.setUseStopAction(false);
try {
playerNotificationManager.setPlayer(exoPlayer);
}catch (Exception e){
}
}
}
-----------------------HERE IS THE ACTIVITY WITH PLAYER ----------------------------------
public class ThePlayingActivity extends AppCompatActivity {
private static final int PERMISION_STORAGE_CODE = 100;
private ProgressBar downloadingProgress;
public static ProgressBar myProgress;
public static Dialog dialog;
private ConstraintLayout layoutForSnack;
long downloadId;
private PowerManager powerManager;
private PowerManager.WakeLock wakeLock;
String myurl;
public static PlayerControlView myPlayerView;
private TextView currentPlaying, downloadingTv;
public static Button downloadBtn;
private String thePlayingSura;
private final BroadcastReceiver onDownloadComplete = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID,-1);
if (downloadId == id){
downloadingProgress.setVisibility(View.GONE);
downloadingTv.setVisibility(View.GONE);
downloadBtn.setText("DOWNLOADED");
downloadBtn.setBackgroundColor(Color.TRANSPARENT);
downloadBtn.setTextColor(Color.BLACK);
downloadBtn.setClickable(false);
Toast.makeText(context, "DOWNLOAD COMPLETED", Toast.LENGTH_SHORT).show();
}
}
};
#SuppressLint("SetTextI18n")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_the_playing);
myPlayerView = findViewById(R.id.playerView);
Intent dataIntent = getIntent();
myurl = dataIntent.getStringExtra("theUrl");
if (BackgroundPlayingService.exoPlayer == null){
startService();}else{
BackgroundPlayingService.setNewPlayeData();
myPlayerView.setPlayer(BackgroundPlayingService.exoPlayer);
}
keepActivityAlive();
registerReceiver(onDownloadComplete,new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
downloadingProgress = findViewById(R.id.downloadProgress);
downloadingTv = findViewById(R.id.downloadingWaitTv);
currentPlaying = findViewById(R.id.currentPlaying);
downloadBtn = findViewById(R.id.downloadbtn);
downloadBtn.setVisibility(View.GONE);
myProgress = findViewById(R.id.progressBar2);
myProgress.setVisibility(View.GONE);
layoutForSnack = findViewById(R.id.constraintLayout);
downloadingProgress.setVisibility(View.GONE);
downloadingTv.setVisibility(View.GONE);
thePlayingSura = dataIntent.getStringExtra("sendSuraName");
currentPlaying.setText(thePlayingSura+" - " + DataUtility.theKariName);
/////////////end of ids
showLoadingDialog();
/////////////////download
downloadBtn.setOnClickListener(view -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED){
//todo ask permission
String permissions[] = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permissions,PERMISION_STORAGE_CODE);
}else{
downloadStaffs();
}
}else {
//TODO DOWNLOAD
downloadStaffs();
}
});
/////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
}
#Override
public void onBackPressed() {
super.onBackPressed();
//todo fire service (may be)
}
private void showLoadingDialog() {
dialog = new Dialog(ThePlayingActivity.this);
dialog.setContentView(R.layout.dialog_loading_quran);
dialog.setCancelable(false);
dialog.show();
}
private void showSnackBar() {
Snackbar snackbar = Snackbar.make(layoutForSnack, "THERE WAS ON ERROR, CHECK YOUR INTERNET CONNECTION", Snackbar.LENGTH_INDEFINITE);
snackbar.setAction("RETRY", view -> {
});
snackbar.setActionTextColor(Color.YELLOW);
snackbar.show();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case PERMISION_STORAGE_CODE:{
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
// we have permission
//todo Download
downloadStaffs();
}else{
Toast.makeText(ThePlayingActivity.this , "PERMISSION DENIED... CAN NOT DOWNLOAD", Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(onDownloadComplete);
try {
if (wakeLock.isHeld()){
wakeLock.release();}
}catch (Exception ignore){
}
}
private void downloadStaffs(){
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(DataUtility.playingUrl));
request.setDescription("Download File");
request.setTitle(thePlayingSura);
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, thePlayingSura+" - "+ DataUtility.theKariName+".mp3");
final DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
final long downloadId = manager.enqueue(request);
this.downloadId = downloadId;
final ProgressBar mProgressBar = (ProgressBar) findViewById(R.id.downloadProgress);
downloadingTv.setVisibility(View.VISIBLE);
mProgressBar.setVisibility(View.VISIBLE);
new Thread(new Runnable() {
#SuppressLint("Range")
#Override
public void run() {
boolean downloading = true;
while (downloading) {
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterById(downloadId);
Cursor cursor = manager.query(q);
cursor.moveToFirst();
#SuppressLint("Range") int bytes_downloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
#SuppressLint("Range") int bytes_total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {
downloading = false;
}
final double dl_progress = (int) ((bytes_downloaded * 100l) / bytes_total);
runOnUiThread(new Runnable() {
#Override
public void run() {
mProgressBar.setProgress((int) dl_progress);
}
});
Log.d("MESSAGES", statusMessage(cursor));
cursor.close();
}
}
}).start();
}
#SuppressLint("Range")
private String statusMessage(Cursor c) {
String msg = "???";
switch (c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS))) {
case DownloadManager.STATUS_FAILED:
msg = "Download failed!";
break;
case DownloadManager.STATUS_PAUSED:
msg = "Download paused!";
break;
case DownloadManager.STATUS_PENDING:
msg = "Download pending!";
break;
case DownloadManager.STATUS_RUNNING:
msg = "Download in progress!";
break;
case DownloadManager.STATUS_SUCCESSFUL:
msg = "Download complete!";
break;
default:
msg = "Download is nowhere in sight";
break;
}
return (msg);
}
}
private void keepActivityAlive(){
powerManager = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"QuranAudio:WakeLock");
}
private void startService(){
Intent i = new Intent(this, BackgroundPlayingService.class);
startService(i);
}
}
I figured it out.
I had to keep most of my business inside in onStartCommand
public class BackgroundPlayingService extends Service {
public static final String TAG = "bck_service";
public static ExoPlayer player;
public static PlayerNotificationManager playerNotificationManager;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String url = DataUtility.playingUrl;
if (url==null){
url = "https://server8.mp3quran.net/afs/Rewayat-AlDorai-A-n-Al-Kisa-ai/025.mp3";
}
if (player == null){
player = createPlayerIfNull();
MediaItem mediaItem = MediaItem.fromUri(Uri.parse(url));
player.setMediaItem(mediaItem);
player.prepare();
player.addListener(new Player.Listener() {
#Override
public void onEvents(Player player, Player.Events events) {
}
#Override
public void onPlaybackStateChanged(int playbackState) {
Player.Listener.super.onPlaybackStateChanged(playbackState);
try {
if (ThePlayingActivity.dialog.isShowing()){
ThePlayingActivity.dialog.dismiss();}
}catch (Exception ignore){
}
if (playbackState==Player.STATE_READY){
try {
ThePlayingActivity.downloadBtn.setVisibility(View.VISIBLE);
showNotification();
}catch (Exception ignore){
}
}
if (playbackState == Player.STATE_BUFFERING) {
try {
ThePlayingActivity.myProgress.setVisibility(View.VISIBLE);
}catch (Exception e){
}
} else {
try {
ThePlayingActivity.myProgress.setVisibility(View.GONE);
}catch (Exception e){
}
}
}
#Override
public void onIsLoadingChanged(boolean isLoading) {
Player.Listener.super.onIsLoadingChanged(isLoading);
}
#Override
public void onPlayerError(PlaybackException error) {
Player.Listener.super.onPlayerError(error);
try {
if (ThePlayingActivity.dialog.isShowing()){
ThePlayingActivity.dialog.dismiss();}
}catch (Exception ignore){
}
}
});
player.play();
try {
ThePlayingActivity.myPlayerView.setPlayer(player);
}catch (Exception ignore){}
}
//notification
createNotificationChannel();
Intent i = new Intent(this,BackgroundPlayingService.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,i,0);
Notification notification = new NotificationCompat.Builder(this,"myChannelId")
.setContentTitle("QURAN IS PLAYING")
.setContentText("This means that Qur-an app is open. You can close it from app exit menu")
.setSmallIcon(androidx.core.R.drawable.notification_icon_background)
.setContentIntent(pendingIntent)
.build();
startForeground(1,notification);
return START_STICKY;
}
public ExoPlayer createPlayerIfNull() {
if (player == null) {
player = new ExoPlayer.Builder(BackgroundPlayingService.this).build();
ThePlayingActivity.myProgress.setVisibility(View.VISIBLE);
try {
ThePlayingActivity.dialog.show();
}catch (Exception e){
Log.d(TAG, "createPlayerIfNull: ");
}
}
return player;
}
private void createNotificationChannel(){
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
NotificationChannel channel = new NotificationChannel("myChannelId","qur-anAudiChannel", NotificationManager.IMPORTANCE_LOW);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
}
#Override
public void onDestroy() {
super.onDestroy();
player.stop();
player = null;
stopForeground(true);
}
public void showNotification() {
playerNotificationManager = new PlayerNotificationManager.Builder(this, 151,
this.getResources().getString(R.string.app_name))
.setChannelNameResourceId(R.string.app_name)
.setChannelImportance(IMPORTANCE_HIGH)
.setMediaDescriptionAdapter(new PlayerNotificationManager.MediaDescriptionAdapter() {
#Override
public CharSequence getCurrentContentTitle(Player player) {
return player.getCurrentMediaItem().mediaMetadata.displayTitle;
}
#Nullable
#Override
public PendingIntent createCurrentContentIntent(Player player) {
return null;
}
#Nullable
#Override
public CharSequence getCurrentContentText(Player player) {
return Objects.requireNonNull(player.getCurrentMediaItem()).mediaMetadata.artist;
}
#Nullable
#Override
public Bitmap getCurrentLargeIcon(Player player, PlayerNotificationManager.BitmapCallback callback) {
return null;
}
}).setNotificationListener(new PlayerNotificationManager.NotificationListener() {
#Override
public void onNotificationCancelled(int notificationId, boolean dismissedByUser) {
}
#Override
public void onNotificationPosted(int notificationId, Notification notification, boolean ongoing) {
PlayerNotificationManager.NotificationListener.super.onNotificationPosted(notificationId, notification, ongoing);
}
})
.build();
playerNotificationManager.setUseStopAction(false);
try {
playerNotificationManager.setPlayer(player);
}catch (Exception e){
}}
}
-------------------- player view activity ------------------------------------
public class ThePlayingActivity extends AppCompatActivity {
private static final int PERMISION_STORAGE_CODE = 100;
private ProgressBar downloadingProgress;
public static ProgressBar myProgress;
public static Dialog dialog;
private ConstraintLayout layoutForSnack;
long downloadId;
private PowerManager powerManager;
private PowerManager.WakeLock wakeLock;
String myurl;
public static PlayerControlView myPlayerView;
private TextView currentPlaying, downloadingTv;
public static Button downloadBtn;
private String thePlayingSura;
private BroadcastReceiver onDownloadComplete = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
if (downloadId == id) {
downloadingProgress.setVisibility(View.GONE);
downloadingTv.setVisibility(View.GONE);
downloadBtn.setText("DOWNLOADED");
downloadBtn.setBackgroundColor(Color.TRANSPARENT);
downloadBtn.setTextColor(Color.BLACK);
downloadBtn.setClickable(false);
Toast.makeText(context, "DOWNLOAD COMPLETED", Toast.LENGTH_SHORT).show();
}
}
};
#SuppressLint("StaticFieldLeak")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_the_playing);
myPlayerView = findViewById(R.id.playerView);
Intent dataIntent = getIntent();
myurl = dataIntent.getStringExtra("theUrl");
Intent backgroundPlayIntent = new Intent(ThePlayingActivity.this,BackgroundPlayingService.class);
try {
stopService(backgroundPlayIntent);
}catch (Exception e){}
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
startForegroundService(backgroundPlayIntent);
}else{
startService(backgroundPlayIntent);
}
keepActivityAlive();
registerReceiver(onDownloadComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
downloadingProgress = findViewById(R.id.downloadProgress);
downloadingTv = findViewById(R.id.downloadingWaitTv);
currentPlaying = findViewById(R.id.currentPlaying);
downloadBtn = findViewById(R.id.downloadbtn);
downloadBtn.setVisibility(View.GONE);
myProgress = findViewById(R.id.progressBar2);
myProgress.setVisibility(View.VISIBLE);
layoutForSnack = findViewById(R.id.constraintLayout);
downloadingProgress.setVisibility(View.GONE);
downloadingTv.setVisibility(View.GONE);
thePlayingSura = dataIntent.getStringExtra("sendSuraName");
currentPlaying.setText(thePlayingSura + " - " + DataUtility.theKariName);
/////////////end of ids
showLoadingDialog();
/////////////////download
downloadBtn.setOnClickListener(view -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
String permissions[] = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permissions, PERMISION_STORAGE_CODE);
} else {
downloadStaffs();
}
} else {
downloadStaffs();
}
});
}
private void showLoadingDialog() {
dialog = new Dialog(ThePlayingActivity.this);
dialog.setContentView(R.layout.dialog_loading_quran);
dialog.setCancelable(false);
dialog.show();
}
public void showSnackBar() {
Snackbar snackbar = Snackbar.make(layoutForSnack, "THERE WAS ON ERROR, CHECK YOUR INTERNET CONNECTION", Snackbar.LENGTH_INDEFINITE);
snackbar.setAction("RETRY", view -> {
//todo retry player
});
snackbar.setActionTextColor(Color.YELLOW);
snackbar.show();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PERMISION_STORAGE_CODE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// we have permission
downloadStaffs();
} else {
Toast.makeText(ThePlayingActivity.this, "PERMISSION DENIED... CAN NOT DOWNLOAD", Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(onDownloadComplete);
try {
if (wakeLock.isHeld()) {
wakeLock.release();
}
} catch (Exception ignore) {
}
}
private void downloadStaffs() {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(DataUtility.playingUrl));
request.setDescription("Download File");
request.setTitle(thePlayingSura);
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, thePlayingSura + " - " + DataUtility.theKariName + ".mp3");
final DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
final long downloadId = manager.enqueue(request);
this.downloadId = downloadId;
final ProgressBar mProgressBar = (ProgressBar) findViewById(R.id.downloadProgress);
downloadingTv.setVisibility(View.VISIBLE);
mProgressBar.setVisibility(View.VISIBLE);
new Thread(new Runnable() {
#SuppressLint("Range")
#Override
public void run() {
boolean downloading = true;
while (downloading) {
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterById(downloadId);
Cursor cursor = manager.query(q);
cursor.moveToFirst();
#SuppressLint("Range") int bytes_downloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
#SuppressLint("Range") int bytes_total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {
downloading = false;
}
final double dl_progress = (int) ((bytes_downloaded * 100l) / bytes_total);
runOnUiThread(new Runnable() {
#Override
public void run() {
mProgressBar.setProgress((int) dl_progress);
}
});
Log.d("MESSAGES", statusMessage(cursor));
cursor.close();
}
}
}).start();
}
#SuppressLint("Range")
private String statusMessage(Cursor c) {
String msg = "???";
switch (c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS))) {
case DownloadManager.STATUS_FAILED:
msg = "Download failed!";
break;
case DownloadManager.STATUS_PAUSED:
msg = "Download paused!";
break;
case DownloadManager.STATUS_PENDING:
msg = "Download pending!";
break;
case DownloadManager.STATUS_RUNNING:
msg = "Download in progress!";
break;
case DownloadManager.STATUS_SUCCESSFUL:
msg = "Download complete!";
break;
default:
msg = "Download is nowhere in sight";
break;
}
return (msg);
}
private void keepActivityAlive() {
powerManager = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "QuranAudio:WakeLock");
}
private void startService() {
Intent i = new Intent(this, BackgroundPlayingService.class);
startService(i);
}}
--------------------- extra --------------------------------------
I also had to create other service to remove notification when the
user kill app by clearing app from recent apps.
here is it
MyAppService extends Service {
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
Intent i = new Intent(MyAppService.this,BackgroundPlayingService.class);
try {
BackgroundPlayingService.playerNotificationManager.setPlayer(null);
stopService(i);
}catch (Exception ignore){}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}}
-------------------- WARNING ----------------------------------
I don't take this as a best approach, but it gave me a quick solution while waiting for a better approach.
I will pot the app link here when it's available in playstore.

Why am I getting a java.lang.NullPointerException error in a wifip2p connection

Here is the error - java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.wdchat.MainActivity$SendReceive.write(byte[])' on a null object reference.
I have included my mainactivity class code and wifibroadcastreceover class code as well. The code is actually from wifip2p tutorial on youtube made by sarthi technology
Here is my MainActivity class.
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
AppCompatEditText editText;
ImageView wifi_on_off_iv, wifi_descovery_iv, send_btn_iv, save_ic_iv, brd_msg_iv;
TextView username, sentMessage, connectionStatus, tallytext, tallyno;
WifiManager wifiManager;
WifiP2pManager p2pManager;
WifiP2pManager.Channel mchannel;
String messageText;
LinearLayout nestedLinearlayout;
ListView listView;
ServerClass serverClass;
ClientClass clientClass;
SendReceive sendReceive;
BroadcastReceiver broadcastReceiver;
IntentFilter intentFilter;
List<WifiP2pDevice> peers = new ArrayList<WifiP2pDevice>();
String[] devicenameArray;
WifiP2pDevice[] wifiP2pDeviceArray;
static final int MESSAGE_READ = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeViews();
exqListener();
}
Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message message) {
switch (message.what){
case MESSAGE_READ:
byte[] readBuff = (byte[]) message.obj;
String temMsg = new String(readBuff, 0, message.arg1);
sentMessage.setText(temMsg);
break;
}
return true;
}
});
private void exqListener() {
wifi_on_off_iv.setOnClickListener(view -> {
if (wifiManager.isWifiEnabled()) {
wifi_on_off_iv.setImageResource(R.drawable.ic_wifi_on);
wifiManager.setWifiEnabled(false);
wifi_on_off_iv.setImageResource(R.drawable.ic_wifi_off);
} else {
wifiManager.setWifiEnabled(true);
wifi_on_off_iv.setImageResource(R.drawable.ic_wifi_on);
}
});
wifi_descovery_iv.setOnClickListener(view -> p2pManager.discoverPeers(mchannel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
connectionStatus.setText(R.string.discovery_on);
wifi_descovery_iv.setImageResource(R.drawable.ic_wifi_discover);
connectionStatus.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.purple_500));
}
#Override
public void onFailure(int i) {
connectionStatus.setText(R.string.discovery_off);
wifi_descovery_iv.setImageResource(R.drawable.ic_wifi_discovery_off);
connectionStatus.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.red));
}
}));
p2pManager.createGroup(mchannel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
}
#Override
public void onFailure(int i) {
}
});
listView.setOnItemClickListener((adapterView, view, i, l) -> {
final WifiP2pDevice device = wifiP2pDeviceArray[i];
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = device.deviceAddress;
p2pManager.connect(mchannel, config, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
Toast.makeText(MainActivity.this, "Connected to " + device.deviceName, Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(int i) {
Toast.makeText(MainActivity.this, "Not connected", Toast.LENGTH_SHORT).show();
}
});
});
send_btn_iv.setOnClickListener(view -> {
// sendReceive = new SendReceive(sock);
messageText = Objects.requireNonNull(editText.getText()).toString().trim();
sendReceive.write(messageText.getBytes());
Toast.makeText(MainActivity.this, "you sent"+ messageText, Toast.LENGTH_SHORT).show();
});
}
private void initializeViews() {
intentFilter = new IntentFilter();
intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
toolbar = findViewById(R.id.mdboard_toolbar);
wifi_on_off_iv = findViewById(R.id.md_wifi);
wifi_descovery_iv = findViewById(R.id.md_wifi_descov);
brd_msg_iv = findViewById(R.id.md_broadcast_mesaage);
editText = findViewById(R.id.md_editext);
sentMessage = findViewById(R.id.md_tally_message);
send_btn_iv = findViewById(R.id.md_send_btn);
save_ic_iv = findViewById(R.id.md_save);
username = findViewById(R.id.md_profile_username);
connectionStatus = findViewById(R.id.md_status_text);
listView = findViewById(R.id.md_list_view);
tallytext = findViewById(R.id.md_tally_text);
tallyno = findViewById(R.id.md_tally_no);
nestedLinearlayout = findViewById(R.id.nestedscroll_linearlayout);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(R.string.dashboard);
ViewCompat.setNestedScrollingEnabled(nestedLinearlayout, true);
wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
p2pManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mchannel = p2pManager.initialize(this, getMainLooper(), null);
broadcastReceiver = new WifiDirectBroadcastReceiver(p2pManager, mchannel, this);
}
WifiP2pManager.PeerListListener peerListListener = new WifiP2pManager.PeerListListener() {
#Override
public void onPeersAvailable(WifiP2pDeviceList wifiP2pDeviceList) {
if (!wifiP2pDeviceList.getDeviceList().equals(peers)) {
peers.clear();
peers.addAll(wifiP2pDeviceList.getDeviceList());
devicenameArray = new String[wifiP2pDeviceList.getDeviceList().size()];
wifiP2pDeviceArray = new WifiP2pDevice[wifiP2pDeviceList.getDeviceList().size()];
int index = 0;
for (WifiP2pDevice device: wifiP2pDeviceList.getDeviceList()) {
devicenameArray[index] = device.deviceName;
wifiP2pDeviceArray[index] = device;
index++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, devicenameArray);
listView.setAdapter(adapter);
}
if (peers.size()==0) {
Toast.makeText(MainActivity.this, "No device found", Toast.LENGTH_SHORT).show();
return;
}
}
};
WifiP2pManager.ConnectionInfoListener connectionInfoListener = new WifiP2pManager.ConnectionInfoListener(){
#Override
public void onConnectionInfoAvailable(WifiP2pInfo wifiP2pInfo) {
final InetAddress groupOwner = wifiP2pInfo.groupOwnerAddress;
if (wifiP2pInfo.groupFormed && wifiP2pInfo.isGroupOwner){
connectionStatus.setText("Host");
serverClass = new ServerClass();
serverClass.start();
} else if (wifiP2pInfo.groupFormed){
connectionStatus.setText("CLient");
clientClass = new ClientClass(groupOwner);
clientClass.start();
}
}
};
#Override
protected void onStart(){
super.onStart();
exqListener();
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(broadcastReceiver, intentFilter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
}
public class ServerClass extends Thread {
Socket socket;
ServerSocket serverSocket;
#Override
public void run() {
try {
serverSocket = new ServerSocket(8888);
socket = serverSocket.accept();
sendReceive = new SendReceive(socket);
sendReceive.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private class SendReceive extends Thread{
private Socket socket;
private InputStream inputStream;
private OutputStream outputStream;
public SendReceive(Socket skt) {
socket = skt;
try {
inputStream = socket.getInputStream();
outputStream = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
byte[] buffer = new byte[1024];
int bytes;
while (socket!=null) {
try {
bytes = inputStream.read(buffer);
if (bytes>0){
handler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void write(byte[] bytes){
outputStream = new OutputStream() {
#Override
public void write(int i) throws IOException {
outputStream.write(bytes);
}
};
}
}
public class ClientClass extends Thread {
Socket socket;
String hostAdd;
public ClientClass(InetAddress hostAddress) {
hostAdd = hostAddress.getHostAddress();
socket = new Socket();
}
#Override
public void run() {
try {
socket.connect(new InetSocketAddress(hostAdd, 8888),500);
sendReceive = new SendReceive(socket);
sendReceive.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// requestGroupInfo
private void requestGroupInfo() {
p2pManager.requestGroupInfo(mchannel, new WifiP2pManager.GroupInfoListener() {
#Override
public void onGroupInfoAvailable(WifiP2pGroup wifiP2pGroup) {
connectionStatus.setText("request group info");
}
});
}
}
Here is my wifibroadcastReceiver class
public class WifiDirectBroadcastReceiver extends BroadcastReceiver {
WifiP2pManager wifiP2pManager;
WifiP2pManager.Channel channel;
MainActivity mainActivity;
public WifiDirectBroadcastReceiver(WifiP2pManager mManager, WifiP2pManager.Channel mchannel, MainActivity mActivity) {
this.wifiP2pManager = mManager;
this.channel = mchannel;
this.mainActivity = mActivity;
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)){
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
mainActivity. wifi_on_off_iv.setImageResource(R.drawable.ic_wifi_on);
Toast.makeText(context, "Wifi is on", Toast.LENGTH_SHORT).show();
} else {
mainActivity.wifi_on_off_iv.setImageResource(R.drawable.ic_wifi_off);
Toast.makeText(context, "Wifi is off", Toast.LENGTH_SHORT).show();
}
} else if(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
// do somethimg
if (wifiP2pManager != null) {
wifiP2pManager.requestPeers(channel, mainActivity.peerListListener);
}
} else if(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
// do somthing
if (wifiP2pManager == null) {
return;
}
NetworkInfo networkInfo = intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
if (networkInfo.isConnected()) {
wifiP2pManager.requestConnectionInfo(channel, mainActivity.connectionInfoListener);
mainActivity.connectionStatus.setText("[Device connected]");
mainActivity.wifi_descovery_iv.setImageResource(R.drawable.ic_wifi_discover);
} else {
mainActivity.connectionStatus.setText("[Device disconnected]");
mainActivity.wifi_descovery_iv.setImageResource(R.drawable.ic_wifi_discovery_off);
}
}else if(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
}
}
}

Can't receive data of the HC - 05 after successful connection on my android studio app

I have used BluetoothSPP Library:
https://github.com/akexorcist/Android-BluetoothSPPLibrary
The arduino connecting successfully to the android studio application, but I can't receive the data, I will import both of my codes and please some one tell me if I did something wrong, from what I read and understood , bluetooth.setOnDataReceivedListener is the function to receive and you should place bluetooth.print(data) on the arduino part in order to
Android:
public class MainActivity extends AppCompatActivity {
final String ON = "1";
final String OFF = "0";
BluetoothSocket socket;
private BluetoothAdapter mAdapter;
BluetoothSPP bluetooth;
private BluetoothDevice remoteDevice;
TextView text;
private BluetoothServerSocket mmServerSocket;
String TAG = "TEST: ";
Button connect;
Button on;
Button off;
private OnDataReceivedListener mDataReceivedListener = null;
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == BluetoothState.REQUEST_CONNECT_DEVICE) {
if (resultCode == Activity.RESULT_OK)
bluetooth.connect(data);
} else if (requestCode == BluetoothState.REQUEST_ENABLE_BT) {
if (resultCode == Activity.RESULT_OK) {
bluetooth.setupService();
} else {
Toast.makeText(getApplicationContext()
, "Bluetooth was not enabled."
, Toast.LENGTH_SHORT).show();
finish();
}
}
}
public void setOnDataReceivedListener (OnDataReceivedListener listener) {
if (mDataReceivedListener == null)
mDataReceivedListener = listener;
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket, String socketType) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
}
public void onStart() {
super.onStart();
if (!bluetooth.isBluetoothEnabled()) {
bluetooth.enable();
} else {
if (!bluetooth.isServiceAvailable()) {
bluetooth.setupService();
bluetooth.startService(BluetoothState.DEVICE_OTHER);
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bluetooth = new BluetoothSPP(this);
text = (TextView) findViewById(R.id.textView2);
connect = (Button) findViewById(R.id.connect);
on = (Button) findViewById(R.id.on);
off = (Button) findViewById(R.id.off);
BluetoothSocket socket = null;
mAdapter = BluetoothAdapter.getDefaultAdapter();
if (!bluetooth.isBluetoothAvailable()) {
Toast.makeText(getApplicationContext(), "Bluetooth is not available", Toast.LENGTH_SHORT).show();
finish();
}
bluetooth.setOnDataReceivedListener(new BluetoothSPP.OnDataReceivedListener() {
public void onDataReceived(byte[] data, String message) {
Log.d(TAG, "Start Reading");
/*Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();*/
Log.i("Check", "Message : " + message);
}
});
bluetooth.setBluetoothConnectionListener(new BluetoothSPP.BluetoothConnectionListener() {
public void onDeviceConnected(String name, String address) {
connect.setText("Connected to " + name);
}
public void onDeviceDisconnected() {
connect.setText("Connection lost");
}
public void onDeviceConnectionFailed() {
connect.setText("Unable to connect");
}
});
connect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (bluetooth.getServiceState() == BluetoothState.STATE_CONNECTED) {
bluetooth.disconnect();
} else {
Intent intent = new Intent(getApplicationContext(), DeviceList.class);
startActivityForResult(intent, BluetoothState.REQUEST_CONNECT_DEVICE);
}
}
});
on.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "Its on");
bluetooth.send(ON, true);
}
});
off.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "Its off");
bluetooth.send(OFF, true);
}
});
}
arduino part:
The Arduino code looks right.
Try first a Bluetooth serial monitor on your Android to check if the data is really being sent and received.
Then make sure in your Android code you connect to the module first then try to receive the data.

BLE image transfer

Here is the code to convert an image to byte array and and send to ble device
i am not able to send complete data and its stopping nearly at 1kb
what are the methods to send large data to ble .
will it be appropriate to use delay in the data transfer and if so can you share the code
if anyone has any code to send data upto 1mb please do share
public class RxTxActivity extends Activity {
byte[] imageInByte,SendByte;
private static int IMG_RESULT = 1;
String ImageDecode;
ImageView imageViewLoad;
Button LoadImage;
Intent intent;
String[] FILE;
String[] SAImage,SAsent;
private final static String TAG = DeviceControlActivity.class.getSimpleName();
public static final String EXTRAS_DEVICE_NAME = "DEVICE_NAME";
public static final String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS";
private TextView mCharaDescriptor;
private TextView mConnectionState;
private TextView mDataField;
private TextView mDeviceAddressTextView;
private String mServiceUUID, mDeviceAddress;
private String mCharaUUID, mDeviceName;
private BluetoothLeService mBluetoothLeService;
private ArrayList<ArrayList<BluetoothGattCharacteristic>> mGattCharacteristics =
new ArrayList<ArrayList<BluetoothGattCharacteristic>>();
private boolean mConnected = true;
private BluetoothGattCharacteristic mNotifyCharacteristic;
private Button EditButton;
private Button CharaSubscribeButton;
private EditText EditText;
private final String LIST_NAME = "NAME";
private final String LIST_UUID = "UUID";
private String CHARA_DESC = "";
private String properties = "";
private Context context = this;
// Code to manage Service lifecycle.
private final ServiceConnection mServiceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName componentName, IBinder service) {
mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
if (!mBluetoothLeService.initialize()) {
Log.e(TAG, "Unable to initialize Bluetooth");
finish();
}
// Automatically connects to the device upon successful start-up initialization.
mBluetoothLeService.connect(mDeviceAddress);
mBluetoothLeService.readCustomDescriptor(mCharaUUID, mServiceUUID);
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
mBluetoothLeService = null;
}
};
// Handles various events fired by the Service.
// ACTION_GATT_CONNECTED: connected to a GATT server.
// ACTION_GATT_DISCONNECTED: disconnected from a GATT server.
// ACTION_GATT_SERVICES_DISCOVERED: discovered GATT services.
// ACTION_DATA_AVAILABLE: received data from the device. This can be a result of read
// or notification operations.
private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(final Context context, Intent intent) {
final String action = intent.getAction();
switch (action) {
case BluetoothLeService.ACTION_GATT_CONNECTED:
mConnected = true;
updateConnectionState(R.string.connected);
invalidateOptionsMenu();
break;
case BluetoothLeService.ACTION_GATT_DISCONNECTED:
mConnected = false;
updateConnectionState(R.string.disconnected);
invalidateOptionsMenu();
break;
case BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED:
break;
case BluetoothLeService.ACTION_DATA_AVAILABLE:
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "Data Received!", Toast.LENGTH_SHORT).show();
}
});
displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
break;
case BluetoothLeService.ACTION_DESCRIPTOR_AVAILABLE:
Log.i("Receiving data", "Broadcast received");
displayDescriptor(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
default:
break;
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.data_transfer);
imageViewLoad = (ImageView) findViewById(R.id.imageView1);
LoadImage = (Button)findViewById(R.id.button1);
LoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, IMG_RESULT);
}
});
final Intent intent = getIntent();
Log.i("OnCreate", "Created");
mDeviceAddress = intent.getStringExtra(EXTRAS_DEVICE_ADDRESS);
mDeviceName = intent.getStringExtra(EXTRAS_DEVICE_NAME);
mServiceUUID = intent.getStringExtra("Service UUID");
mCharaUUID = intent.getStringExtra("Characteristic UUID");
CHARA_DESC = intent.getStringExtra("Characteristic Descriptor");
properties = intent.getStringExtra("Characteristic properties");
// Sets up UI references.
((TextView) findViewById(R.id.device_address_rxtx)).setText("Characteristic UUID: " + mCharaUUID);
((TextView) findViewById(R.id.characteristic_Descriptor)).setText("Characteristic Descriptor: " + CHARA_DESC);
((TextView) findViewById(R.id.device_address)).setText(mDeviceAddress);
mConnectionState = (TextView) findViewById(R.id.connection_state);
mConnectionState.setText("Connected");
mDataField = (TextView) findViewById(R.id.data_value);
EditText = (EditText) findViewById(R.id.characteristicEditText);
EditButton = (Button) findViewById(R.id.characteristicButton);
CharaSubscribeButton = (Button) findViewById(R.id.characteristic_Subscribe);
mCharaDescriptor = (TextView) findViewById(R.id.characteristic_Descriptor);
EditButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String str = EditText.getText().toString();
mBluetoothLeService.writeCustomCharacteristic(str, mServiceUUID, mCharaUUID);
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "Message Sent!", Toast.LENGTH_SHORT).show();
}
});
mBluetoothLeService.readCustomDescriptor(mCharaUUID, mServiceUUID);
}
});
CharaSubscribeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (properties.indexOf("Indicate") >= 0) {
mBluetoothLeService.subscribeCustomCharacteristic(mServiceUUID, mCharaUUID, 1);
} else if (properties.indexOf("Notify") >= 0) {
mBluetoothLeService.subscribeCustomCharacteristic(mServiceUUID, mCharaUUID, 2);
}
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "Characteristic Subscribed!", Toast.LENGTH_SHORT).show();
}
});
mBluetoothLeService.readCustomDescriptor(mCharaUUID, mServiceUUID);
}
});
checkProperties();
getActionBar().setTitle(mDeviceName);
getActionBar().setDisplayHomeAsUpEnabled(true);
Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
}
private void checkProperties() {
if (properties.indexOf("Write") >= 0) {
} else {
EditButton.setEnabled(false);
}
if (properties.indexOf("Indicate") >= 0) {
} else {
CharaSubscribeButton.setEnabled(false);
}
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
if (mBluetoothLeService != null) {
final boolean result = mBluetoothLeService.connect(mDeviceAddress);
Log.d(TAG, "Connect request result=" + result);
}
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(mGattUpdateReceiver);
}
#Override
protected void onDestroy() {
super.onDestroy();
unbindService(mServiceConnection);
mBluetoothLeService = null;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.gatt_services, menu);
if (mConnected) {
menu.findItem(R.id.menu_connect).setVisible(false);
menu.findItem(R.id.menu_disconnect).setVisible(true);
} else {
menu.findItem(R.id.menu_connect).setVisible(true);
menu.findItem(R.id.menu_disconnect).setVisible(false);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_connect:
mBluetoothLeService.connect(mDeviceAddress);
return true;
case R.id.menu_disconnect:
mBluetoothLeService.disconnect();
return true;
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
private void updateConnectionState(final int resourceId) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mConnectionState.setText(resourceId);
}
});
}
private void displayData(String data) {
if (data != null) {
mDataField.setText(data);
}
}
private void displayDescriptor(final String data) {
if( data != null){
runOnUiThread(new Runnable() {
#Override
public void run() {
mCharaDescriptor.setText(mCharaDescriptor.getText().toString() + "\n" + data);
}
});
}
}
private static IntentFilter makeGattUpdateIntentFilter() {
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
intentFilter.addAction(BluetoothLeService.ACTION_DESCRIPTOR_AVAILABLE);
return intentFilter;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == IMG_RESULT && resultCode == RESULT_OK
&& null != data) {
Uri URI = data.getData();
String[] FILE = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(URI,
FILE, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(FILE[0]);
ImageDecode = cursor.getString(columnIndex);
cursor.close();
imageViewLoad.setImageBitmap(BitmapFactory
.decodeFile(ImageDecode));
}
} catch (Exception e) {
Toast.makeText(this, "Please try again", Toast.LENGTH_LONG)
.show();
}
}
public void ClickConvert(View view) {
TextView txtView;
txtView=(TextView)findViewById(R.id.textview_byte);
ImageView imageView = (ImageView) findViewById(R.id.imageView1);
Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
imageInByte = baos.toByteArray();
String response ;
response = byteArrayToString(imageInByte);
// response = new sun.misc.BASE64Encoder().encode(imageInByte);
//String s = javax.xml.bind.DatatypeConverter.printHexBinary(imageInByte);
//String str = new String(imageInByte, "UTF-8");
txtView.setText(response);
}
public static String byteArrayToString(byte[] data){
String response = Arrays.toString(data);
String[] byteValues = response.substring(1, response.length() - 1).split(",");
byte[] bytes = new byte[byteValues.length];
for (int i=0, len=bytes.length; i<len; i++) {
bytes[i] = Byte.parseByte(byteValues[i].trim());
}
String str = new String(bytes);
return str.toLowerCase();
}
public void ClickImage(View view) {
final int num= imageInByte.length;
int i,j,l,h;
j=num/20;
Toast.makeText(getApplicationContext(), "loop : " + j, Toast.LENGTH_SHORT).show();
for (i = 0; i <= j; i++) {
l=20*i;
h=20*(i+1);
SystemClock.sleep(40); //ms
SendByte = Arrays.copyOfRange(imageInByte, l, h);
String str = new String(SendByte);
mBluetoothLeService.writeCustomCharacteristic(str, mServiceUUID, mCharaUUID);
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
mBluetoothLeService.readCustomDescriptor(mCharaUUID, mServiceUUID);
}
}
}
Here is the code for writecustomCharacteristics
public void writeCustomCharacteristic(String str, String serviceUuid, String charaUuid) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
/*check if the service is available on the device*/
BluetoothGattService mCustomService = mBluetoothGatt.getService(UUID.fromString(serviceUuid));
if(mCustomService == null){
Log.w(TAG, "Custom BLE Service not found");
return;
}
/*byte[] value = parseHex(str);
*//*get the read characteristic from the service*//*
BluetoothGattCharacteristic mWriteCharacteristic = mCustomService.getCharacteristic(UUID.fromString(charaUuid));
mWriteCharacteristic.setValue(value);
mBluetoothGatt.writeCharacteristic(mWriteCharacteristic);*/
byte[] strBytes = str.getBytes();
BluetoothGattCharacteristic mWriteCharacteristic = mCustomService.getCharacteristic(UUID.fromString(charaUuid));
mWriteCharacteristic.setValue(strBytes);
mBluetoothGatt.writeCharacteristic(mWriteCharacteristic);
}

why do i get th java.lang.RuntimeException: Unable to start activity ComponentInfo

Hi guys im making a auto update after following a tutorial online then editing the code to suit my needs.. but im getting this error in my logcat
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.harrops.h20droidapp/com.example.harrops.h20droidapp.Homescreen}: android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.harrops.h20droidapp/com.example.harrops.h20droidapp.UpdateService}; have you declared this activity in your AndroidManifest.xml?
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
can some one please help me
this is my service class
public class UpdateService extends Service {
public UpdateService() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
String url = "<MY Link for version>";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response != null) {
boolean resp = response.contains("<div class='post-body entry-content' id='post-body-6791062644900393367' itemprop='description articleBody'>\n" +
"1.1.8\n" +
"<div style='clear: both;'></div>");
if (!resp) {
//Dialog to show update
Intent intent1 = new Intent(UpdateService.this, UpdateDialog.class);
intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent1);
} else {
Toast.makeText(UpdateService.this, "No New Update Found..", Toast.LENGTH_LONG).show();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
queue.add(stringRequest);
return Service.START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
then this is my dialog class
public static Button btn;
public static String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Update";
public static File Dir = new File(path);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidAuthSession session = buildSession();
dropboxAPI = new DropboxAPI<AndroidAuthSession>(session);
Dir.mkdir();
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setIcon(R.mipmap.ic_launcher);
alertDialog.setTitle("update");
alertDialog.setMessage("New update Available...");
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "UPDATE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
DownloadFromDropboxFromPath(path + "downloadFileFromDropbox", "Update/Myupdate.apk");
}
});
alertDialog.show();
}
static DropboxAPI<AndroidAuthSession> dropboxAPI;
private static final String APP_KEY = "********* **** ** **";
private static final String APP_SECRET = "XXX XX X X XX X";
private static final String ACCESSTOKEN = "xx x x xxx x x x x";
private DropboxAPI.UploadRequest request;
private AndroidAuthSession buildSession() {
AppKeyPair appKeyPair = new AppKeyPair(APP_KEY, APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appKeyPair);
session.setOAuth2AccessToken(ACCESSTOKEN);
return session;
}
static final int UploadFromSelectApp = 9501;
static final int UploadFromFilemanager = 9502;
public static String DropboxUploadPathFrom = "";
public static String DropboxUploadName = "";
public static String DropboxDownloadPathFrom = "";
public static String DropboxDownloadPathTo = "";
private void UploadToDropboxFromPath(String uploadPathFrom, String uploadPathTo) {
Toast.makeText(getApplicationContext(), "Upload file ...", Toast.LENGTH_SHORT).show();
final String uploadPathF = uploadPathFrom;
final String uploadPathT = uploadPathTo;
Thread th = new Thread(new Runnable() {
public void run() {
File tmpFile = null;
try {
tmpFile = new File(uploadPathF);
} catch (Exception e) {
e.printStackTrace();
}
FileInputStream fis = null;
try {
fis = new FileInputStream(tmpFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
dropboxAPI.putFileOverwrite(uploadPathT, fis, tmpFile.length(), null);
} catch (Exception e) {
}
getMain().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "File successfully uploaded.", Toast.LENGTH_SHORT).show();
}
});
}
});
th.start();
}
private void UploadToDropboxFromSelectedApp(String uploadName) {
DropboxUploadName = uploadName;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent, "Upload from ..."), UploadFromSelectApp);
}
private void UploadToDropboxFromFilemanager(String uploadName) {
DropboxUploadName = uploadName;
Intent intent = new Intent("com.sec.android.app.myfiles.PICK_DATA");
intent.putExtra("CONTENT_TYPE", "*/*");
intent.addCategory(Intent.CATEGORY_DEFAULT);
startActivityForResult(intent, UploadFromFilemanager);
}
private void DownloadFromDropboxFromPath(String downloadPathTo, String downloadPathFrom) {
DropboxDownloadPathTo = downloadPathTo;
DropboxDownloadPathFrom = downloadPathFrom;
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Download file ...", Toast.LENGTH_SHORT).show();
Thread th = new Thread(new Runnable() {
public void run() {
File file = new File(DropboxDownloadPathTo + DropboxDownloadPathFrom.substring(DropboxDownloadPathFrom.lastIndexOf('.')));
if (file.exists()) file.delete();
try {
FileOutputStream outputStream = new FileOutputStream(file);
UpdateDialog.dropboxAPI.getFile(DropboxDownloadPathFrom, null, outputStream, null);
getMain().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "File successfully downloaded.", Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
th.start();
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == UploadFromFilemanager) {
final Uri currFileURI = intent.getData();
final String pathFrom = currFileURI.getPath();
Toast.makeText(getApplicationContext(), "Upload file ...", Toast.LENGTH_SHORT).show();
Thread th = new Thread(new Runnable() {
public void run() {
getMain().runOnUiThread(new Runnable() {
#Override
public void run() {
UploadToDropboxFromPath(pathFrom, "/db-test/" + DropboxUploadName + pathFrom.substring(pathFrom.lastIndexOf('.')));
Toast.makeText(getApplicationContext(), "File successfully uploaded.", Toast.LENGTH_SHORT).show();
}
});
}
});
th.start();
}
if (requestCode == UploadFromSelectApp) {
Toast.makeText(getApplicationContext(), "Upload file ...", Toast.LENGTH_SHORT).show();
final Uri uri = intent.getData();
DropboxUploadPathFrom = getPath(getApplicationContext(), uri);
if (DropboxUploadPathFrom == null) {
DropboxUploadPathFrom = uri.getPath();
}
Thread th = new Thread(new Runnable() {
public void run() {
try {
final File file = new File(DropboxUploadPathFrom);
InputStream inputStream = getContentResolver().openInputStream(uri);
dropboxAPI.putFile("/db-test/" + DropboxUploadName + file.getName().substring(file.getName().lastIndexOf("."),
file.getName().length()), inputStream, file.length(), null, new ProgressListener() {
#Override
public long progressInterval() {
return 100;
}
#Override
public void onProgress(long arg0, long arg1) {
}
});
getMain().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "File successfully uploaded.", Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
th.start();
}
super.onActivityResult(requestCode, resultCode, intent);
}
public String getPath(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = {MediaStore.Images.Media.DATA, MediaStore.Video.Media.DATA, MediaStore.Audio.Media.DATA};
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String s = cursor.getString(column_index);
if (s != null) {
cursor.close();
return s;
}
} catch (Exception e) {
}
try {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
cursor.moveToFirst();
String s = cursor.getString(column_index);
if (s != null) {
cursor.close();
return s;
}
} catch (Exception e) {
}
try {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
cursor.moveToFirst();
String s = cursor.getString(column_index);
cursor.close();
return s;
} finally {
if (cursor != null) {
cursor.close();
}
}
}
public UpdateDialog getMain() {
return this;
}
}
then finally i call it in my homescreen class. with an intent
Intent intent = new Intent(Homescreen.this, UpdateService.class);
startActivity(intent);
UpdateService is a Service. It is not an Activity. To start a service, you call startService(), not startActivity().
As UpdateService is a service you have to start it by startService() method like #CommonsWare mentioned above. Also don't forget to add your service in Manifest file.
UpdateService is not an activity, It's a class that is extending services.
I think u r a very beginner.
Please go to Udacity and learn the concepts before tingling with android, otherwise, u will waste lot of your time in finding a copy-paste solution.

Categories

Resources