Call through SIP using wifi - java

Actually i am doing call using sip through wifi. bt in this program the problem is that I when i select sip account of the person whom i want to call but when i select the number and press ok then on then second phone there is no notification display that their is an inncoming call. Please help me I am stuck here ???
public class WalkieTalkieActivity extends Activity implements View.OnTouchListener {
public String sipAddress = null;
String DummyNum;
SipManager manager=null;
public SipProfile me = null;
public SipAudioCall call = null;
public IncomingCallReceiver callReceiver;
Button contact;
TextView tv;
private static final int CALL_ADDRESS = 1;
private static final int SET_AUTH_INFO = 2;
private static final int UPDATE_SETTINGS_DIALOG = 3;
private static final int HANG_UP = 4;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.walkietalkie);
// PickContact();
contact = (Button) findViewById(R.id.button1);
contact.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// BoD con't: CONTENT_TYPE instead of CONTENT_ITEM_TYPE
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent, 1);
}
});
tv = (TextView) findViewById(R.id.textView1);
ToggleButton pushToTalkButton = (ToggleButton) findViewById(R.id.pushToTalk);
pushToTalkButton.setOnTouchListener(this);
// Set up the intent filter. This will be used to fire an
// IncomingCallReceiver when someone calls the SIP address used by this
// application.
IntentFilter filter = new IntentFilter();
filter.addAction("android.SipDemo.INCOMING_CALL");
callReceiver = new IncomingCallReceiver();
this.registerReceiver(callReceiver, filter);
// "Push to talk" can be a serious pain when the screen keeps turning off.
// Let's prevent that.
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
initializeManager();
}
#Override
public void onStart() {
super.onStart();
// When we get back from the preference setting Activity, assume
// settings have changed, and re-login with new auth info.
initializeManager();
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
public void onDestroy() {
super.onDestroy();
if (call != null) {
call.close();
}
closeLocalProfile();
if (callReceiver != null) {
this.unregisterReceiver(callReceiver);
}
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void initializeManager() {
if (manager == null) {
manager = SipManager.newInstance(this);
}
initializeLocalProfile();
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void initializeLocalProfile() {
if (manager == null) {
return;
}
if (me != null) {
closeLocalProfile();
}
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String username = prefs.getString("namePref", "");
String domain = prefs.getString("domainPref", "");
String password = prefs.getString("passPref", "");
if (username.length() == 0 || domain.length() == 0 || password.length() == 0) {
showDialog(UPDATE_SETTINGS_DIALOG);
return;
}
try {
SipProfile.Builder builder = new SipProfile.Builder(username, domain);
builder.setPassword(password);
me = builder.build();
Intent i = new Intent();
i.setAction("android.SipDemo.INCOMING_CALL");
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, Intent.FILL_IN_DATA);
manager.open(me, pi, null);
// This listener must be added AFTER manager.open is called,
// Otherwise the methods aren't guaranteed to fire.
manager.setRegistrationListener(me.getUriString(), new SipRegistrationListener() {
public void onRegistering(String localProfileUri) {
updateStatus("Registering with SIP Server...");
}
public void onRegistrationDone(String localProfileUri, long expiryTime) {
updateStatus("Ready");
}
public void onRegistrationFailed(String localProfileUri, int errorCode,
String errorMessage) {
updateStatus("Registration failed. Please check settings.");
}
});
} catch (ParseException pe) {
updateStatus("Connection Error.");
} catch (SipException se) {
updateStatus("Connection error.");
}
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void closeLocalProfile() {
if (manager == null) {
return;
}
try {
if (me != null) {
manager.close(me.getUriString());
}
} catch (Exception ee) {
Log.d("WalkieTalkieActivity/onDestroy", "Failed to close local profile.", ee);
}
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void initiateCall() {
updateStatus(sipAddress);
try {
SipAudioCall.Listener listener = new SipAudioCall.Listener() {
// Much of the client's interaction with the SIP Stack will
// happen via listeners. Even making an outgoing call, don't
// forget to set up a listener to set things up once the call is established.
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
public void onCallEstablished(SipAudioCall call) {
call.startAudio();
call.setSpeakerMode(true);
call.toggleMute();
updateStatus(call);
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
public void onCallEnded(SipAudioCall call) {
updateStatus("Ready.");
}
};
call = manager.makeAudioCall(me.getUriString(), sipAddress, listener, 30);
} catch (Exception e) {
Log.i("WalkieTalkieActivity/InitiateCall", "Error when trying to close manager.", e);
if (me != null) {
try {
manager.close(me.getUriString());
} catch (Exception ee) {
Log.i("WalkieTalkieActivity/InitiateCall",
"Error when trying to close manager.", ee);
ee.printStackTrace();
}
}
if (call != null) {
call.close();
}
}
}
public void updateStatus(final String status) {
// Be a good citizen. Make sure UI changes fire on the UI thread.
this.runOnUiThread(new Runnable() {
public void run() {
TextView labelView = (TextView) findViewById(R.id.sipLabel);
labelView.setText(status);
}
});
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void updateStatus(SipAudioCall call) {
String useName = call.getPeerProfile().getDisplayName();
if (useName == null) {
useName = call.getPeerProfile().getUserName();
}
updateStatus(useName + "#" + call.getPeerProfile().getSipDomain());
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public boolean onTouch(View v, MotionEvent event) {
if (call == null) {
return false;
} else if (event.getAction() == MotionEvent.ACTION_DOWN && call != null && call.isMuted()) {
call.toggleMute();
} else if (event.getAction() == MotionEvent.ACTION_UP && !call.isMuted()) {
call.toggleMute();
}
return false;
}
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, CALL_ADDRESS, 0, "Call someone");
menu.add(0, SET_AUTH_INFO, 0, "Edit your SIP Info.");
menu.add(0, HANG_UP, 0, "End Current Call.");
return true;
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case CALL_ADDRESS:
showDialog(CALL_ADDRESS);
break;
case SET_AUTH_INFO:
updatePreferences();
break;
case HANG_UP:
if (call != null) {
try {
call.endCall();
} catch (SipException se) {
Log.d("WalkieTalkieActivity/onOptionsItemSelected",
"Error ending call.", se);
}
call.close();
}
break;
}
return true;
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case CALL_ADDRESS:
LayoutInflater factory = LayoutInflater.from(this);
final View textBoxView = factory.inflate(R.layout.call_address_dialog, null);
return new AlertDialog.Builder(this)
.setTitle("Call Someone.")
.setView(textBoxView)
.setPositiveButton(
android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
EditText textField = (EditText)
(textBoxView.findViewById(R.id.calladdress_edit));
DummyNum = textField.getText().toString();
tv.setText(DummyNum);
SendMessageWebTask webTask1 = new SendMessageWebTask(WalkieTalkieActivity.this);
webTask1.execute();
initiateCall();
}
}
)
.setNegativeButton(
android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Noop.
}
}
)
.create();
case UPDATE_SETTINGS_DIALOG:
return new AlertDialog.Builder(this)
.setMessage("Please update your SIP Account Settings.")
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
updatePreferences();
}
})
.setNegativeButton(
android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Noop.
}
}
)
.create();
}
return null;
}
public void updatePreferences() {
Intent settingsActivity = new Intent(getBaseContext(),
SipSettings.class);
startActivity(settingsActivity);
}
public void PickContact() {
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
Uri uri = data.getData();
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE},
null, null, null
);
if (c != null && c.moveToFirst()) {
String number = c.getString(0);
int type = c.getInt(1);
// showSelectedNumber(type, number);
tv.setText(number);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
public void showSelectedNumber(int type, String number) {
}
public class SendMessageWebTask extends AsyncTask<String, Void, String> {
private static final String TAG = "WebTask";
private ProgressDialog progressDialog;
private Context context;
private String status;
public SendMessageWebTask(Context context) {
super();
this.context = context;
this.progressDialog = new ProgressDialog(context);
this.progressDialog.setCancelable(true);
this.progressDialog.setMessage("Checking User using Connecto...");
}
#Override
protected String doInBackground(String... params) {
status = invokeWebService();
return status;
}
#Override
protected void onPreExecute() {
Log.i(TAG, "Showing dialog...");
progressDialog.show();
}
#Override
protected void onPostExecute(String params) {
super.onPostExecute(params);
progressDialog.dismiss();
//params = USER_NOT_EXIST_CODE;
if (params.equals("008")) {
Toast toast = Toast.makeText(WalkieTalkieActivity.this, "Requested user is not using Connecto", 7000);
toast.show();
MediaPlayer mp1 = MediaPlayer.create(WalkieTalkieActivity.this, R.raw.button_test);
mp1.start();
sipAddress = DummyNum;
performDial(DummyNum);
} else if (params.equals("001")) {
Toast toast = Toast.makeText(WalkieTalkieActivity.this, "Requested user is not using Connecto... Now Call is through GSM Network", 7000);
toast.show();
// sipAddress = DummyNum;
performDial(DummyNum);
// initiateCall();
} else if (params.equals("100")) {
Toast toast = Toast.makeText(WalkieTalkieActivity.this, "Server Error... Now Call is through GSM Network", 7000);
toast.show();
// sipAddress = DummyNum;
performDial(DummyNum);
// initiateCall();
} else {
Toast toast = Toast.makeText(WalkieTalkieActivity.this, "Your Call is Staring...", 7000);
toast.show();
sipAddress = DummyNum;
// performDial(DummyNum);
initiateCall();
}
// tv.setText(params);
}
private String invokeWebService() {
final String NAMESPACE = "http://tempuri.org/";
final String METHOD_NAME = Utility.verify_sip;
final String URL = Utility.webServiceUrl;
final String SOAP_ACTION = "http://tempuri.org/" + Utility.verify_sip;
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("phone", DummyNum);
Log.v("XXX", tv.getText().toString());
//request.addProperty("password", inputParam2);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive result = (SoapPrimitive) envelope.getResponse();
String status = result.toString();
Log.v("RESULT: ", status);
return status;
} catch (Exception e) {
Log.e("exception", e.toString());
StackTraceElement elements[] = e.getStackTrace();
for (int i = 0, n = elements.length; i < n; i++) {
Log.i("File", elements[i].getFileName());
Log.i("Line", String.valueOf(elements[i].getLineNumber()));
Log.i("Method", elements[i].getMethodName());
Log.i("------", "------");
}
return "EXCEPTION";
}
}
}
private void performDial(String numberString) {
if (!numberString.equals("")) {
Uri number = Uri.parse("tel:" + numberString);
Intent dial = new Intent(Intent.ACTION_CALL, number);
startActivity(dial);
}
}
}

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.

