i am trying to autoconnect to bluetooth and return back from bluetooth settings to main activity ?can any one help me? - android-bluetooth

hello i am trying to autoconnect to bluetooth and return back to main activity,but i am not able to auto connect and return back from current activity to main activty....
Of course if there are more easy ways to do it I would appreciate it very much.
here is code==>
public class SimpleUiActivity extends Activity {
private static final String TAG = SimpleUiActivity.class.getSimpleName();
private static final int RESULT_OK = 1;
private static final int RQS_IMAGE = 2;
private static final int RQS_I = 3;
private BluetoothAdapter BA;
private Map<String, Gpio> mGpioMap = new LinkedHashMap<>();
Button ble;
Button campre;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
LinearLayout gpioPinsView = (LinearLayout) findViewById(R.id.gpio_pins);
LayoutInflater inflater = getLayoutInflater();
PeripheralManagerService pioService = new PeripheralManagerService();
for (String name : pioService.getGpioList()) {
View child = inflater.inflate(R.layout.list_item_gpio, gpioPinsView, false);
Switch button = (Switch) child.findViewById(R.id.gpio_switch);
button.setText(name);
gpioPinsView.addView(button);
Log.d(TAG, "Added button for GPIO: " + name);
try {
final Gpio ledPin = pioService.openGpio(name);
ledPin.setEdgeTriggerType(Gpio.EDGE_NONE);
ledPin.setActiveType(Gpio.ACTIVE_HIGH);
ledPin.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);
button.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
try {
ledPin.setValue(isChecked);
} catch (IOException e) {
Log.e(TAG, "error toggling gpio:", e);
buttonView.setOnCheckedChangeListener(null);
// reset button to previous state.
buttonView.setChecked(!isChecked);
buttonView.setOnCheckedChangeListener(this);
}
}
});
mGpioMap.put(name, ledPin);
} catch (IOException e) {
Log.e(TAG, "Error initializing GPIO: " + name, e);
// disable button
button.setEnabled(false);
}
//-----------------
ble=(Button)findViewById(R.id.autobluetooth);
ble.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
ble.postDelayed(new Runnable() {
#Override
public void run() {
BA = BluetoothAdapter.getDefaultAdapter();
BA.enable();
Intent intent=new Intent(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS);
Log.i("aaa","i am here");
// startActivityForResult(intent, RQS_IMAGE);// Activity is started with requestCode 2
finish();
}
}, 10000);
}
});
//-----------------
//-----------------
campre=(Button)findViewById(R.id.camerapreview);
campre.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent1=new Intent(SimpleUiActivity.this,MainActivity.class);
startActivityForResult(intent1, RQS_I);// Activity is started with requestCode 3
}
});
//----------------
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==RESULT_OK) {
switch (requestCode) {
case RQS_IMAGE:
Log.i("abc", "i am here");
Toast.makeText(getApplicationContext(), "Bluetooth switched ON", Toast.LENGTH_LONG).show();
finish();
// textsource.setText(source.toString());
break;
case RQS_I:
break;
}
}
}
#Override
protected void onDestroy() {
super.onDestroy();
for (Map.Entry<String, Gpio> entry : mGpioMap.entrySet()) {
try {
entry.getValue().close();
} catch (IOException e) {
Log.e(TAG, "Error closing GPIO " + entry.getKey(), e);
}
}
mGpioMap.clear();
}
}

Related

Getting the next turn/direction in Mapbox

