Android runOnUiThread - android

I'm trying to get values through a query for the azure! After that I wanted to try to get these values and move to a new intent but I do not know how to do this because of threads
Here I start QrCode to find an id that I need
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.qrcode_activity);
cameraPreview = findViewById(R.id.cameraPreview);
txtResult = findViewById(R.id.txtresult);
barcodeDetector = new BarcodeDetector.Builder(this).
setBarcodeFormats(Barcode.QR_CODE).build();
cameraSource = new CameraSource.Builder(getApplicationContext(), barcodeDetector)
.setRequestedPreviewSize(640, 480).build();
intent = new Intent(getBaseContext(), ValuesActivity.class);
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> qrcodes = detections.getDetectedItems();
if(qrcodes.size() != 0)
{
txtResult.post(new Runnable() {
#Override
public void run() {
//Create vibrate
Vibrator vibrator = (Vibrator)getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(100);
_idDevice = qrcodes.valueAt(0).displayValue;
txtResult.setText(qrcodes.valueAt(0).displayValue);
getQuery();
}
});
}
}
});
cameraPreview.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
ActivityCompat.requestPermissions(QrCodeActivity.this, new String[]{Manifest.permission.CAMERA},RequestCameraPermissionID);
return;
}
try {
cameraSource.start(cameraPreview.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
}
This is where I do the query, however, as I call runUIThread I can not access the variables from that thread for another try.
As you can see:
public void getQuery(){
try
{
final ProgressDialog dialog = ProgressDialog.show(QrCodeActivity.this, "", "Loading. Please wait...", true);
Query query = Query.Companion.select()
.from("Equipment")
.where("deviceId", "Box2");
AzureData.queryDocuments("Equipment", "valuesDatabase", query, DictionaryDocument.class,null, onCallback( response -> {
Log.e(TAG, "Document list result: " + response.isSuccessful());
idnomes = new ArrayList<>();
listaValues = new ArrayList<>();
listaValuesSensor = new HashMap<>();
datasAlertas = new ArrayList<>();
runOnUiThread(() -> {
int i = 0;
for( Document d : response.getResource().getItems()){
if(response.getResource().getItems().get(i).get("deviceId").equals("Box2")) {
Object alert = response.getResource().getItems().get(i).get("alert");
Object valueSensor = response.getResource().getItems().get(i).get("value");
Object datavalor = response.getResource().getItems().get(i).get("data");
i++;
if(listaValuesSensor.isEmpty()){
listaValues.add(Integer.valueOf(valueSensor.toString()));
listaValuesSensor.put(alert.toString(),listaValues );
datasAlertas.add(datavalor.toString());
}else{
if(listaValuesSensor.containsKey(alert.toString())){
ArrayList<Integer> o = listaValuesSensor.get(alert.toString());
o.add(Integer.valueOf(valueSensor.toString()));
listaValuesSensor.put(alert.toString(),o );
datasAlertas.add(datavalor.toString());
}else{
listaValues = new ArrayList<>();
listaValues.add(Integer.valueOf(valueSensor.toString()));
listaValuesSensor.put(alert.toString(), listaValues);
datasAlertas.add(datavalor.toString());
}
}
if(!idnomes.contains(alert.toString())) {
d.setId(alert.toString());
idnomes.add(alert.toString());
}
}
dialog.cancel();
}
});
Intent i = new Intent(getApplicationContext(),ValuesActivity.class);
intent.putExtra("id_equipamento", "Box2");
//intent.putExtra("listaValuesSensor", listaValuesSensor.get(coll.getId()).toString());
intent.putExtra("listaValuesSensor", listaValuesSensor);
intent.putExtra("dataValues", datasAlertas);
startActivity(i);
}));
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}

You didn't pointed out which variables you can't access, so we have to figure it out, but your problem is not that they are in different threads. It seems to be related to the variables' visibility in different scopes. If everything is declared in the same Activity, then you should not have any problems accessing them in the code that you posted, but if they are not in the same class, then you have to change your design.
The only thing I could see is that you are declaring "i" and trying to use "intent":
Intent i = new Intent(getApplicationContext(),ValuesActivity.class);
intent.putExtra("id_equipamento", "Box2");
//intent.putExtra("listaValuesSensor", listaValuesSensor.get(coll.getId()).toString());
intent.putExtra("listaValuesSensor", listaValuesSensor);
intent.putExtra("dataValues", datasAlertas);

Related

onDestroy() is called when press home button in video call using agora.io

onDestroy() is called when press home button in video call using agora.io .
I have 2 project one is for user and other for astrologer. In User app everything in working fine but in astrologer app onDestroy is calling whenever I press the home button.
This is refernce for agora
https://github.com/AgoraIO/Basic-Video-Call/tree/master/One-to-One-Video/Agora-Android-Tutorial-1to1
public class VideoChatViewActivity extends AppCompatActivity {
private static final String TAG = VideoChatViewActivity.class.getSimpleName();
private static final int PERMISSION_REQ_ID = 22;
// Permission WRITE_EXTERNAL_STORAGE is not mandatory
// for Agora RTC SDK, just in case if you wanna save
// logs to external sdcard.
private static final String[] REQUESTED_PERMISSIONS = {
Manifest.permission.RECORD_AUDIO,
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
private RtcEngine mRtcEngine;
private boolean mCallEnd;
private boolean mMuted;
private FrameLayout mLocalContainer;
private RelativeLayout mRemoteContainer;
private SurfaceView mLocalView;
private SurfaceView mRemoteView;
private ImageView mCallBtn;
private ImageView mMuteBtn;
private ImageView mSwitchCameraBtn;
// Customized logger view
/**
* Event handler registered into RTC engine for RTC callbacks.
* Note that UI operations needs to be in UI thread because RTC
* engine deals with the events in a separate thread.
*/
private final IRtcEngineEventHandler mRtcEventHandler = new IRtcEngineEventHandler() {
#Override
public void onJoinChannelSuccess(String channel, final int uid, int elapsed) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.e("TAG", "Join channel success, uid: " + (uid & 0xFFFFFFFFL));
}
});
}
#Override
public void onFirstRemoteVideoDecoded(final int uid, int width, int height, int elapsed) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.e("TAG", "First remote video decoded, uid: " + (uid & 0xFFFFFFFFL));
setupRemoteVideo(uid);
}
});
}
#Override
public void onUserOffline(final int uid, int reason) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.e("TAG", "User offline, uid: " + (uid & 0xFFFFFFFFL));
onRemoteUserLeft();
}
});
}
};
private void setupRemoteVideo(int uid) {
// Only one remote video view is available for this
// tutorial. Here we check if there exists a surface
// view tagged as this uid.
int count = mRemoteContainer.getChildCount();
View view = null;
for (int i = 0; i < count; i++) {
View v = mRemoteContainer.getChildAt(i);
if (v.getTag() instanceof Integer && ((int) v.getTag()) == uid) {
view = v;
}
}
if (view != null) {
return;
}
mRemoteView = RtcEngine.CreateRendererView(getBaseContext());
mRemoteContainer.addView(mRemoteView);
mRtcEngine.setupRemoteVideo(new VideoCanvas(mRemoteView, VideoCanvas.RENDER_MODE_HIDDEN, uid));
mRemoteView.setTag(uid);
}
private void onRemoteUserLeft() {
removeRemoteVideo();
}
private void removeRemoteVideo() {
if (mRemoteView != null) {
mRemoteContainer.removeView(mRemoteView);
}
mRemoteView = null;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_chat_view);
initUI();
// Ask for permissions at runtime.
// This is just an example set of permissions. Other permissions
// may be needed, and please refer to our online documents.
if (checkSelfPermission(REQUESTED_PERMISSIONS[0], PERMISSION_REQ_ID) &&
checkSelfPermission(REQUESTED_PERMISSIONS[1], PERMISSION_REQ_ID) &&
checkSelfPermission(REQUESTED_PERMISSIONS[2], PERMISSION_REQ_ID)) {
initEngineAndJoinChannel();
}
}
private void initUI() {
mLocalContainer = findViewById(R.id.local_video_view_container);
mRemoteContainer = findViewById(R.id.remote_video_view_container);
mCallBtn = findViewById(R.id.btn_call);
mMuteBtn = findViewById(R.id.btn_mute);
mSwitchCameraBtn = findViewById(R.id.btn_switch_camera);
// Sample logs are optional.
showSampleLogs();
}
private void showSampleLogs() {
Log.e("TAG", "Welcome to Agora 1v1 video call");
}
private boolean checkSelfPermission(String permission, int requestCode) {
if (ContextCompat.checkSelfPermission(this, permission) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, REQUESTED_PERMISSIONS, requestCode);
return false;
}
return true;
}
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == PERMISSION_REQ_ID) {
if (grantResults[0] != PackageManager.PERMISSION_GRANTED ||
grantResults[1] != PackageManager.PERMISSION_GRANTED ||
grantResults[2] != PackageManager.PERMISSION_GRANTED) {
showLongToast("Need permissions " + Manifest.permission.RECORD_AUDIO +
"/" + Manifest.permission.CAMERA + "/" + Manifest.permission.WRITE_EXTERNAL_STORAGE);
finish();
return;
}
// Here we continue only if all permissions are granted.
// The permissions can also be granted in the system settings manually.
initEngineAndJoinChannel();
}
}
private void showLongToast(final String msg) {
this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
});
}
private void initEngineAndJoinChannel() {
// This is our usual steps for joining
// a channel and starting a call.
initializeEngine();
setupVideoConfig();
setupLocalVideo();
joinChannel();
}
private void initializeEngine() {
try {
mRtcEngine = RtcEngine.create(getBaseContext(), getString(R.string.agora_app_id), mRtcEventHandler);
} catch (Exception e) {
Log.e(TAG, Log.getStackTraceString(e));
throw new RuntimeException("NEED TO check rtc sdk init fatal error\n" + Log.getStackTraceString(e));
}
}
private void setupVideoConfig() {
// In simple use cases, we only need to enable video capturing
// and rendering once at the initialization step.
// Note: audio recording and playing is enabled by default.
mRtcEngine.enableVideo();
// Please go to this page for detailed explanation
// https://docs.agora.io/en/Video/API%20Reference/java/classio_1_1agora_1_1rtc_1_1_rtc_engine.html#af5f4de754e2c1f493096641c5c5c1d8f
mRtcEngine.setVideoEncoderConfiguration(new VideoEncoderConfiguration(
VideoEncoderConfiguration.VD_640x360,
VideoEncoderConfiguration.FRAME_RATE.FRAME_RATE_FPS_15,
VideoEncoderConfiguration.STANDARD_BITRATE,
VideoEncoderConfiguration.ORIENTATION_MODE.ORIENTATION_MODE_FIXED_PORTRAIT));
}
private void setupLocalVideo() {
// This is used to set a local preview.
// The steps setting local and remote view are very similar.
// But note that if the local user do not have a uid or do
// not care what the uid is, he can set his uid as ZERO.
// Our server will assign one and return the uid via the event
// handler callback function (onJoinChannelSuccess) after
// joining the channel successfully.
mLocalView = RtcEngine.CreateRendererView(getBaseContext());
mLocalView.setZOrderMediaOverlay(true);
mLocalContainer.addView(mLocalView);
mRtcEngine.setupLocalVideo(new VideoCanvas(mLocalView, VideoCanvas.RENDER_MODE_HIDDEN, 0));
}
private void joinChannel() {
// 1. Users can only see each other after they join the
// same channel successfully using the same app id.
// 2. One token is only valid for the channel name that
// you use to generate this token.
mRtcEngine.joinChannel(null, getIntent().getExtras().getString("channel_name"), "Extra Optional Data", 0);
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.e(TAG, "onDestroy: ");
if (!mCallEnd) {
leaveChannel();
}
RtcEngine.destroy();
}
#Override
protected void onPause() {
super.onPause();
Log.e(TAG, "onPause: ");
}
#Override
protected void onStop() {
super.onStop();
Log.e(TAG, "onStop: ");
}
private void leaveChannel() {
mRtcEngine.leaveChannel();
}
public void onLocalAudioMuteClicked(View view) {
mMuted = !mMuted;
mRtcEngine.muteLocalAudioStream(mMuted);
int res = mMuted ? R.drawable.btn_mute : R.drawable.btn_mute;
mMuteBtn.setImageResource(res);
}
public void onSwitchCameraClicked(View view) {
mRtcEngine.switchCamera();
}
public void onCallClicked(View view) {
if (mCallEnd) {
startCall();
mCallEnd = false;
mCallBtn.setImageResource(R.drawable.btn_end_call);
} else {
endCall();
mCallEnd = true;
mCallBtn.setImageResource(R.drawable.btn_end_call);
}
showButtons(!mCallEnd);
}
private void startCall() {
setupLocalVideo();
joinChannel();
}
private void endCall() {
removeLocalVideo();
removeRemoteVideo();
leaveChannel();
}
private void removeLocalVideo() {
if (mLocalView != null) {
mLocalContainer.removeView(mLocalView);
}
mLocalView = null;
}
private void showButtons(boolean show) {
int visibility = show ? View.VISIBLE : View.GONE;
mMuteBtn.setVisibility(visibility);
mSwitchCameraBtn.setVisibility(visibility);
}
}
Welcome to codding party.
you should implement
onSaveInstanceState
and
onRestoreInstanceState
properly. The framework may kill your Activity at any time it isn't foreground.
other way u can Use Foreground service for keeping alive your call.