Android recorded incoming and outgoing calls are silent

Here is the code
public class MainActivity extends AppCompatActivity {
ToggleButton toggleButton;
TextView textSubHeader;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
textSubHeader = (TextView) findViewById(R.id.textSubHeader);
// File CallRecorder = new File("/sdcard/CallRecorder");
// CallRecorder.mkdirs();
}
#Override
protected void onResume() {
super.onResume();
// Runtime permission
try {
boolean permissionGranted_OutgoingCalls = ActivityCompat.checkSelfPermission(this, Manifest.permission.PROCESS_OUTGOING_CALLS) == PackageManager.PERMISSION_GRANTED;
boolean permissionGranted_phoneState = ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED;
boolean permissionGranted_recordAudio = ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED;
boolean permissionGranted_WriteExternal = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
boolean permissionGranted_ReadExternal = ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
if (permissionGranted_OutgoingCalls) {
if (permissionGranted_phoneState) {
if (permissionGranted_recordAudio) {
if (permissionGranted_WriteExternal) {
if (permissionGranted_ReadExternal) {
try {
toggleButton.setVisibility(View.VISIBLE);
} catch (Exception e) {
e.printStackTrace();
}
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 200);
}
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 300);
}
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, 400);
}
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, 500);
}
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.PROCESS_OUTGOING_CALLS}, 600);
}
} catch (Exception e) {
e.printStackTrace();
}
}
#SuppressLint("ResourceAsColor")
public void toggleButtonClick(View view) {
try {
boolean checked = ((ToggleButton) view).isChecked();
if (checked) {
Intent intent = new Intent(this, CallRecorder.class);
startService(intent);
Toast.makeText(getApplicationContext(), "Call Recording is set ON", Toast.LENGTH_SHORT).show();
textSubHeader.setText("Switch on Toggle to record your calls");
} else {
Intent intent = new Intent(this, CallRecorder.class);
stopService(intent);
Toast.makeText(getApplicationContext(), "Call Recording is set OFF", Toast.LENGTH_SHORT).show();
textSubHeader.setText("Switch Off Toggle to stop recording your calls");
}
}
catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 200 || requestCode == 300 || requestCode == 400 || requestCode == 500 || requestCode == 600) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
try {
toggleButton.setVisibility(View.VISIBLE);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
public class CallRecorder extends Service {
private MediaRecorder recorder;
private boolean recordStarted = false;
private String savedNumber;
public static final String ACTION_IN = "android.intent.action.PHONE_STATE";
public static final String ACTION_OUT = "android.intent.action.NEW_OUTGOING_CALL";
public static final String EXTRA_PHONE_NUMBER = "android.intent.extra.PHONE_NUMBER";
private int lastState = TelephonyManager.CALL_STATE_IDLE;
private boolean isIncoming;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
final IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_OUT);
filter.addAction(ACTION_IN);
this.registerReceiver(new CallReceiver(), filter);
return super.onStartCommand(intent, flags, startId);
}
private void stopRecording() {
if (recordStarted) {
recorder.stop();
recordStarted = false;
}
}
public abstract class PhoneCallReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_OUT)) {
savedNumber = intent.getStringExtra(EXTRA_PHONE_NUMBER);
} else {
String stateStr = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
savedNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
int state = 0;
if (stateStr.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
state = TelephonyManager.CALL_STATE_IDLE;
} else if (stateStr.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
state = TelephonyManager.CALL_STATE_OFFHOOK;
} else if (stateStr.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
state = TelephonyManager.CALL_STATE_RINGING;
}
onCallStateChanged(context, state, savedNumber);
}
}
protected abstract void onIncomingCallReceived(Context ctx, String number);
protected abstract void onIncomingCallAnswered(Context ctx, String number);
protected abstract void onIncomingCallEnded(Context ctx, String number);
protected abstract void onOutgoingCallStarted(Context ctx, String number);
protected abstract void onOutgoingCallEnded(Context ctx, String number);
protected abstract void onMissedCall(Context ctx, String number);
public void onCallStateChanged(Context context, int state, String number) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
String time = dateFormat.format(new Date()) ;
File sampleDir = new File(Environment.getExternalStorageDirectory(), "/indcallrecorder");
if (!sampleDir.exists()) {
sampleDir.mkdirs();
}
if (lastState == state) {
return;
}
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
isIncoming = true;
savedNumber = number;
onIncomingCallReceived(context, number );
recorder = new MediaRecorder();
// recorder.setAudioSamplingRate(8000);
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(sampleDir.getAbsolutePath() + "/" + "Incoming \n" + number + " \n" + time + " \n" + " Call.amr");
try {
recorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
recorder.start();
recordStarted = true;
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
if (lastState != TelephonyManager.CALL_STATE_RINGING) {
isIncoming = false;
recorder = new MediaRecorder();
recorder.setAudioSamplingRate(8000);
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(sampleDir.getAbsolutePath() + "/" + "Outgoing \n" + savedNumber + " \n" + time + " \n" + " Call.amr");
try {
recorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
recorder.start();
recordStarted = true;
onOutgoingCallStarted(context, savedNumber );
} else {
isIncoming = true;
onIncomingCallAnswered(context, savedNumber);
}
break;
case TelephonyManager.CALL_STATE_IDLE:
if (lastState == TelephonyManager.CALL_STATE_RINGING) {
onMissedCall(context, savedNumber);
} else if (isIncoming) {
stopRecording();
onIncomingCallEnded(context, savedNumber);
} else {
stopRecording();
onOutgoingCallEnded(context, savedNumber);
}
break;
}
lastState = state;
}
}
public class CallReceiver extends PhoneCallReceiver {
#Override
protected void onIncomingCallReceived(Context ctx, String number) {
}
#Override
protected void onIncomingCallAnswered(Context ctx, String number) {
}
#Override
protected void onIncomingCallEnded(Context ctx, String number) {
}
#Override
protected void onOutgoingCallStarted(Context ctx, String number) {
}
#Override
protected void onOutgoingCallEnded(Context ctx, String number) {
}
#Override
protected void onMissedCall(Context ctx, String number) {
}
}
}
I am implementing call recording option in my Android application and all the calls are recoding fine below Android version 10 but from Android version 10 to above versions calls are recorded and when I try to play the recorded calls its silent. I am not able to listen the recorded voice.
What can I try to resolve this?

