SignalR Java Client not working in Android 12 - signalr

I implemented SignalR Java Client in my Android Project. It works well on Android Versions 6 to 11 but fails on Android 12, I'm getting this error only on Android 12 java.net.SocketException: Socket closed [Ljava.lang.StackTraceElement;#e95116d, here is my code:
import android.content.Context;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.microsoft.signalr.HubConnection;
import com.microsoft.signalr.HubConnectionBuilder;
import com.microsoft.signalr.OnClosedCallback;
import org.json.JSONObject;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import timber.log.Timber;
public class SignalRChatService {
Timer timer = new Timer();
public void startTimer()
{
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// Your code here
Timer_Elapsed();
}
}, 1000, 2000);
}
private void Timer_Elapsed()
{
try
{
module.checkNetwork(context);
if(!Connected)
{
Init();
}
}
catch (Exception e)
{
Connected = false;
}
}
private HubConnection _connection;
public boolean Connected;
public String instanceName;
public int instanceProfileId;
private boolean connecting;
private SignalRMessageReceivedEvents signalRMessageReceivedEvents;
private final Gson gson;
private final Context context;
public SignalRChatService(Context context, String instanceName, int instanceProfileId, SignalRMessageReceivedEvents signalRMessageReceivedEvents) {
this.instanceName = instanceName;
this.instanceProfileId = instanceProfileId;
this.connecting = false;
this.context = context;
this.signalRMessageReceivedEvents = signalRMessageReceivedEvents;
gson = new GsonBuilder().setPrettyPrinting().create();
}
public void Stop()
{
try
{
_connection.stop();
}
catch(Exception ignored)
{}
}
public void Init()
{
if (connecting)
{
return;
}
try
{
connecting = true;
_connection = HubConnectionBuilder.create("https://" + instanceName.trim().toLowerCase() + ".com").build();
try
{
_connection.start();
Connected = true;
}
catch (Exception e)
{
Connected = false;
Timber.e("SignalR Push connect: %s", e.getLocalizedMessage());
return;
}
_connection.on("Message", (message) ->
{
try
{
// Separate this code affterwads
JSONObject messageObject = new JSONObject(message);
String Messagetype = (String) messageObject.get("messageType");
HandleWebSocketMessage(Messagetype, message);
}
catch (Exception ignored)
{
}
}, String.class);
_connection.onClosed(new OnClosedCallback() {
#Override
public void invoke(Exception exception) {
handleClosed();
}
});
}
catch (Exception ignored)
{
}
finally
{
connecting = false;
startTimer();
}
}
private void handleClosed()
{
try
{
TimeUnit.MILLISECONDS.sleep(100);
}
catch (Exception ignored)
{
}
Init();
}
}
I've tried upgrading to the latest version of SignalR Java Client
implementation "com.microsoft.signalr:signalr:6.0.3"
and it is still not working. It just wont receive any Signal.

Related

Get current location (city name) without gps and mobile network