HERE Map Turn By Turn Activate

i'm developing turn by turn based navigation application on android. I'm using HERE maps sdk for android. I can't switch to navigation driver mode for turn by turn navigation. How can i switch normal map to turn by turn mode.
Note: I changed to map scheme mode
map.setMapScheme(Map.Scheme.CARNAV_TRAFFIC_DAY);
public class BasicMapActivity extends Activity {
// permissions request code
private final static int REQUEST_CODE_ASK_PERMISSIONS = 1;
private PositioningManager posManager;
private MapRoute mapRoute;
private Route route;
private GeoPosition myPosition;
/**
* Permissions that need to be explicitly requested from end user.
*/
private static final String[] REQUIRED_SDK_PERMISSIONS = new String[] {
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE };
// map embedded in the map fragment
private Map map = null;
// map fragment embedded in this activity
private MapFragment mapFragment = null;
private PositioningManager.OnPositionChangedListener positionListener = new PositioningManager.OnPositionChangedListener() {
#Override
public void onPositionUpdated(PositioningManager.LocationMethod locationMethod, GeoPosition geoPosition, boolean b) {
Log.v("HERE MAP",geoPosition.getCoordinate().toString());
myPosition = geoPosition;
map.setCenter(geoPosition.getCoordinate(),
Map.Animation.BOW);
// Set the zoom level to the average between min and max
}
#Override
public void onPositionFixChanged(PositioningManager.LocationMethod locationMethod, PositioningManager.LocationStatus locationStatus) {
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
checkPermissions();
}
#Override
protected void onResume() {
super.onResume();
if (posManager != null) {
posManager.start(
PositioningManager.LocationMethod.GPS_NETWORK);
}
}
#Override
protected void onPause() {
super.onPause();
if (posManager != null) {
posManager.stop();
}
}
public void onDestroy() {
if (posManager != null) {
// Cleanup
posManager.removeListener(
positionListener);
}
map = null;
super.onDestroy();
}
private void initialize() {
setContentView(R.layout.activity_main);
findViewById(R.id.btnDrawRoute).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawRoute();
}
});
findViewById(R.id.btnChangeMap).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setNavigationManager();
NavigationManager.Error error = NavigationManager.getInstance().startNavigation(route);
if(error.equals(NavigationManager.Error.NONE)){
map.setExtrudedBuildingsVisible(false);
}
}
});
// Search for the map fragment to finish setup by calling init().
mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.mapfragment);
mapFragment.init(new OnEngineInitListener() {
#Override
public void onEngineInitializationCompleted(OnEngineInitListener.Error error) {
if (error == OnEngineInitListener.Error.NONE) {
// retrieve a reference of the map from the map fragment
map = mapFragment.getMap();
// Set the map center to the Vancouver region (no animation)
map.setZoomLevel((map.getMaxZoomLevel() + map.getMinZoomLevel()) / 2);
map.setCartoMarkersVisible(true);
map.setLandmarksVisible(true);
map.setMapScheme(Map.Scheme.CARNAV_DAY);
map.setTrafficInfoVisible(true);
map.setExtrudedBuildingsVisible(true);
map.setStreetLevelCoverageVisible(true);
mapFragment.getPositionIndicator().setVisible(true);
try {
posManager = PositioningManager.getInstance();
posManager.addListener(new WeakReference<>(positionListener));
posManager.start(
PositioningManager.LocationMethod.GPS_NETWORK);
}catch (Exception ex){
Log.v("Error",ex.getMessage());
}
} else {
System.out.println("ERROR: Cannot initialize Map Fragment");
}
}
});
}
private void setNavigationManager() {
NavigationManager.getInstance().setMap(map);
NavigationManager.getInstance().setMapUpdateMode(NavigationManager.MapUpdateMode.ROADVIEW);
NavigationManager.getInstance().setTrafficAvoidanceMode(NavigationManager.TrafficAvoidanceMode.DYNAMIC);
NavigationManager.getInstance().setRealisticViewMode(NavigationManager.RealisticViewMode.DAY);
NavigationManager.getInstance().setDistanceUnit(NavigationManager.UnitSystem.METRIC);
ArrayList<NavigationManager.NaturalGuidanceMode> arrayList = new ArrayList<NavigationManager.NaturalGuidanceMode>();
arrayList.add(NavigationManager.NaturalGuidanceMode.JUNCTION);
arrayList.add(NavigationManager.NaturalGuidanceMode.STOP_SIGN);
arrayList.add(NavigationManager.NaturalGuidanceMode.TRAFFIC_LIGHT);
EnumSet<NavigationManager.NaturalGuidanceMode> enumSet = EnumSet.copyOf(arrayList);
NavigationManager.getInstance().setNaturalGuidanceMode(enumSet);
setVoice();
ArrayList<NavigationManager.AudioEvent> audioEvents = new ArrayList<>();
audioEvents.add(NavigationManager.AudioEvent.ROUTE);
audioEvents.add(NavigationManager.AudioEvent.GPS);
NavigationManager.getInstance().setEnabledAudioEvents(EnumSet.copyOf(audioEvents));
NavigationManager.getInstance().addNewInstructionEventListener(new WeakReference<NavigationManager.NewInstructionEventListener>(new NavigationManager.NewInstructionEventListener() {
#Override
public void onNewInstructionEvent() {
super.onNewInstructionEvent();
Maneuver maneuver = NavigationManager.getInstance().getNextManeuver();
Log.v("Manevra",maneuver.getNextRoadName() + " "+maneuver.getRoadName());
maneuver.getRoadName();
}
}));
NavigationManager.getInstance().addManeuverEventListener(new WeakReference<NavigationManager.ManeuverEventListener>(new NavigationManager.ManeuverEventListener() {
#Override
public void onManeuverEvent() {
super.onManeuverEvent();
}
}));
NavigationManager.getInstance().addPositionListener(new WeakReference<NavigationManager.PositionListener>(new NavigationManager.PositionListener() {
#Override
public void onPositionUpdated(GeoPosition geoPosition) {
super.onPositionUpdated(geoPosition);
geoPosition.getCoordinate();
geoPosition.getHeading();
geoPosition.getSpeed();
// also remaining time and distance can be
// fetched from navigation manager
NavigationManager.getInstance().getTta(Route.TrafficPenaltyMode.DISABLED, true);
NavigationManager.getInstance().getDestinationDistance();
}
}));
}
private void setVoice() {
// Get the list of voice packages from the voice catalog list
List<VoicePackage> voicePackages = VoiceCatalog.getInstance().getCatalogList();
long id = -1;
// select
for (VoicePackage vPackage : voicePackages) {
if (vPackage.getMarcCode().compareToIgnoreCase("eng") == 0) {
if (vPackage.isTts()) {
id = vPackage.getId();
break;
}
}
}
if(id>-1)
NavigationManager.getInstance().setVoiceSkin(VoiceCatalog.getInstance().getLocalVoiceSkin(id));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
/**
* Checks the dynamically controlled permissions and requests missing permissions from end user.
*/
protected void checkPermissions() {
final List<String> missingPermissions = new ArrayList<String>();
// check all required dynamic permissions
for (final String permission : REQUIRED_SDK_PERMISSIONS) {
final int result = ContextCompat.checkSelfPermission(this, permission);
if (result != PackageManager.PERMISSION_GRANTED) {
missingPermissions.add(permission);
}
}
if (!missingPermissions.isEmpty()) {
// request all missing permissions
final String[] permissions = missingPermissions
.toArray(new String[missingPermissions.size()]);
ActivityCompat.requestPermissions(this, permissions, REQUEST_CODE_ASK_PERMISSIONS);
} else {
final int[] grantResults = new int[REQUIRED_SDK_PERMISSIONS.length];
Arrays.fill(grantResults, PackageManager.PERMISSION_GRANTED);
onRequestPermissionsResult(REQUEST_CODE_ASK_PERMISSIONS, REQUIRED_SDK_PERMISSIONS,
grantResults);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[],
#NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_PERMISSIONS:
for (int index = permissions.length - 1; index >= 0; --index) {
if (grantResults[index] != PackageManager.PERMISSION_GRANTED) {
// exit the app if one permission is not granted
Toast.makeText(this, "Required permission '" + permissions[index]
+ "' not granted, exiting", Toast.LENGTH_LONG).show();
finish();
return;
}
}
// all permissions were granted
initialize();
break;
}
}
private void drawRoute(){
CoreRouter router = new CoreRouter();
GeoCoordinate gebzeCoord = new GeoCoordinate(40.9047617,29.4065243);
GeoCoordinate maslakCoord = new GeoCoordinate(41.1066509,29.0204711);
// Create the RoutePlan and add two waypoints
RoutePlan routePlan = new RoutePlan();
routePlan.addWaypoint(new RouteWaypoint(myPosition.getCoordinate()));
routePlan.addWaypoint(new RouteWaypoint(maslakCoord));
// Create the RouteOptions and set its transport mode & routing type
RouteOptions routeOptions = new RouteOptions();
routeOptions.setTransportMode(RouteOptions.TransportMode.CAR);
routeOptions.setRouteType(RouteOptions.Type.FASTEST);
routePlan.setRouteOptions(routeOptions);
// Calculate the route
router.calculateRoute(routePlan, new RouteListener());
TrafficUpdater trafficUpdater = TrafficUpdater.getInstance();
trafficUpdater.request(route, new TrafficUpdater.Listener() {
#Override
public void onStatusChanged(TrafficUpdater.RequestState requestState) {
}
});
}
private class RouteListener implements CoreRouter.Listener {
// Method defined in Listener
public void onProgress(int percentage) {
// Display a message indicating calculation progress
}
// Method defined in Listener
public void onCalculateRouteFinished(List<RouteResult> routeResult, RoutingError error) {
// If the route was calculated successfully
if (error == RoutingError.NONE) {
// Render the route on the map
mapRoute = new MapRoute(routeResult.get(0).getRoute());
route = routeResult.get(0).getRoute();
map.addMapObject(mapRoute);
}
else {
// Display a message indicating route calculation failure
}
}
}
}
Declare NavigationManager's object as a global object.
private NavigationManager m_navigationManager;
after that initialize it in your setNavigationManager() method.
m_navigationManager = NavigationManager.getInstance();
m_navigationManager.setMap(map);
// try to change current MapUpdateMode to POSITION_ANIMATION
m_navigationManager.setMapUpdateMode(NavigationManager.MapUpdateMode.POSITION_ANIMATION);
m_navigationManager.setTrafficAvoidanceMode(NavigationManager.TrafficAvoidanceMode.DYNAMIC);
m_navigationManager.setRealisticViewMode(NavigationManager.RealisticViewMode.DAY);
// set all other method on this object.
m_navigationManager.......
After you have to start navigation like this
NavigationManager.Error error = m_navigationManager.startNavigation(route);
if (error != NavigationManager.Error.NONE) {
m_navigationManager.setMap(null);
}
//set Tilt to at some angle that you can look in 3d mode
map.setTilt(70f, com.here.android.mpa.mapping.Map.Animation.NONE);
map.setZoomLevel(18);