Image do not show after i saved it in a sqlite database

In this app I save products in a sqlite database. Could you help me understand why I can’t see the image when I want to edit a product? I can see it when I add it but not when I click on product to edit it.
public class EditorActivity extends AppCompatActivity implements
LoaderManager.LoaderCallbacks<Cursor>{
private static final int EXISTING_PRODUCT_LOADER = 1;
private static final int PICTURE_GALLERY_REQUEST = 1;
private static final String STATE_PICTURE_URI = "STATE_PICTURE_URI";
private Uri mPictureUri;
private Uri mCurrentProductUri;
private EditText mNameEditText;
private EditText mPriceEditText;
private EditText mQuantityEditText;
private EditText mSupplierEditText;
private EditText mMailEditText;
private int mProductQuantity=-1;
private Button mIncreaseQuantityButton;
private Button mDecreaseQuantityButton;
private Button mSelectImageButton;
private ImageView mProductImageView;
private String picturePath;
private String stringUri;
private Button mOrderButton;
final Context mContext = EditorActivity.this;
private boolean mProductHasChanged = false;
private View.OnTouchListener mTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
mProductHasChanged = true;
return false;
}
};
public static Bitmap getImage(byte[] image) {
return BitmapFactory.decodeByteArray(image, 70, image.length);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editor_activity);
Intent intent = getIntent();
mCurrentProductUri = intent.getData();
if (mCurrentProductUri == null) {
setTitle(getString(R.string.editor_activity_title_new_product));
invalidateOptionsMenu();
} else {
setTitle(getString(R.string.editor_activity_title_edit_product));
getLoaderManager().initLoader(EXISTING_PRODUCT_LOADER, null, this);
}
initialiseViews();
setOnTouchListener();
}
private void setOnTouchListener() {
mNameEditText.setOnTouchListener(mTouchListener);
mPriceEditText.setOnTouchListener(mTouchListener);
mQuantityEditText.setOnTouchListener(mTouchListener);
mSupplierEditText.setOnTouchListener(mTouchListener);
mMailEditText.setOnTouchListener(mTouchListener);
mIncreaseQuantityButton.setOnTouchListener(mTouchListener);
mDecreaseQuantityButton.setOnTouchListener(mTouchListener);
mSelectImageButton.setOnTouchListener(mTouchListener);
mOrderButton.setOnTouchListener(mTouchListener);
}
private void initialiseViews() {
mOrderButton = (Button) findViewById(R.id.order_button);
mOrderButton.setVisibility(View.VISIBLE);
mOrderButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String productName = mNameEditText.getText().toString().trim();
String emailAddress = "mailto:" + mMailEditText.getText().toString().trim();
String subjectHeader = "Order For: " + productName;
String orderMessage = "Please send a unit of " + productName + ". " + " \n\n" + "Thank you.";
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setData(Uri.parse(emailAddress));
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, orderMessage);
intent.putExtra(Intent.EXTRA_SUBJECT, subjectHeader);
startActivity(Intent.createChooser(intent, "Send Mail..."));
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
});
mNameEditText = (EditText) findViewById(R.id.edit_name);
mPriceEditText = (EditText) findViewById(R.id.edit_price);
mQuantityEditText = (EditText) findViewById(R.id.edit_quantity);
mSupplierEditText = (EditText) findViewById(R.id.edit_supplier);
mMailEditText= (EditText) findViewById(R.id.edit_supplier_mail);
mIncreaseQuantityButton = (Button) findViewById(R.id.editor_increase);
mIncreaseQuantityButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String quanititynumber = mQuantityEditText.getText().toString();
if (TextUtils.isEmpty(quanititynumber)) {
Toast.makeText(EditorActivity.this, "Quantity field is Empty", Toast.LENGTH_SHORT).show();
return;
} else {
mProductQuantity = Integer.parseInt(quanititynumber);
mProductQuantity++;
mQuantityEditText.setText(String.valueOf(mProductQuantity));
}}
});
mDecreaseQuantityButton = (Button) findViewById(R.id.editor_decrease);
mDecreaseQuantityButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String quanititynumber = mQuantityEditText.getText().toString();
if (TextUtils.isEmpty(quanititynumber)) {
Toast.makeText(EditorActivity.this, "Quantity field is Empty", Toast.LENGTH_SHORT).show();
return;
} else {
mProductQuantity = Integer.parseInt(quanititynumber);
if (mProductQuantity > 0) {
mProductQuantity--;
mQuantityEditText.setText(String.valueOf(mProductQuantity));
}
}}
});
mProductImageView = (ImageView) findViewById(R.id.image);
mSelectImageButton = (Button) findViewById(R.id.upload_image);
mSelectImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent openPictureGallery = new Intent(Intent.ACTION_OPEN_DOCUMENT);
File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String pictureDirectoryPath = pictureDirectory.getPath();
Uri data = Uri.parse(pictureDirectoryPath);
openPictureGallery.setDataAndType(data, "image/*");
startActivityForResult(openPictureGallery, PICTURE_GALLERY_REQUEST);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
// checking if the request code and result code match our request
if (requestCode == PICTURE_GALLERY_REQUEST && resultCode == Activity.RESULT_OK) {
if (resultData != null) {
try {
//this is the address of the image on the sd cards
mPictureUri = resultData.getData();
int takeFlags = resultData.getFlags();
takeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
picturePath = mPictureUri.toString();
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
getContentResolver().takePersistableUriPermission(mPictureUri, takeFlags);
}
} catch (SecurityException e) {
e.printStackTrace();
}
mProductImageView.setImageBitmap(getBitmapFromUri(mPictureUri, mContext, mProductImageView));
} catch (Exception e) {
e.printStackTrace();
//Show the user a Toast mewssage that the Image is not available
Toast.makeText(EditorActivity.this, "Unable to open image", Toast.LENGTH_LONG).show();
}
}
}
}
public Bitmap getBitmapFromUri(Uri uri, Context mContext, ImageView imageView) {
if (uri == null || uri.toString().isEmpty())
return null;
// Get the dimensions of the View
int targetW = imageView.getWidth();
int targetH = imageView.getHeight();
InputStream input = null;
try {
input = this.getContentResolver().openInputStream(uri);
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeStream(input, null, bmOptions);
if (input != null)
input.close();
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW / targetW, photoH / targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
input = this.getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(input, null, bmOptions);
Bitmap.createScaledBitmap(bitmap, 88, 88, false);
input.close();
return bitmap;
} catch (FileNotFoundException fne) {
Log.e("EditorActivity", "Failed to load image.", fne);
return null;
} catch (Exception e) {
Log.e("EditorActivity", "Failed to load image.", e);
return null;
} finally {
try {
input.close();
} catch (IOException ioe) {
}
}
}
private void saveProduct() {
String nameString = mNameEditText.getText().toString().trim();
String quantityString = mQuantityEditText.getText().toString().trim();
String priceString = mPriceEditText.getText().toString().trim();
String supplierString = mSupplierEditText.getText().toString().trim();
String supplierEmailString = mMailEditText.getText().toString().trim();
if (mCurrentProductUri == null &&
TextUtils.isEmpty(nameString) && TextUtils.isEmpty(quantityString) &&
TextUtils.isEmpty(priceString) && TextUtils.isEmpty(supplierString)&& TextUtils.isEmpty(supplierEmailString)) {
return;
}
int quantity = parseInt(quantityString);
double price = Double.parseDouble(mPriceEditText.getText().toString().trim());
ContentValues values = new ContentValues();
values.put(ProductContract.ProductEntry.COLUMN_PRODUCT_NAME, nameString);
values.put(ProductContract.ProductEntry.COLUMN_PRODUCT_PRICE, priceString);
values.put(ProductContract.ProductEntry.COLUMN_PRODUCT_QUANTITY, quantityString);
values.put(ProductContract.ProductEntry.COLUMN_PRODUCT_SUPPLIER, supplierString);
values.put(ProductContract.ProductEntry.COLUMN_PRODUCT_SUPPLIER_MAIL, supplierEmailString);
if(mPictureUri!=null) {
picturePath = mPictureUri.toString().trim();
}
else{
picturePath=stringUri;
}
values.put(ProductContract.ProductEntry.COLUMN_PRODUCT_PICTURE, picturePath);
if (mCurrentProductUri == null) {
Uri newUri = getContentResolver().insert(ProductContract.ProductEntry.CONTENT_URI, values);
if (newUri == null) {
Toast.makeText(this, getString(R.string.editor_insert_product_failed),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, getString(R.string.editor_insert_product_successful),
Toast.LENGTH_SHORT).show();
}
} else {
int rowsAffected = getContentResolver().update(mCurrentProductUri, values, null, null);
if (rowsAffected == 0) {
Toast.makeText(this, getString(R.string.editor_update_product_failed),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, getString(R.string.editor_update_product_successful),
Toast.LENGTH_SHORT).show();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_editor, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
if (mCurrentProductUri == null) {
MenuItem menuItem = menu.findItem(R.id.action_delete);
menuItem.setVisible(false);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_save:
saveProduct();
finish();
return true;
case R.id.action_delete:
showDeleteConfirmationDialog();
return true;
case android.R.id.home:
if (!mProductHasChanged) {
NavUtils.navigateUpFromSameTask(EditorActivity.this);
return true;
}
DialogInterface.OnClickListener discardButtonClickListener =
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
NavUtils.navigateUpFromSameTask(EditorActivity.this);
}
};
showUnsavedChangesDialog(discardButtonClickListener);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
if (!mProductHasChanged) {
super.onBackPressed();
return;
}
DialogInterface.OnClickListener discardButtonClickListener =
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
};
showUnsavedChangesDialog(discardButtonClickListener);
}
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
String[] projection = {
ProductContract.ProductEntry._ID,
ProductContract.ProductEntry.COLUMN_PRODUCT_NAME,
ProductContract.ProductEntry.COLUMN_PRODUCT_PRICE,
ProductContract.ProductEntry.COLUMN_PRODUCT_QUANTITY,
ProductContract.ProductEntry.COLUMN_PRODUCT_SUPPLIER,
ProductContract.ProductEntry.COLUMN_PRODUCT_SUPPLIER_MAIL,
ProductContract.ProductEntry.COLUMN_PRODUCT_PICTURE};
return new CursorLoader(this, // Parent activity context
mCurrentProductUri, // Query the content URI for the current product
projection, // Columns to include in the resulting Cursor
null, // No selection clause
null, // No selection arguments
null); // Default sort order
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
if (cursor == null || cursor.getCount() < 1) {
return;
}
ViewTreeObserver viewTreeObserver = mProductImageView.getViewTreeObserver();
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
mProductImageView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
mProductImageView.setImageBitmap(getBitmapFromUri(mPictureUri, mContext, mProductImageView));
}
}
});
if (cursor.moveToFirst()) {
int nameColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_NAME);
int priceColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_PRICE);
int quantityColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_QUANTITY);
int supplierColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_SUPPLIER);
int mailColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_SUPPLIER_MAIL);
int pictureColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_PICTURE);
String name = cursor.getString(nameColumnIndex);
String price = cursor.getString(priceColumnIndex);
int quantity = cursor.getInt(quantityColumnIndex);
String supplier = cursor.getString(supplierColumnIndex);
String mail = cursor.getString(mailColumnIndex);
stringUri = cursor.getString(pictureColumnIndex);
Uri uriData = Uri.parse(stringUri);
mNameEditText.setText(name);
mPriceEditText.setText(price);
mQuantityEditText.setText(String.valueOf(quantity));
mSupplierEditText.setText(supplier);
mMailEditText.setText(mail);
if (mPictureUri!=null){
if (stringUri!=null)
mProductImageView.setImageURI(uriData);
else {
Bitmap bM = getBitmapFromUri(mPictureUri, mContext, mProductImageView);
mProductImageView.setImageBitmap(bM);
}}
}
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mNameEditText.setText("");
mPriceEditText.setText("");
mQuantityEditText.setText("");
mSupplierEditText.setText("");
mMailEditText.setText("");
mProductImageView.setImageResource(R.drawable.ic_add_a_photo_black_24dp);
}
private void showUnsavedChangesDialog(
DialogInterface.OnClickListener discardButtonClickListener) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.unsaved_changes_dialog_msg);
builder.setPositiveButton(R.string.discard, discardButtonClickListener);
builder.setNegativeButton(R.string.keep_editing, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (dialog != null) {
dialog.dismiss();
}
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
private void showDeleteConfirmationDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.delete_dialog_msg);
builder.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
deleteProduct();
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (dialog != null) {
dialog.dismiss();
}
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
private void deleteProduct() {
if (mCurrentProductUri != null) {
int rowsDeleted = getContentResolver().delete(mCurrentProductUri, null, null);
if (rowsDeleted == 0) {
Toast.makeText(this, getString(R.string.editor_delete_product_failed),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, getString(R.string.editor_delete_product_successful),
Toast.LENGTH_SHORT).show();
}
}
finish();
}
}
The link to the full code is : https://drive.google.com/open?id=1aQFcWHinIqqXHbTyssfPYTD20o9E2piA
and if you can’t find the java files here they are: https://drive.google.com/drive/folders/1VKp0CoJlJssSdKzK4ctk26KFY0_xIDzU?usp=sharing
In your onLoadFinished you assume mPictureURI is set and is not empty.
Now you have set a listener on mProductImageView for changes. No matter what you write/set down below the mProductImageView finally the in the listener it was set back to mPictureURI which was empty hence showing an empty image space.
Please have a look at the code below(also verified that it works).
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
if (cursor == null || cursor.getCount() < 1) {
return;
}
if (cursor.moveToFirst()) {
int nameColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_NAME);
int priceColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_PRICE);
int quantityColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_QUANTITY);
int supplierColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_SUPPLIER);
int mailColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_SUPPLIER_MAIL);
int pictureColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_PICTURE);
String name = cursor.getString(nameColumnIndex);
String price = cursor.getString(priceColumnIndex);
int quantity = cursor.getInt(quantityColumnIndex);
String supplier = cursor.getString(supplierColumnIndex);
String mail = cursor.getString(mailColumnIndex);
stringUri = cursor.getString(pictureColumnIndex);
mPictureUri = Uri.parse(stringUri);
mNameEditText.setText(name);
mPriceEditText.setText(price);
mQuantityEditText.setText(String.valueOf(quantity));
mSupplierEditText.setText(supplier);
mMailEditText.setText(mail);
}
ViewTreeObserver viewTreeObserver = mProductImageView.getViewTreeObserver();
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
mProductImageView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
if(mPictureUri !=null) {
mProductImageView.setImageBitmap(getBitmapFromUri(mPictureUri, mContext, mProductImageView));
}
}
}
});
}

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