I have an android tablet that does not hasve a SIM card and GPS set to save battery mode too.
Tablet is connected to the internet by ethernet (with cable) and connected to LAN by WIFI.
I write a code for find current location (city name) and it work good in my phone. (GPS of my phone is active and connected to the internet by wifi (modem) or mobile network).
package com.xenon.location;
import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import static android.content.Context.LOCATION_SERVICE;
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
private final Activity mActivity;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
protected LocationManager locationManager;
public GPSTracker(Activity activity) {
this.mContext = activity.getBaseContext();
this.mActivity = activity;
getLocation();
}
public Location getLocation() {
try {
//locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
}else{
this.canGetLocation = true;
if (isNetworkEnabled) {
if (ContextCompat.checkSelfPermission(
mActivity, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(mActivity
, new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION}
, 0);
}
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
public void stopUsingGPS() {
if (locationManager != null) {
if (ContextCompat.checkSelfPermission(mActivity, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(mActivity, new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION},
0);
locationManager.removeUpdates(GPSTracker.this);
}
}
}
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
return longitude;
}
public String getCityName() {
String result = "";
if (location != null) {
double latitude, longitude;
List<Address> list;
Locale locale = new Locale("tr");
Geocoder geocoder = new Geocoder(mContext, locale);
try {
list = geocoder.getFromLocation(getLatitude(), getLongitude(), 2);
Address address = list.get(0);
/*
String gpsMsg = "CountryCode: " + address.getCountryCode() +
" ,AdminArea : " + address.getAdminArea() +
" ,CountryName : " + address.getCountryName() +
" ,SubLocality : " + address.getSubLocality();
*/
result = address.getAdminArea();
} catch (IOException e) {
e.printStackTrace();
}
catch (Exception e){
}
}
return result;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
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(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
when run it on Tablet :
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
isNetworkEnabled and canGetLocation always return false;
You can't get location because you disable the GPS.
but if you want to get your location without GPS, try to get the CELL INFORMATION(MNC MCC CELLID AND LAC) where your device Connected then try to USE API (unwiredlab.com) to convert that Cell INFO into location.

Music service Not Working with Album songs

I developing music app.so i create Music service that play in song background so that work perfectly good in when i play song.
But my question is we need different different service for all.
so when i use music Service for album for playing album song that not working.
i don'i know what to do
thanks in advance
that my code
package com.musicbox.google.musicboxlive.Musiclibrary;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentUris;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.Log;
import com.musicbox.google.musicboxlive.Musiclibrary.Song.Songpojo;
import com.musicbox.google.musicboxlive.R;
import java.util.ArrayList;
/**
* Created by Jiagr Fumakiya on 2/1/18.
*/
public class MusicService extends Service implements
MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener,
MediaPlayer.OnCompletionListener {
//media player
private MediaPlayer player;
//song list
private ArrayList<Songpojo> songpojos;
//current position
private int songPosn;
private final IBinder musicBind = new MusicBinder();
String songtitile;
#Override
public IBinder onBind(Intent intent) {
return musicBind;
}
#Override
public void onCreate() {
super.onCreate();
songPosn = 0;
//create player
player = new MediaPlayer();
initMusicPlayer();
}
public void initMusicPlayer() {
//set player properties
player.setWakeMode(getApplicationContext(),
PowerManager.PARTIAL_WAKE_LOCK);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnPreparedListener(this);
player.setOnCompletionListener(this);
player.setOnErrorListener(this);
}
public void setList(ArrayList<Songpojo> theSongpojos) {
songpojos = theSongpojos;
}
public class MusicBinder extends Binder {
public MusicService getService() {
return MusicService.this;
}
}
#Override
public boolean onUnbind(Intent intent) {
player.stop();
player.release();
return false;
}
public void playSong() {
player.reset();
//get song
Songpojo playSongpojo = songpojos.get(songPosn);
songtitile = playSongpojo.getTitle();
//get id
long currSong = playSongpojo.getID();
//set uri
Uri trackUri = ContentUris.withAppendedId
(android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, currSong);
try {
player.setDataSource(getApplicationContext(), trackUri);
} catch (Exception e) {
Log.e("MUSIC SERVICE", "Error setting data source", e);
}
player.prepareAsync();
//player.start();
}
public void nextsong() {
if (songPosn < (songpojos.size() - 1)) {
// play(currentSongIndex - 1);
songPosn = songPosn + 1;
} else {
songPosn = 0;
}
}
public void previousong() {
if (songPosn > 0) {
// play(currentSongIndex - 1);
songPosn = songPosn - 1;
} else {
songPosn = songpojos.size() - 1;
}
}
public void pause() {
if (player.isPlaying()) {
player.pause();
}
}
public void resume() {
int seek = player.getCurrentPosition();
if (!player.isPlaying()) {
player.seekTo(seek);
player.start();
}
}
public void isplaying() {
if (player.isPlaying()) {
player.reset();
}
}
#Override
public void onStart(Intent intent, int startId) {
Log.d("musicid", String.valueOf(startId));
super.onStart(intent, startId);
}
#Override
public void onCompletion(MediaPlayer mp) {
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
return false;
}
#Override
public void onPrepared(MediaPlayer mp) {
//start playback
/* if (mp.isPlaying()) {
mp.reset();
} else {
mp.start();
}*/
mp.start();
Intent notIntent = new Intent(this, MusiclibraryHome.class);
notIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendInt = PendingIntent.getActivity(this, 0,
notIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder builder = new Notification.Builder(this);
builder.setContentIntent(pendInt)
.setSmallIcon(R.drawable.play)
.setTicker(songtitile)
.setOngoing(true)
.setContentTitle("Playing")
.setContentText(songtitile);
Notification not = builder.build();
startForeground(1, not);
}
public void setSong(int songIndex) {
songPosn = songIndex;
}
}
Yes..
After finding lot of online now i get that you need different method to handle each event in Music player (like album,song ,genres) all different.
that is method from playing song album wise in android.
public void playAlbum() {
player.reset();
//get Album song
AlbumPojo albumPojo = albumPojos.get(albumPosn);
id = albumPojo.getId();
songName = albumPojo.getTitle();
albumArt = albumPojo.getAlbumArt();
albumName = albumPojo.getAlbum();
artistName = albumPojo.getAlbum_artist();
Intent intent = new Intent("MusicServiceInfo");
intent.putExtra("songid", id);
intent.putExtra("songtitile", songName);
intent.putExtra("songimage", albumArt);
intent.putExtra("albumname", albumName);
intent.putExtra("artist", artistName);
sendBroadcast(intent);
Log.w("Albumart", "" + albumArt);
//set uri
Uri trackUri = ContentUris.withAppendedId
(android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id);
try {
player.setDataSource(getApplicationContext(), trackUri);
} catch (Exception e) {
Log.e("MUSIC SERVICE", "Error setting data source", e);
}
player.prepareAsync();
}

Java Android code in WinDev

I'm new in WinDev and I'm trying to create an Android application on a honeywell device with a barcode scanner.
I tried 2 different ways in Android Studio and they work.
One is the following:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.honeywell.scanintent.ScanIntent;
public class MainActivity extends Activity {
TextView barcodeData = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
barcodeData = (TextView) findViewById(R.id.textView);
}
public void onSendButtonClick(View v) {
Intent intentScan = new Intent(ScanIntent.SCAN_ACTION);
intentScan.addCategory(Intent.CATEGORY_DEFAULT);
intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
int loadmode = 0;
intentScan.putExtra("scan_mode",ScanIntent.SCAN_MODE_RESULT_AS_URI);
this.startActivityForResult(intentScan, 5);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (resultCode == ScanIntent.SCAN_RESULT_SUCCESSED) {
String data = intent.getStringExtra(ScanIntent.EXTRA_RESULT_BARCODE_DATA);
int format = intent.getIntExtra(ScanIntent.EXTRA_RESULT_BARCODE_FORMAT, 0);
barcodeData.setText(data);
}
else{
barcodeData.setText("FALLITO");
}
}
}
And the other way is this:
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.IOException;
import com.honeywell.decodemanager.DecodeManager;
import com.honeywell.decodemanager.SymbologyConfigs;
import com.honeywell.decodemanager.barcode.DecodeResult;
import com.honeywell.decodemanager.symbologyconfig.SymbologyConfigCode39;
public final class MainActivity extends Activity {
private final int ID_SCANSETTING = 0x12;
private final int ID_CLEAR_SCREEN = 0x13;
private final int SCANKEY = 0x94;
private DecodeManager mDecodeManager = null;
private TextView mDecodeResultEdit = null;
private final int SCANTIMEOUT = 2000;
long mScanAccount = 0;
private boolean mbKeyDown = true;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = (Button) findViewById(R.id.button);
mDecodeResultEdit = (TextView) findViewById(R.id.textView);
button.setOnTouchListener(new Button.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
final int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
try {
if (mbKeyDown) {
DoScan();
mbKeyDown = false;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case MotionEvent.ACTION_UP:
try {
mbKeyDown = true;
cancleScan();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
return true;
}
});
}
private void DoScan() throws Exception {
try {
mDecodeManager.doDecode(SCANTIMEOUT);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onResume() {
super.onResume();
if (mDecodeManager == null) {
mDecodeManager = new DecodeManager(this ,ScanResultHandler);
}
}
#Override
protected void onPause() {
super.onPause();
if (mDecodeManager != null) {
try {
mDecodeManager.release();
mDecodeManager = null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
private Handler ScanResultHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case DecodeManager.MESSAGE_DECODER_COMPLETE:
String strDecodeResult = "";
DecodeResult decodeResult = (DecodeResult) msg.obj;
strDecodeResult = "Decode Result::"+ decodeResult.barcodeData;
mDecodeResultEdit.setText(strDecodeResult);
break;
case DecodeManager.MESSAGE_DECODER_FAIL:
mDecodeResultEdit.setText("FAILED");
break;
case DecodeManager.MESSAGE_DECODER_READY:
{
try {
SymbologyConfigCode39 code39 = new SymbologyConfigCode39();
code39.enableCheckEnable(false);
code39.enableSymbology(false);
code39.setMaxLength(48);
code39.setMinLength(2);
SymbologyConfigs symconfig = new SymbologyConfigs();
symconfig.addSymbologyConfig(code39);
mDecodeManager.setSymbologyConfigs(symconfig);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
break;
default:
super.handleMessage(msg);
break;
}
}
};
private void cancleScan() throws Exception {
mDecodeManager.cancelDecode();
}
}
On WinDev I created a GLOBAL JAVA PROCEDURE and I generated the application, importing the honeywell library, but I don't understand how to implement the android native functions. How can I do this?
Thank you so much!
First add a Global Procedure set to your project and then in this set create an empty Global procedure.
Once the procedure is created on its header bar click on the letters WL and it will convert to JAVA code mode. Now paste you JAVA code!
HTH
Yogi Yang

Fragments MediaPlayer and moving back

I've got an app with Navigation Drawer using fragments. From One of the fragments that lists all tracks, I try to run a media player and show it's associated lyrics. But I'm unable to handle the back button of this fragment.
What I have done here only navigates back to the previous fragment. But I'm unable to click the ListView items after coming back and I'm also unable to click on my nav drawer in the mediaplayer or once I move back from the mediaplayer fragment. Anyone with any ideas?
Here's my code:
package com.myapp.slidingmenu;
import java.io.IOException;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.res.AssetFileDescriptor;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.MediaController;
import android.widget.MediaController.MediaPlayerControl;
import android.widget.Toast;
import com.myapp.myplayer.R;
public class PlayTrackFragment extends Fragment implements MediaPlayerControl {
protected static final Fragment PlayTrackFragment = null;
public PlayTrackFragment(){}
private MediaController mMediaController;
private MediaPlayer mMediaPlayer;
private Handler mHandler = new Handler();
AssetFileDescriptor fd = null;
int iDispatchCounter = 1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_playtrack, container, false);
Bundle args = getArguments();
if (args != null && args.containsKey("id_User"))
{
String userId = args.getString("id_User");
Toast.makeText(rootView.getContext(),userId,Toast.LENGTH_SHORT).show();
}
WebView wv;
wv = (WebView) rootView.findViewById(R.id.webViewPlayTrack);
wv.loadUrl("file:///android_asset/traditions.html");
wv.setBackgroundColor(0x00000000);
wv.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
//AssetFileDescriptor fd = expansionFile.getAssetFileDescriptor(mytracks[trackTitle].toString()+".mp3");
AssetFileDescriptor fd = null;
try {
fd = getActivity().getAssets().openFd("aa01.mp3");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (fd == null)
{
Toast.makeText(rootView.getContext(), "Expansion File Not Loaded", Toast.LENGTH_SHORT).show();
//return;
}
mMediaPlayer = new MediaPlayer();
mMediaController = new MediaController(rootView.getContext()){
#Override
public void hide() {
this.show(0);
}
#Override
public boolean dispatchKeyEvent(KeyEvent event)
{
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && iDispatchCounter == 1)
{
iDispatchCounter++;
rootView.setFocusableInTouchMode(true);
rootView.requestFocus();
if(mMediaPlayer.isPlaying()){ mMediaPlayer.pause();}
//mMediaPlayer = null;
//mMediaController.hide();
mMediaController.setVisibility(View.GONE);
mMediaController = null;
HomeFragment homefragment = new HomeFragment();
PlayTrackFragment playtrackfragment = new PlayTrackFragment();
FragmentManager fragmentManager = getFragmentManager();
FragmentManager fragmentManager2 = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
FragmentTransaction fragmentTransaction2 = fragmentManager2.beginTransaction();
fragmentTransaction.replace(R.id.frame_container, homefragment).commit();
fragmentTransaction2.remove(playtrackfragment).commit();
//fragmentTransaction.commit();
//mMediaPlayer.stop();
//mMediaPlayer = null;
//mMediaController = null;
//getActivity().finish();
//getActivity().onBackPressed();
//Todo: make finish work
//return true;
//Toast.makeText(rootView.getContext(),"Inside onDispatchKey",Toast.LENGTH_SHORT).show();
Log.i((String) getTag(), "onDispatch keyCode: " + event);
//getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
getFragmentManager().popBackStackImmediate();
return false;
}
return false;
}
};
//Original Lines
//mMediaController.setMediaPlayer(PlayTrack.this);
mMediaController.setBackgroundColor(Color.rgb(40, 40, 80));
mMediaController.setMediaPlayer(PlayTrackFragment.this);
mMediaController.setAnchorView(rootView.findViewById(R.id.layoutPlayTrack));
mMediaPlayer.setVolume(1f, 1f);
try {
mMediaPlayer.setDataSource( fd.getFileDescriptor(), fd.getStartOffset(),fd.getLength());
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mMediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mMediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mHandler.post(new Runnable() {
public void run() {
getActivity().setVolumeControlStream(AudioManager.STREAM_SYSTEM);
mMediaPlayer.start();
mMediaController.show(0);
}
});
}
});
/*rootView.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_MOVE){
//mMediaController.show();
//do something
}
return true;
}
});*/
/*rootView.setFocusableInTouchMode(true);
rootView.requestFocus();
rootView.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
Toast.makeText(rootView.getContext(),"Inside onKey",Toast.LENGTH_SHORT).show();
Log.i(getTag(), "onKey keyCode: " + keyCode);
if( keyCode == KeyEvent.KEYCODE_BACK ) {
Log.i(getTag(), "onKey Back listener is working!!!");
getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
return true;
} else {
return false;
}
}
});*/
return rootView;
}
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return true;
}
#Override
public boolean canSeekForward() {
return true;
}
#Override
public int getBufferPercentage() {
int percentage = (mMediaPlayer.getCurrentPosition() * 100) / mMediaPlayer.getDuration();
return percentage;
}
#Override
public int getCurrentPosition() {
if (mMediaPlayer != null){return mMediaPlayer.getCurrentPosition();}
return 0;
}
#Override
public int getDuration() {
return mMediaPlayer.getDuration();
}
#Override
public boolean isPlaying() {
return mMediaPlayer.isPlaying();
}
#Override
public void pause() {
if(mMediaPlayer.isPlaying())
mMediaPlayer.pause();
}
#Override
public void seekTo(int pos) {
mMediaPlayer.seekTo(pos);
}
#Override
public void start() {
mMediaPlayer.start();
}
#Override
public int getAudioSessionId() {
// TODO Auto-generated method stub
return 0;
}
}
I found a solution. I can hide the MediaController in the onDetach of the fragment.
#Override
public void onDetach() {
// TODO Auto-generated method stub
mMediaController.hide();
super.onDetach();
}
But there is still one problem. Although I can pull out my sliding drawer menu, I cannot click it. The MediaController seems to be on top of everything. How can I fix this please?

How to quickly stop seda in camel

I have a camel route with a splitter (using streaming) that sends messages to a seda queue to be processed. When I'm trying to stop the application gently, the seda queue doesn't stop immediately, it is processing all the messages before finally shutting down.
What can I do to stop it right away?
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.ExpressionBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.main.Main;
public class MySedaShutdownTest extends RouteBuilder {
#Override
public void configure() throws Exception {
onException(Exception.class)
.process(new Processor() {
#Override
public void process(Exchange exchange) throws Exception {
System.out.println("exception");
}
});
from("timer:myTimer?repeatCount=1")
.split(ExpressionBuilder.beanExpression(new MySplitter(), "myIterator"))
.streaming()
.to("seda:mySeda");
from("seda:mySeda")
.throttle(1)
.process(new Processor() {
#Override
public void process(Exchange exchange) throws Exception {
System.out.println("processing: " + exchange.getIn().getBody()
+ "; app status: " + exchange.getContext().getStatus());
}
});
}
public static class MySplitter {
public Iterator<String> myIterator() {
List<String> values = new ArrayList<String>();
for (int i = 0; i < 10; i++) {
values.add("string nr : " + i);
}
System.out.println("in myIterator");
return values.iterator();
}
}
public static void main(String[] a) throws Exception {
final Main main = new Main();
new Thread(new Runnable() {
#Override
public void run() {
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
System.out.println("invoking shutdown");
main.shutdown();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
System.out.println("starting app");
main.enableHangupSupport();
main.addRouteBuilder(new MySedaShutdownTest());
main.run();
}
}
There is a purgeQueue method on the SedaEndpoint. So you can get the endpoint and call this method. You can also access it from JMX.
A bit related we have this ticket for improvement
https://issues.apache.org/jira/browse/CAMEL-5911
And I logged a ticket for this
https://issues.apache.org/jira/browse/CAMEL-6405
Just add string below as first line of your configure() method:
getContext().getShutdownStrategy().setTimeout(1);
It will reduce shutdown timeout from 300 seconds (default) to 1
See more info on controlling start-up and shutdown of routes.

Resources