I'm trying to get the direction of the upcoming turn while travelling, i.e. I want to trigger an event in my app according to the direction of the upcoming turn.
I've tried using event listeners, taking help of the documentation and the provided examples but as I'm pretty new to android studio and mapbox, I've not been successful (my app either crashed or the function would never get triggered). I've also tried searching for getting the voice commands into text form or log form but have failed.
While my current code does display directions and gives voiced instructions, I can't figure out how to access either of them. I'd like to know if there's a simple way of achieving what I'm after without using any event listeners.
private MapView mapView;
private MapboxMap mapboxMap;
private PermissionsManager permissionsManager;
private LocationComponent locationComponent;
private DirectionsRoute currentRoute;
private static final String TAG = "DirectionsActivity";
private NavigationMapRoute navigationMapRoute;
private MapboxNavigation navigation;
private Button button;
private NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this, getString(R.string.access_token));
setContentView(R.layout.activity_main);
mapView = findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
// Toast.makeText(this, "Hello", Toast.LENGTH_SHORT).show();
}
#Override
public void onMapReady(#NonNull final MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
//Toast.makeText(this, "Hello", Toast.LENGTH_SHORT).show();
mapboxMap.setStyle(getString(R.string.navigation_guidance_day), new Style.OnStyleLoaded() {
#Override
public void onStyleLoaded(#NonNull Style style) {
enableLocationComponent(style);
addDestinationIconSymbolLayer(style);
mapboxMap.addOnMapClickListener(MainActivity.this);
button = findViewById(R.id.startButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean simulateRoute = true;
NavigationLauncherOptions options = NavigationLauncherOptions.builder()
.directionsRoute(currentRoute)
.shouldSimulateRoute(simulateRoute)
.build();
NavigationLauncher.startNavigation(MainActivity.this, options);
}
});
}
});
}
private void addDestinationIconSymbolLayer(#NonNull Style loadedMapStyle) {
loadedMapStyle.addImage("destination-icon-id",
BitmapFactory.decodeResource(this.getResources(), R.drawable.mapbox_marker_icon_default));
GeoJsonSource geoJsonSource = new GeoJsonSource("destination-source-id");
Log.d(TAG, "addDestinationIconSymbolLayer: " + geoJsonSource);
loadedMapStyle.addSource(geoJsonSource);
SymbolLayer destinationSymbolLayer = new SymbolLayer("destination-symbol-layer-id", "destination-source-id");
destinationSymbolLayer.withProperties(
iconImage("destination-icon-id"),
iconAllowOverlap(true),
iconIgnorePlacement(true)
);
loadedMapStyle.addLayer(destinationSymbolLayer);
}
#SuppressWarnings( {"MissingPermission"})
#Override
public boolean onMapClick(#NonNull LatLng point) {
Point destinationPoint = Point.fromLngLat(point.getLongitude(), point.getLatitude());
Point originPoint = Point.fromLngLat(locationComponent.getLastKnownLocation().getLongitude(),
locationComponent.getLastKnownLocation().getLatitude());
GeoJsonSource source = mapboxMap.getStyle().getSourceAs("destination-source-id");
Log.d(TAG, "Does this even work");
Log.d(TAG, "onMapClick: " + source.toString());
if (source != null) {
source.setGeoJson(Feature.fromGeometry(destinationPoint));
}
getRoute(originPoint, destinationPoint);
button.setEnabled(true);
button.setBackgroundResource(R.color.mapboxBlue);
return true;
}
private void getRoute(Point origin, Point destination) {
NavigationRoute.builder(this)
.accessToken(Mapbox.getAccessToken())
.origin(origin)
.destination(destination)
.build()
.getRoute(new Callback<DirectionsResponse>() {
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
Log.d(TAG, "Response code: " + response.code());
if (response.body() == null) {
Log.e(TAG, "No routes found, make sure you set the right user and access token.");
return;
} else if (response.body().routes().size() < 1) {
Log.e(TAG, "No routes found");
return;
}
currentRoute = response.body().routes().get(0);
if (navigationMapRoute != null) {
navigationMapRoute.removeRoute();
} else {
navigationMapRoute = new NavigationMapRoute(null, mapView, mapboxMap, R.style.NavigationMapRoute);
}
navigationMapRoute.addRoute(currentRoute);
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable throwable) {
Log.e(TAG, "Error: " + throwable.getMessage());
}
});
}
#SuppressWarnings( {"MissingPermission"})
private void enableLocationComponent(#NonNull Style loadedMapStyle) {
if (PermissionsManager.areLocationPermissionsGranted(this)) {
locationComponent = mapboxMap.getLocationComponent();
locationComponent.activateLocationComponent(this, loadedMapStyle);
locationComponent.setLocationComponentEnabled(true);
locationComponent.setCameraMode(CameraMode.TRACKING);
} else {
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
public void onExplanationNeeded(List<String> permissionsToExplain) {
Toast.makeText(this, R.string.user_location_permission_explanation, Toast.LENGTH_LONG).show();
}
#Override
public void onPermissionResult(boolean granted) {
if (granted) {
enableLocationComponent(mapboxMap.getStyle());
} else {
Toast.makeText(this, R.string.user_location_permission_not_granted, Toast.LENGTH_LONG).show();
finish();
}
}
// Add the mapView's own lifecycle methods to the activity's lifecycle methods
#Override
public void onStart() {
super.onStart();
mapView.onStart();
}
#Override
public void onResume() {
super.onResume();
mapView.onResume();
// Toast.makeText(this, "Hello", Toast.LENGTH_SHORT).show();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onStop() {
super.onStop();
mapView.onStop();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
}
It sounds like you might want to look at using an event listener for a custom milestone. Here's a link to the docs:
https://docs.mapbox.com/android/navigation/overview/milestones/#milestone-event-listener

Why do i never enter in specific callback functions in native interface?

I'm making an application which has to detect a bluetooth card reader and if a card is inserted or removed from this one.
I'm using an API for the android part in my native interface so I implement two callback functions from an interface which concerns the bluetooth card reader detection and two other callback functions which concerns the detection of cards in the bluetooth card reader.
Two callback functions which are called when the bluetooth card reader is detected and the two others which are called when a card is inserted or removed from the device.
I have no problem with the callback which are called when the bluetooth card reader is detected but the application never calls the functions which must be called when the card are inserted or removed.
public class FtReaderNativeImpl implements BluetoothRead.CardListener,BluetoothRead.ReaderListener{
private BluetoothRead btRead;
ArrayList<BluetoothDevice> listRead;
public String scanBluetooth(){
String chaine ="";
if (Looper.myLooper() == null)
{
Looper.prepare();
}
Log.p("btread avant init:"+btRead);
btRead = new
BluetoothRead(com.codename1.impl.android.AndroidNativeUtil.getContext());
btRead.setCardListener(this);
btRead.setReaderListener(this);
ReturnCode rc = btRead.btInitLib();
Log.p("btread après init:"+btRead);
Log.p("rc:"+rc);
return chaine;
}
#Override
public void CardInserted()
{
//showMessage("onCardInserted");
String chaine="";
//Toast.makeText(com.codename1.impl.android.AndroidNativeUtil.getActivity(), "INSERTED", Toast.LENGTH_SHORT).show();
chaine+=btRead.getName();
chaine+=btRead.getFirstName();
eidReader.showDialog("INSERTED "+chaine);
Log.p("btInsertOK");
}
#Override
public void CardRemoved()
{
String chaine="";
//Toast.makeText(com.codename1.impl.android.AndroidNativeUtil.getActivity(), "REMOVED", Toast.LENGTH_SHORT).show();
EidReader.showDialog("REMOVED "+chaine);
Log.p("btRemoveNOK");
}
#Override
public void ReaderConnected(BluetoothDevice bluetoothDevice)
{
/*Toast.makeText(com.codename1.impl.android.AndroidNativeUtil.getActivity(), "CONNECTED", Toast.LENGTH_SHORT).show();*/
EidReader.showDialog("CONNECTED");
Log.p("onReaderConnected: " + bluetoothDevice.getName());
if (btRead.btOpen(bluetoothDevice) == ReturnCode.OK) {
Log.p("btOpen OK");
} else {
Log.p("btOpen NOK");
}
Log.p("btread après listener:"+btRead);
}
#Override
public void ReaderDisconnected(BluetoothDevice bluetoothDevice)
{
//Toast.makeText(com.codename1.impl.android.AndroidNativeUtil.getActivity(), "DISCONNECTED", Toast.LENGTH_SHORT).show();
EidReader.showDialog("DISCONNECTED");
}}
ScanBluetooth is just a initialization method which is called in the beginning of the form:
public class EidReader extends Form implements HasLogger {
Container loggatt = new Container();
private Bluetooth bt;
private static Container devicesCnt;
private Map devices = new HashMap();
Form main = this;
FtReaderNative frn;
public EidReader(Form parent)
{
this.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
Display dis = Display.getInstance();
frn = (FtReaderNative)NativeLookup.create(FtReaderNative.class);
if(dis.getPlatformName().compareTo("and")==0){
LocationManager lm = LocationManager.getLocationManager();
}
bt = new Bluetooth();
frn.scanBluetooth();
//combo.setRenderer(new GenericListCellRenderer<>(new MultiButton(),new MultiButton()));
this.add(new Button(new Command("enable bluetooth")
{
#Override
public void actionPerformed(ActionEvent evt){
try {
if (!bt.isEnabled()) {
bt.enable();
}
if (!bt.hasPermission()) {
bt.requestPermission();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}));
this.add(new Button(new Command("initialize")
{
#Override
public void actionPerformed(ActionEvent evt)
{
try {
bt.initialize(true, false, "bluetoothleplugin");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}));
Button bttest = new Button("DISPLAY READER");
bttest.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ev)
{
DeleteUI();
StringTokenizer st = new StringTokenizer(frn.infoDevices());
while (st.hasMoreTokens()) {
MultiButton mb = new MultiButton(st.nextToken());
mb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
devicesCnt.add(new SpanLabel(frn.readerStatus( mb.getTextLine1())));
}});
devicesCnt.add(mb);
}
}
});
this.add(bttest);
devicesCnt = new Container(new BoxLayout(BoxLayout.Y_AXIS));
devicesCnt.setScrollableY(true);
this.add(devicesCnt);
this.show();
}
private void DeleteUI()
{
devicesCnt.removeAll();
devicesCnt.revalidate();
}
#Override
public String getLogName()
{
// TODO Auto-generated method stub
return null;
}
public static void showDialog(String txt)
{
//Display.getInstance().callSerially(()->
//{
devicesCnt.add(new SpanLabel(txt));
devicesCnt.forceRevalidate();
//});
}
}

Codenameone closing a socket

There seems to be no way of disconnecting a socket without causing a connection reset error on the server side.
I'm using the com.codename1.io.Socket and com.codename1.io.SocketConnection implementations within a tester app. My code is as follows:
private SpanLabel lblStatus;
private SpanLabel lblIncoming;
private CustomSocketConnection con;
private Thread tIncoming;
public ConnectForm() {
con = getSocketConnection();
Button btnConnect = getConnectButton();
Button btnDisconnect = getDisconnectButton();
Button btnSendMessage = getSendMessageButton();
lblStatus = getInfoLabel();
lblIncoming = getIncomingLabel();
setLayout(new BoxLayout(BoxLayout.Y_AXIS));
addComponent(btnConnect);
addComponent(btnDisconnect);
addComponent(btnSendMessage);
addComponent(lblStatus);
addComponent(lblIncoming);
}
private Button getConnectButton() {
Button btn = new Button("Connect (localhost)");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Socket.connect("localhost", 8687, con);
}
});
return btn;
}
private Button getDisconnectButton() {
Button btn = new Button("Disconnect");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//??? I don't know how to do this
try {
tIncoming.join();
} catch (Exception e) {
e.printStackTrace();
tIncoming.interrupt();
}
}
});
return btn;
}
private Button getSendMessageButton() {
Button btn = new Button("Send Message");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
try {
con.os.write("Hello".getBytes());
con.os.write(Integer.parseInt("04", 16)); //end of transmit
con.os.flush();
lblStatus.setText("Message Sent");
} catch (Exception e) {
e.printStackTrace();
}
}
});
return btn;
}
private SpanLabel getInfoLabel() {
return new SpanLabel("Disconnected");
}
private SpanLabel getIncomingLabel() {
return new SpanLabel("...");
}
private CustomSocketConnection getSocketConnection() {
return new CustomSocketConnection();
}
class CustomSocketConnection extends SocketConnection {
public OutputStream os;
public InputStream is;
#Override
public void connectionError(int errorCode, String message) {
lblStatus.setText("Error Connecting. ErrorCode: " + errorCode + " Message: " + message);
}
#Override
public void connectionEstablished(InputStream is, OutputStream os) {
lblStatus.setText("Connected :)");
this.is = is;
this.os = os;
spawnIncomingMessageWatcher();
}
}
private void spawnIncomingMessageWatcher() {
tIncoming = new Thread(new Runnable() {
public void run() {
String s = "";
int eot = Integer.parseInt("04", 16);
while (con.isConnected()) {
try {
int temp;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while (((temp = con.is.read()) != -1) && (temp != eot)) {
baos.write(temp);
}
lblIncoming.setText(new String(baos.toByteArray()));
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
tIncoming.start();
}
With the getDisconnectButton() method, I do not know how to properly disconnect from the server, as the SocketConnection object does not seem to have an appropriate method for this.
If you call close() on either the Input- or OutputStream then you close the Socket, code from Socket.SocketInputStream class link.
public void close() throws IOException {
closed = true;
if(Util.getImplementation().isSocketConnected(impl)) {
Util.getImplementation().disconnectSocket(impl);
con.setConnected(false);
}
}
So first send close instruction to Server and then close a stream.
Hope this helps,

Show toast if mp3 file there was not in SD card

In this class a mp3 file played from sd card, but if mp3 file not available
app give "force close"
i want cods that show toast if mp3 there was not in SD card(Not download) and back to previous activity.plase help me
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getInit();
seekUpdation();
}
public void getInit() {
seek_bar = (SeekBar) findViewById(R.id.seek_bar);
play_button = (Button) findViewById(R.id.play_button);
pause_button = (Button) findViewById(R.id.pause_button);
text_shown = (TextView) findViewById(R.id.text_shown);
play_button.setOnClickListener(this);
pause_button.setOnClickListener(this);
String filePath = Environment.getExternalStorageDirectory() + "/Android/music.mp3";
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(filePath);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException 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();
}
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
}
});
mediaPlayer.prepareAsync();
seek_bar.setMax(mediaPlayer.getDuration());
}
Runnable run = new Runnable() {
#Override
public void run() {
seekUpdation();
}
};
public void seekUpdation() {
seek_bar.setProgress(mediaPlayer.getCurrentPosition());
seekHandler.postDelayed(run, 1000);
seek_bar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seek_bar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seek_bar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seek_bar, int progress, boolean fromUser) {
if(fromUser){
mediaPlayer.seekTo(progress);
seek_bar.setProgress(progress);
}
}
});
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.play_button:
text_shown.setText("Playing...");
mediaPlayer.start();
break;
case R.id.pause_button:
mediaPlayer.pause();
text_shown.setText("Paused...");
}
}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if(fromUser){
mediaPlayer.seekTo(progress);
seekBar.setProgress(progress);
}
}
In IOException catch block place this code:
Toast.makeText(context,'No mp3 file found',Toast.LENGTH_SHORT).show();
this.finish()
finish() will complete current activity and backs to the previous activity.