How to Stop extand Thread class In android?

i using call function to javascript to android . i using my android code below how to stop android mthread.i used for MyBackgroudMethod mThread but i want to stop this thread in sendCheckOutBackgroundKill();how to possible.please help me!!!
public class EmployeeManager extends CordovaActivity implements
LocationListener{
JavaScriptInterface jsInterface;
LocationManager locationManager;
boolean isGPSEnabled = false;
boolean network_enabled = false;
String provider;
String lati = "";
String latlong = "";
String accuracy = "";
Location currentLocation;
LocationManager mLocationManager;
String devieID = "";
boolean backgroundtask = false;
String iSGps = "";
String mTime="";
String mEmployeeId="";
String mAttendanceId="";
MyBackgroudMethod mThread;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_employee_manager_main);
super.loadUrl("file:///android_asset/www/index.html");
//mThread = new MyBackgroudMethod();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
/**/
jsInterface = new JavaScriptInterface(EmployeeManager.this);
appView.addJavascriptInterface(jsInterface, "JSInterface");
appView.getSettings().setJavaScriptEnabled(true);
appView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
devieID = getUniquePsuedoID();
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
network_enabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// Creating an empty criteria object
Criteria criteria = new Criteria();
// Getting the name of the provider that meets the criteria
provider = locationManager.getBestProvider(criteria, false);
if (provider != null && !provider.equals("")) {
// Get the location from the given provider
Location location = locationManager.getLastKnownLocation(provider);
if (isGPSEnabled) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
} else if (network_enabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
}
// locationManager.requestLocationUpdates(provider, 1000, 0, this);
if (location != null) {
onLocationChanged(location);
} else {
Toast.makeText(getBaseContext(), "Location can't be retrieved",
Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getBaseContext(), "No Provider Found",Toast.LENGTH_SHORT).show();
}
}
public static String getUniquePsuedoID()
{
String m_szDevIDShort = "35" + (Build.BOARD.length() % 10) + (Build.BRAND.length() % 10) + (Build.CPU_ABI.length() % 10) + (Build.DEVICE.length() % 10) + (Build.MANUFACTURER.length() % 10) + (Build.MODEL.length() % 10) + (Build.PRODUCT.length() % 10);
String serial = null;
try
{
serial = android.os.Build.class.getField("SERIAL").get(null).toString();
return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
}
catch (Exception e)
{
serial = "serial"; // some value
}
return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
}
public class JavaScriptInterface {
public Activity mContext;
public JavaScriptInterface(Activity c) {
this.mContext = c;
}
#JavascriptInterface
public void sendToAndroid(boolean deviceID) {
Log.v("log", "Sent TO android");
runOnUiThread(new Runnable() {
public void run() {
appView.loadUrl("javascript:passLatLong(\"" + lati + "\",\"" + latlong + "\",\"" + accuracy + "\");");
appView.setEnabled(false);
}
});
}
#JavascriptInterface
public void sendToDeviceId() {
runOnUiThread(new Runnable() {
public void run() {
appView.loadUrl("javascript:passDevieId(\"" + devieID + "\");");
}
});
}
#JavascriptInterface
public void sendCheckInBackground(String time, String employeeId, String attendanceId) {
mTime= time;
mEmployeeId = employeeId;
mAttendanceId = attendanceId;
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(EmployeeManager.this, "Check In Background Native", 3000).show();
mThread = new MyBackgroudMethod();
mThread.setDaemon(true);
mThread.start();
}
});
}
public void sendCheckOutBackgroundKill() {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(EmployeeManager.this, "Check Out Background Native Kill", 3000).show();
mThread.interrupt();
}
});
}
}
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("GPS is settings");
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
private class MyBackgroudMethod extends Thread {
#Override
public void run() {
while (true) {
checkInternetConnection();
try {
Thread.sleep(Integer.parseInt(mTime)*60*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
private void checkInternetConnection() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// test for connection
if (cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected()) {
new JSONTask().execute(mTime,mEmployeeId,mAttendanceId);
} else {
Log.v(TAG, "Internet Connection Not Present");
}
}
#Override
public void onLocationChanged(Location location) {
if(location.getAccuracy() < 400) {
lati = Double.toString(location.getLatitude());
latlong = Double.toString(location.getLongitude());
accuracy = Double.toString(location.getAccuracy());
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public class JSONTask extends AsyncTask<String, Void, String> {
public void onPreExecute() {
// progress.show();
}
protected String doInBackground(String... arg) {
// This value will be returned to your
// onPostExecute(result) method
String time1 = arg[0];
String employeeId2 = arg[1];
String attendenceId2 = arg[2];
String img_url = DBAdpter.onFieldCheckIn(employeeId2, attendenceId2, lati, latlong, accuracy);
return img_url;
}
protected void onPostExecute(String result) {
Toast.makeText(EmployeeManager.this, "JSON TASK", 4000).show();
}
}
}
The loop isn't exiting after the interruption. Put a "break;" inside the catch-clause. That's all.

Categories

Resources