PocketSphinx on Android recognises words even if they aren't spoken

I am using PocketSphinx for android-23.
I want to code an offline assistant for one of my apps.
I have successfully used recognizer.addKeyphraseSearch to initialize the assistant. For eg. In this case I say "Hello" to initialize it.
this is my entire code
public class Farmax_2 extends Activity implements
RecognitionListener {
/* Named searches allow to quickly reconfigure the decoder */
private static final String KWS_SEARCH = "wakeup";
private static final String ahead = "about";
private static final String PHONE_SEARCH = "ahead";
private static final String MENU_SEARCH = "menu";
TextToSpeech t1;
Button btn;
/* Keyword we are looking for to activate menu */
private static final String KEYPHRASE = "hello";
/* Used to handle permission request */
private static final int PERMISSIONS_REQUEST_RECORD_AUDIO = 1;
private SpeechRecognizer recognizer;
private HashMap<String, Integer> captions;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
setContentView(R.layout.activity_farmax_2);
// Check if user has given permission to record audio
int permissionCheck = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.RECORD_AUDIO);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, PERMISSIONS_REQUEST_RECORD_AUDIO);
return;
}
btn=(Button)findViewById(R.id.buttonme);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent inte = new Intent(Farmax_2.this, MainMenu.class);
startActivity(inte);
}
});
t1 = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
t1.setLanguage(Locale.UK);
}
}
});
runRecognizerSetup();
}
public void omku(View view) { Intent in=new Intent(this,abtus.class);
startActivity(in);}
private void runRecognizerSetup() {
// Recognizer initialization is a time-consuming and it involves IO,
// so we execute it in async task
new AsyncTask<Void, Void, Exception>() {
#Override
protected Exception doInBackground(Void... params) {
try {
Assets assets = new Assets(Farmax_2.this);
File assetDir = assets.syncAssets();
setupRecognizer(assetDir);
} catch (IOException e) {
return e;
}
return null;
}
#Override
protected void onPostExecute(Exception result) {
if (result != null) {
} else {
switchSearch(KWS_SEARCH);
}
}
}.execute();
}
#Override
public void onRequestPermissionsResult(int requestCode,
String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSIONS_REQUEST_RECORD_AUDIO) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
runRecognizerSetup();
} else {
finish();
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (recognizer != null) {
recognizer.cancel();
recognizer.shutdown();
}
}
/**
* In partial result we get quick updates about current hypothesis. In
* keyword spotting mode we can react here, in other modes we need to wait
* for final result in onResult.
*/
#Override
public void onPartialResult(Hypothesis hypothesis) {
if (hypothesis == null)
return;
String text = hypothesis.getHypstr();
switch (text) {
case KEYPHRASE: {
omkar();
break;
}
case ahead: {
Intent in = new Intent(this, abtus.class);
startActivity(in);
break;
// t1.speak("taking you to privacy policy of farmax.", TextToSpeech.QUEUE_FLUSH, null);
}
case PHONE_SEARCH: {
Intent in = new Intent(this, MainMenu.class);
startActivity(in);
// t1.speak("Main Menu.", TextToSpeech.QUEUE_FLUSH, null);
break;
}
}
}
private void omkar() {
t1.speak("Yes sir.", TextToSpeech.QUEUE_FLUSH, null);
switchSearch(MENU_SEARCH);
}
/**
* This callback is called when we stop the recognizer.
*/
#Override
public void onResult(Hypothesis hypothesis) {
if (hypothesis != null) {
String text = hypothesis.getHypstr();
makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBeginningOfSpeech() {
}
/**
* We stop recognizer here to get a final result
*/
#Override
public void onEndOfSpeech() {
}
private void switchSearch(String searchName) {
recognizer.stop();
// If we are not spotting, start listening with timeout (10000 ms or 10 seconds).
if (searchName.equals(KWS_SEARCH))
recognizer.startListening(searchName);
else
recognizer.startListening(searchName, 10000);
}
private void setupRecognizer(File assetsDir) throws IOException {
// The recognizer can be configured to perform multiple searches
// of different kind and switch between them
recognizer = SpeechRecognizerSetup.defaultSetup()
.setAcousticModel(new File(assetsDir, "en-us-ptm"))
.setDictionary(new File(assetsDir, "cmudict-en-us.dict"))
.setRawLogDir(assetsDir) // To disable logging of raw audio comment out this call (takes a lot of space on the device)
.getRecognizer();
recognizer.addListener(this);
/** In your application you might not need to add all those searches.
* They are added here for demonstration. You can leave just one.
*/
// Create keyword-activation search.
recognizer.addKeyphraseSearch(KWS_SEARCH, "hello");
// Create grammar-based search for selection between demos
File menuGrammar = new File(assetsDir, "firstscn.gram");
recognizer.addGrammarSearch(MENU_SEARCH, menuGrammar);
// Create grammar-based search for digit recognition
}
#Override
public void onError(Exception error) {
}
#Override
public void onTimeout() {
switchSearch(KWS_SEARCH);
}
}
when I say hello, it responds correctly by replying "Yes sir" via tts. But after that it is supposed to switch menu and wait for the further commands. In this case there are two.
#Override
public void onPartialResult(Hypothesis hypothesis) {
if (hypothesis == null)
return;
String text = hypothesis.getHypstr();
switch (text) {
case KEYPHRASE: {
omkar();
break;
}
case ahead: {
Intent in = new Intent(this, abtus.class);
startActivity(in);
break;
// t1.speak("taking you to privacy policy of farmax.", TextToSpeech.QUEUE_FLUSH, null);
}
case PHONE_SEARCH: {
Intent in = new Intent(this, MainMenu.class);
startActivity(in);
// t1.speak("Main Menu.", TextToSpeech.QUEUE_FLUSH, null);
break;
}
}
}
But the problem is that It doesnt wait for my command after it switches the menu.
Sometimes a toast pops up with "about" or sometimes with "ahead" even though I dont speak them. The app freezes badly after that and leaves me no other option than to close it.
If have also tried if else statements other than switch and case. But they don't seem to help much.
I have also tried to use the above code in onResult rather than onPartialResult but that doesnt help as well.
using sphinx tools I have created my own dictionary and grammar file.
Here is the grammar file content for this case.
#JSGF V1.0;
grammar firstscn;
public <item> = about | ahead;
Where am I going wrong? Please help me.

Uploading text messages to google drive from android not working

First time I am using GoogleApiClient and want to upload all the text messages to google drive when the share button in the app is clicked. But the data is not uploading on the drive.
MainActivity :
public class MainActivity extends AppCompatActivity {
RecyclerView rv;
SmsAdapter adapter;
FloatingActionButton fab;
Cursor c;
ExportTask task;
ArrayList<CustomSms> smslistSearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
smslistSearch = new ArrayList<>();
rv = (RecyclerView) findViewById(R.id.messages_view);
LinearLayoutManager llm = new LinearLayoutManager(MainActivity.this);
rv.setLayoutManager(llm);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i =new Intent(MainActivity.this,SendSms.class);
startActivity(i);
}
});
}
#Override
protected void onResume() {
super.onResume();
try {
final ArrayList<CustomSms> smslist, smsgrouplist;
smslist = new ArrayList<>();
smsgrouplist = new ArrayList<>();
//Fetch inobx sms message
c = getContentResolver().query(SmsApplication.INBOX_URI, null, null, null, null);
while (c.moveToNext()) {
String address = c.getString(c.getColumnIndexOrThrow("address"));
String date = c.getString(c.getColumnIndexOrThrow("date"));
String body = c.getString(c.getColumnIndexOrThrow("body"));
smslist.add(new CustomSms(address, date, body));
}
smslistSearch = smslist;
Map<String, CustomSms> map = new LinkedHashMap<>();
for (CustomSms ays : smslist) {
CustomSms existingValue = map.get(ays.address);
if(existingValue == null){
map.put(ays.address, ays);
}
}
smsgrouplist.clear();
smsgrouplist.addAll(map.values());
adapter = new SmsAdapter(MainActivity.this);
adapter.updateList(smsgrouplist);
rv.setAdapter(adapter);
rv.addOnItemTouchListener(
new RecyclerItemClickListener(getApplicationContext(), new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
// TODO Handle item click
ArrayList<CustomSms> smsinsidegroup = new ArrayList<CustomSms>();
String n = smsgrouplist.get(position).address;
for (int i = 0; i < smslist.size(); i++) {
if(smslist.get(i).address.equals(n))
smsinsidegroup.add(smslist.get(i));
}
Intent i = new Intent(MainActivity.this, ReadAllSms.class);
i.putParcelableArrayListExtra("messages", smsinsidegroup);
startActivity(i);
}
})
);
}
catch (Exception e)
{
e.printStackTrace();
}
}
class ExportTask extends AsyncTask<Void, Integer, Uri> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Exporting to file ...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgress(0);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Uri doInBackground(Void... params) {
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
FileOutputStream fos = null;
try {
File f = new File(Environment.getExternalStorageDirectory(), "SmsBackUp.txt");
fos = new FileOutputStream(f);
int count = c.getCount(), i = 0;
StringBuilder sb = new StringBuilder();
if (c.moveToFirst()) {
do {
sb.append(c.getString(c.getColumnIndex("address")))
.append("\n");
sb.append(c.getString(c.getColumnIndex("body")))
.append("\n");
sb.append("\n");
publishProgress(++i*100/count);
} while (!isCancelled() && c.moveToNext());
}
fos.write(sb.toString().getBytes());
return Uri.fromFile(f);
} catch (Exception e) {
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {}
}
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
pDialog.setProgress(values[0]);
}
#Override
protected void onPostExecute(Uri result) {
super.onPostExecute(result);
pDialog.dismiss();
if (result == null) {
Toast.makeText(MainActivity.this, "Export task failed!",
Toast.LENGTH_LONG).show();
return;
}
Intent i = new Intent(MainActivity.this,UploadData.class);
startActivity(i);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_search) {
Intent i = new Intent(MainActivity.this,SearchActivity.class);
i.putParcelableArrayListExtra("search", smslistSearch);
startActivity(i);
return true;
}
if (id == R.id.action_share) {
/*Intent i = new Intent(MainActivity.this,UploadData.class);
startActivity(i);*/
task = new ExportTask();
task.execute();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPause() {
if (task != null) {
task.cancel(false);
task.pDialog.dismiss();
}
super.onPause();
}
}
UploadData :
public class UploadData extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "upload_file";
private static final int REQUEST_CODE = 101;
private File textFile;
private GoogleApiClient googleApiClient;
public static String drive_id;
public static DriveId driveID;
FrameLayout rl;
TextView success;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_data);
rl = (FrameLayout) findViewById(R.id.frame);
success = (TextView) findViewById(R.id.success);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
View root = rl.getRootView();
root.setBackgroundColor(getResources().getColor(R.color.colorBackOrig));
textFile = new File(Environment.getExternalStorageDirectory(), "SmsBackUp.txt");
buildGoogleApiClient();
}
#Override
protected void onStart() {
super.onStart();
Log.i(TAG, "connecting...");
googleApiClient.connect();
}
protected void onStop() {
super.onStop();
if (googleApiClient != null) {
Log.i(TAG, "disConnecting...");
googleApiClient.disconnect();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
Log.i(TAG, "In onActivityResult() - connecting...");
googleApiClient.connect();
}
}
#Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "in onConnected() - connected");
Drive.DriveApi.newDriveContents(googleApiClient)
.setResultCallback(driveContentsCallback);
}
#Override
public void onConnectionSuspended(int cause) {
switch (cause) {
case 1:
Log.i(TAG, "Connection suspended - Cause: " + "Service disconnected");
break;
case 2:
Log.i(TAG, "Connection suspended - Cause: " + "Connection lost");
break;
default:
Log.i(TAG, "Connection suspended - Cause: " + "Unknown");
break;
}
}
final private ResultCallback<DriveApi.DriveContentsResult> driveContentsCallback = new
ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
Log.i(TAG, "Error creating the new file of contents");
return;
}
final DriveContents driveContents = result.getDriveContents();
new Thread() {
#Override
public void run() {
OutputStream outputStream = driveContents.getOutputStream();
addTextfileToOutputStream(outputStream);
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle("SmsBackup")
.setMimeType("text/plain")
.setDescription("This is a text file uploaded from device")
.setStarred(true).build();
Drive.DriveApi.getRootFolder(googleApiClient)
.createFile(googleApiClient, changeSet, driveContents)
.setResultCallback(fileCallback);
}
}.start();
}
};
private void addTextfileToOutputStream(OutputStream outputStream) {
byte[] buffer = new byte[1024];
int bytesRead;
try {
BufferedInputStream inputStream = new BufferedInputStream(
new FileInputStream(textFile));
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();
}
});
e.printStackTrace();
}
}
final private ResultCallback<DriveFolder.DriveFileResult> fileCallback = new
ResultCallback<DriveFolder.DriveFileResult>() {
#Override
public void onResult(DriveFolder.DriveFileResult result) {
if (!result.getStatus().isSuccess()) {
Toast.makeText(UploadData.this,
"Error adding file to Drive", Toast.LENGTH_SHORT).show();
return;
}
Toast.makeText(UploadData.this,
"File successfully added to Drive", Toast.LENGTH_SHORT).show();
showProgress(false);
rl.setBackgroundColor(getResources().getColor(R.color.colorBack));
View root = rl.getRootView();
root.setBackgroundColor(getResources().getColor(R.color.colorBack));
success.setVisibility(View.VISIBLE);
final PendingResult<DriveResource.MetadataResult> metadata
= result.getDriveFile().getMetadata(googleApiClient);
metadata.setResultCallback(new ResultCallback<DriveResource.MetadataResult>() {
#Override
public void onResult(DriveResource.MetadataResult metadataResult) {
Metadata data = metadataResult.getMetadata();
drive_id = data.getDriveId().encodeToString();
driveID = data.getDriveId();
}
});
}
};
#Override
public void onConnectionFailed(ConnectionResult result) {
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this, 0).show();
return;
}
try {
result.startResolutionForResult(this, REQUEST_CODE);
} catch (IntentSender.SendIntentException e) {
}
}
private void buildGoogleApiClient() {
if (googleApiClient == null) {
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
progressBar.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
}
}
}
You might want to check on how you work with File Contents, first you might want to check if there is a value on the variable textFile that you have set.
The example below illustrates how to append "hello world" to the DriveContents.
try {
ParcelFileDescriptor parcelFileDescriptor = contents.getParcelFileDescriptor();
FileInputStream fileInputStream = new FileInputStream(parcelFileDescriptor
.getFileDescriptor());
// Read to the end of the file.
fileInputStream.read(new byte[fileInputStream.available()]);
// Append to the file.
FileOutputStream fileOutputStream = new FileOutputStream(parcelFileDescriptor
.getFileDescriptor());
Writer writer = new OutputStreamWriter(fileOutputStream);
writer.write("hello world");
} catch (IOException e) {
e.printStackTrace();
}
There is a related SO question - Upload text file to Google Drive using Android that you might want to check out. The answer in the question reminds the OP regarding how to feed the file with contents.
Lastly, you might want to check this github. This code show how to insert the content of the chat into a file and save it to the drive.
Hope this helps.