Android Media Player implementation randomly stops playing: Error (1 -1007)

My Android Media Player randomly stops playing. I dont know why. I am using two Media Players for a gapless loop. After a while the sound stops. The issue appers after seconds or minutes. I tried several fixes:
declaring static media player (according to this)
reducing bitrate (now i have 64 bit/s ogg files)
setWakeMode() (according to this)
None of them solved my problem. Any suggestions? THX!
Code:
private Context context;
private Handler handler;
private Runnable myRunnable;
/*Ausgabe*/
private ImageView cover;
private static MediaPlayer mp;
private static MediaPlayer mp2;
private Uri myUri;
private String curTitle;
private String curPow;
private boolean curMP; //false=mp1, true= mp2
/*Control*/
private ToggleButton onoff;
private Spinner spinner;
private Switch throttle;
/*Volume*/
private SeekBar volumeSeekbar = null;
private AudioManager audioManager = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jukebox);
context = this;
/*Control-Setup*/
initControls();
initButtons();
/*Sound Setup*/
mp = new MediaPlayer();
mp2 = new MediaPlayer(); //workarround f gapless looping
setDisc("classic");
/*Image Setup*/
cover = (ImageView) findViewById(R.id.imageGallerie);
cover.setImageResource(R.drawable.classic);
}
#Override
protected void onDestroy() {
super.onDestroy();
if(mp!=null){
mp.stop();
mp.release();
mp = null;
}
if(mp2!=null){
mp2.stop();
mp2.release();
mp2=null;
}
}
/*sound-file selection*/
public void setDisc(String s){
String tmp = "";
if(throttle.isEnabled()==true && throttle.isChecked())
tmp="2";
myUri = getUri(s+tmp);
curTitle=s;
curPow=tmp;
try {
mp.reset();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setDataSource(context, myUri);
mp.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
mp.prepare();
mp2.reset();
mp2.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp2.setDataSource(context, myUri);
mp2.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
mp2.prepare();
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp2.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
setMyLoop();
play();
}
});
}
});
} catch (IllegalArgumentException e) {
e.printStackTrace();
// Arrr, devensive programming... change request
Toast.makeText(context, getResources().getString(R.string.error3), Toast.LENGTH_LONG).show();
} catch (SecurityException e) {
e.printStackTrace();
Toast.makeText(context, getResources().getString(R.string.error3), Toast.LENGTH_LONG).show();
} catch (IllegalStateException e) {
e.printStackTrace();
Toast.makeText(context, getResources().getString(R.string.error3), Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(context, getResources().getString(R.string.error3), Toast.LENGTH_LONG).show();
}
}
/*Gapless Looping - api 16 oder higher */
public void setMyLoop(){
final AssetFileDescriptor afd = getResources().openRawResourceFd(getRawId(this, curTitle.concat(curPow)));
mp.setNextMediaPlayer(mp2);
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.reset();
try {
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
mediaPlayer.prepare();
} catch (Exception e) {
Toast.makeText(context, getResources().getString(R.string.error1), Toast.LENGTH_LONG).show();
}
mp2.setNextMediaPlayer(mp);
}
});
mp2.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.reset();
try {
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
mediaPlayer.prepare();
} catch (Exception e) {
Toast.makeText(context, getResources().getString(R.string.error2), Toast.LENGTH_LONG).show();
}
mp.setNextMediaPlayer(mp2);
}
});
}
/*play sound*/
public void play(){
if(onoff.isChecked()){
mp.start();
}
}
/*gui control*/
#Override
public void onClick(View v) {
if(v == onoff){
if(onoff.isChecked()==false){
mpAnhalten();
}
else{
mpStarten();
}
}
...
}
#Override
public void onPause(){
super.onPause();
if(mp!=null)
mpAnhalten();
}
/*pause player*/
public void mpAnhalten(){
if(mp2.isPlaying()){
mp2.pause();
curMP=true;
}
else {
if(mp.isPlaying()){
mp.pause();
}
curMP=false;
}
}
/*start player again*/
public void mpStarten(){
if(curMP==true)
mp2.start();
else
mp.start();
}
#Override
public void onResume(){
super.onResume();
View v = findViewById(R.id.LinearLayout1);
if(mp!=null && onoff.isChecked())
mpStarten();
}
/*volume*/
private void initControls(){
try{
volumeSeekbar = (SeekBar)findViewById(R.id.seekBar1);
getApplicationContext();
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
volumeSeekbar.setMax(audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
volumeSeekbar.setProgress(audioManager.getStreamVolume(AudioManager.STREAM_MUSIC));
volumeSeekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar arg0) {
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
}
#Override
public void onProgressChanged(SeekBar arg0, int progress, boolean arg2) {
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
progress, 0);
}
});
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(), getResources().getString(R.string.error1), Toast.LENGTH_LONG).show();
}
}
/*gui-control sound-file selection*/
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selection = parent.getItemAtPosition(position).toString();
if(selection.equals("Classic")){
cover.setImageResource(getImageId(this, "classic"));
cover.invalidate();
throttle.setEnabled(true);
setDisc("classic");
}
...
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
...
/*oncreate submethode*/
private void initButtons(){
/*On Off*/
onoff = (ToggleButton) findViewById(R.id.onoff);
onoff.setChecked(false);
onoff.setOnClickListener(this);
/*track selection*/
spinner = (Spinner) findViewById(R.id.spinner1);
spinner.setOnItemSelectedListener(this);
List<String> list = new ArrayList<String>();
list.add("Modern");
...
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
/*power*/
throttle = (Switch) findViewById(R.id.throttle);
throttle.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
setDisc(curTitle);
}
});
throttle.setChecked(false);
}
Edit:
This is the log output:
07-26 16:07:58.707: W/SoftVorbis(191): vorbis_dsp_synthesis returned -135
07-26 16:07:58.779: E/NuPlayerDecoder(191): Stream error for OMX.google.vorbis.decoder (err=-1007), EOS successfully queued
07-26 16:07:58.780: E/NuPlayer(191): received error(0xfffffc11) from audio decoder, flushing(0), now shutting down
07-26 16:07:58.780: E/MediaPlayer(30858): error (1, -1007)
07-26 16:07:58.781: E/MediaPlayer(30858): Error (1,-1007)
I don't know what is wrong.

Resources