How to play an audio from soundcloud in our app.?

Following program allows user to upload an audio from app to SoundCloud.But what if i need to play an audio from my account in soundcloud in my app?How to play an audio from soundcloud or from particular url of soundclous to in our app ?
public class Record extends Activity {
public static final String TAG = "soundcloud-intent-sharing-example";
private boolean mStarted;
private MediaRecorder mRecorder;
private File mArtwork;
private static boolean AAC_SUPPORTED = Build.VERSION.SDK_INT >= 10;
private static final int PICK_ARTWORK = 1;
private static final int SHARE_SOUND = 2;
private static final File FILES_PATH = new File(
Environment.getExternalStorageDirectory(),
"Android/data/com.soundcloud.android.examples/files");
private static final File RECORDING = new File(
FILES_PATH,
"demo-recording" + (AAC_SUPPORTED ? ".mp4" : "3gp"));
private static final Uri MARKET_URI = Uri.parse("market://details?id=com.soundcloud.android");
private static final int DIALOG_NOT_INSTALLED = 0;
// Replace with the client id of your registered app!
// see http://soundcloud.com/you/apps/
private static final String CLIENT_ID = "fecfc092de134a960dc48e53c044ee91";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Environment.MEDIA_MOUNTED.equals(
Environment.getExternalStorageState())) {
if (!FILES_PATH.mkdirs()) {
Log.w(TAG, "Could not create " + FILES_PATH);
}
} else {
Toast.makeText(this, R.string.need_external_storage, Toast.LENGTH_LONG).show();
finish();
}
setContentView(R.layout.record);
final Button record_btn = (Button) findViewById(R.id.record_btn);
final Button share_btn = (Button) findViewById(R.id.share_btn);
final Button play_btn = (Button) findViewById(R.id.play_btn);
final Button artwork_btn = (Button) findViewById(R.id.artwork_btn);
Record last = getLastNonConfigurationInstance();
if (last != null) {
mStarted = last.mStarted;
mRecorder = last.mRecorder;
mArtwork = last.mArtwork;
record_btn.setText(mStarted ? R.string.stop : R.string.record);
}
record_btn.setOnClickListener(new View.OnClickListener() {
public synchronized void onClick(View v) {
if (!mStarted) {
Toast.makeText(Record.this, R.string.recording, Toast.LENGTH_SHORT).show();
mStarted = true;
mRecorder = getRecorder(RECORDING, AAC_SUPPORTED);
mRecorder.start();
record_btn.setText(R.string.stop);
} else {
Toast.makeText(Record.this, R.string.recording_stopped, Toast.LENGTH_SHORT).show();
mRecorder.stop();
mRecorder.release();
mRecorder = null;
mStarted = false;
record_btn.setText(R.string.record);
share_btn.setEnabled(true);
play_btn.setEnabled(true);
artwork_btn.setEnabled(true);
}
}
});
play_btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
play_btn.setEnabled(false);
record_btn.setEnabled(false);
share_btn.setEnabled(false);
play(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mediaPlayer) {
play_btn.setEnabled(true);
record_btn.setEnabled(true);
share_btn.setEnabled(true);
}
});
}
});
share_btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
shareSound();
}
});
artwork_btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivityForResult(new Intent(Intent.ACTION_GET_CONTENT).setType("image/*"), PICK_ARTWORK);
}
});
if (!isCompatibleSoundCloudInstalled(this)) {
showDialog(DIALOG_NOT_INSTALLED);
}
}
private void play(MediaPlayer.OnCompletionListener onCompletion) {
MediaPlayer player = new MediaPlayer();
try {
player.setDataSource(RECORDING.getAbsolutePath());
player.prepare();
player.setOnCompletionListener(onCompletion);
player.start();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
// the actual sharing happens here
private void shareSound() {
Intent intent = new Intent("com.soundcloud.android.SHARE")
.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(RECORDING))
// here you can set metadata for the track to be uploaded
.putExtra("com.soundcloud.android.extra.title", "SoundCloud Android Intent Demo upload")
.putExtra("com.soundcloud.android.extra.where", "Somewhere")
.putExtra("com.soundcloud.android.extra.description", "This is a demo track.")
.putExtra("com.soundcloud.android.extra.public", true)
.putExtra("com.soundcloud.android.extra.tags", new String[] {
"demo",
"post lolcat bluez",
"soundcloud:created-with-client-id="+CLIENT_ID
})
.putExtra("com.soundcloud.android.extra.genre", "Easy Listening")
.putExtra("com.soundcloud.android.extra.location", getLocation());
// attach artwork if user has picked one
if (mArtwork != null) {
intent.putExtra("com.soundcloud.android.extra.artwork", Uri.fromFile(mArtwork));
}
try {
startActivityForResult(intent, SHARE_SOUND);
} catch (ActivityNotFoundException notFound) {
// use doesn't have SoundCloud app installed, show a dialog box
showDialog(DIALOG_NOT_INSTALLED);
}
}
#Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case SHARE_SOUND:
// callback gets executed when the SoundCloud app returns
if (resultCode == RESULT_OK) {
Toast.makeText(this, R.string.shared_ok, Toast.LENGTH_SHORT).show();
} else {
// canceled
Toast.makeText(this, R.string.shared_canceled, Toast.LENGTH_SHORT).show();
}
break;
case PICK_ARTWORK:
if (resultCode == RESULT_OK) {
mArtwork = getFromMediaUri(getContentResolver(), data.getData());
}
break;
}
}
private MediaRecorder getRecorder(File path, boolean useAAC) {
MediaRecorder recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
if (useAAC) {
recorder.setAudioSamplingRate(44100);
recorder.setAudioEncodingBitRate(96000);
recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
} else {
// older version of Android, use crappy sounding voice codec
recorder.setAudioSamplingRate(8000);
recorder.setAudioEncodingBitRate(12200);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
}
recorder.setOutputFile(path.getAbsolutePath());
try {
recorder.prepare();
} catch (IOException e) {
throw new RuntimeException(e);
}
return recorder;
}
// just get the last known location from the passive provider - not terribly
// accurate but it's a demo app.
private Location getLocation() {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
return locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
}
#Override public Record getLastNonConfigurationInstance() {
return (Record) super.getLastNonConfigurationInstance();
}
#Override public Record onRetainNonConfigurationInstance() {
return this;
}
// Helper method to get file from a content uri
private static File getFromMediaUri(ContentResolver resolver, Uri uri) {
if ("file".equals(uri.getScheme())) {
return new File(uri.getPath());
} else if ("content".equals(uri.getScheme())) {
String[] filePathColumn = {MediaStore.MediaColumns.DATA};
Cursor cursor = resolver.query(uri, filePathColumn, null, null, null);
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
return new File(filePath);
}
} finally {
cursor.close();
}
}
}
return null;
}
private static boolean isCompatibleSoundCloudInstalled(Context context) {
try {
PackageInfo info = context.getPackageManager()
.getPackageInfo("com.soundcloud.android",
PackageManager.GET_META_DATA);
// intent sharing only got introduced with version 22
return info != null && info.versionCode >= 22;
} catch (PackageManager.NameNotFoundException e) {
// not installed at all
return false;
}
}
#Override
protected Dialog onCreateDialog(int id, Bundle data) {
if (DIALOG_NOT_INSTALLED == id) {
return new AlertDialog.Builder(this)
.setTitle(R.string.sc_app_not_found)
.setMessage(R.string.sc_app_not_found_message)
.setPositiveButton(android.R.string.yes, new Dialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent market = new Intent(Intent.ACTION_VIEW, MARKET_URI);
startActivity(market);
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}).create();
} else {
return null;
}
}
}
knowing the url of the sound, you need to do the following:
resolve the URL in order to get the soundcloud API URL using Resolve endpoint
load the tracks API URL to get track representation in json or xml
initialise audio object and set the audio source to the value of stream_url property of track representation
The particular implementation varies depending on the libraries you use etc. But you'll definitely need to use HTTP requests, JSON parser and an audio object.

Categories

Resources