Android Twilio audio client not able to make any connection - android

I'm trying to work with Twilio Client SDK for android with very less experience with Twilio service.
All I want to achieve here is to make voice call from an app to registered numbers using the Twilio number.
Here's my client side implementation
public class AudioCallActivity extends AppCompatActivity implements Twilio.InitListener, View.OnClickListener {
private static final int MIC_PERMISSION_REQUEST_CODE = 1;
private CoordinatorLayout coordinatorLayout;
private String contact;
private String name;
private String profile_pic;
private ImageView profile;
private TextView user;
private TextView timer;
private Device device;
private Connection connection;
private String TAG = AudioCallActivity.this.getClass().getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio_call);
if (ActivityCompat.checkSelfPermission(AudioCallActivity.this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(AudioCallActivity.this, Manifest.permission.MODIFY_AUDIO_SETTINGS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(AudioCallActivity.this,
new String[]{Manifest.permission.RECORD_AUDIO}, MIC_PERMISSION_REQUEST_CODE);
ActivityCompat.requestPermissions(AudioCallActivity.this,
new String[]{Manifest.permission.MODIFY_AUDIO_SETTINGS}, 2);
}
if (getIntent() != null) {
contact = getIntent().getStringExtra("contact").trim();
patient_name = getIntent().getStringExtra("name");
profile_pic = getIntent().getStringExtra("profile_pic").trim();
loadUI();
} else AudioCallActivity.this.finish();
if (!Twilio.isInitialized())
Twilio.initialize(getApplicationContext(), this);
coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorlayout);
}
private void loadUI() {
profile = (ImageView) findViewById(R.id.profile_pic);
((Button) findViewById(R.id.end_call)).setOnClickListener(this);
user = (TextView) findViewById(R.id.userName);
timer = (TextView) findViewById(R.id.timer);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.end_call:
if (connection != null)
connection.disconnect();
device.release();
AudioCallActivity.this.finish();
break;
}
}
#Override
public void onInitialized() {
user.setText("Calling " + name);
new GlideOperations(getApplicationContext(), profile).glideImages(profile_pic);
NetworkManager.getInstance(getApplicationContext()).StringRequest(TAG, new HashMap<String, String>(), AppConfig.CAPABILITY_TOKEN, new VolleyResponse<String>() {
#Override
public void success(String response) {
if (response != null && !response.isEmpty()) {
device = Twilio.createDevice(response, null);
HashMap<String, String> param = new HashMap<>();
param.put("PhoneNumber", "XXXXXXXXXX");
if (connection == null) {
connection = device.connect(param, new ConnectionListener() {
#Override
public void onConnecting(Connection connection) {
Log.d(TAG, "Connecting...");
}
#Override
public void onConnected(Connection connection) {
timer.setVisibility(View.VISIBLE);
Log.d(TAG, "Connected");
}
#Override
public void onDisconnected(Connection connection) {
Log.d(TAG, "Disconnected");
}
#Override
public void onDisconnected(Connection connection, int i, String s) {
}
});
}
}
}
#Override
public void error(VolleyError error) {
Log.d(TAG, "VOLLEY ERROR");
}
}, Request.Method.POST);
}
#Override
public void onError(Exception e) {
Toast.makeText(getApplicationContext(), "ERROR", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == MIC_PERMISSION_REQUEST_CODE && resultCode != RESULT_OK) {
Snackbar snackbar = Snackbar.make(coordinatorLayout, "Lyphe Call need the following permission to operate.", Snackbar.LENGTH_LONG);
snackbar.show();
}
}
}
In my TwiMl application I have the following voice request url {xyz.com}/outgoing
Here's the server side script for the same
require_once dirname(__FILE__) . "/include/config.php";
header('Content-type: text/xml');
$callerId = TWILO_NUMBER;
$number = "XXXXXXX";
if (isset($_POST['PhoneNumber'])) {
$number = htmlspecialchars($_POST['PhoneNumber']);
}
if (preg_match("/^[\d\+\-\(\) ]+$/", $number)) {
$numberOrClient = "<Number>" . $number . "</Number>";
} else {
$numberOrClient = "<Client>" . $number . "</Client>";
}
?>
<Response>
<Dial callerId="<?php echo $callerId ?>">
<?php echo $numberOrClient ?>
</Dial>
</Response>
Please let me know where I'm making the mistake. TIA

Related

App cannot send and retrieve files from server via php mysql

I have a page in my app with similar codes with different values and they send info to my PHP MySQL just fine. On the other hand, this page in my app cannot send the files and giving me an error message:
E/Volley: [258] BasicNetwork.performRequest: Unexpected response code 406
for http://applybpojobs.com/widevalueappfiles/server/api/addvehicle.php
I have already tried numerous solutions on web and this site to no avail. Can anyone help me figure this out?
Here is my java:
public class Addvehicle extends AppCompatActivity {
private static final String TAG = Addvehicle.class.getSimpleName();
private EditText plate_number, vin, car_make, car_model, car_year, displacement,
fuel_type, transmission, mileage, owner_name, address, phone_number,
email_adress, facebook;
private TextView btnCreate;
private TextView btnClose;
private ImageView upload_car, preview;
private int GALLERY = 1, CAMERA = 2;
private static String URL_ADD_VEHICLE = "http://abcde/server/api/addvehicle.php";
//private static String URL_VEHICLE_IMAGE = "http://abcde/server/api/addvehicle.php";
private Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addvehicle);
requestMultiplePermissions();
/*EditText Area*/
plate_number = findViewById(R.id.plate_number);
vin = findViewById(R.id.vin);
car_make = findViewById(R.id.car_make);
car_model = findViewById(R.id.car_model);
car_year = findViewById(R.id.car_year);
displacement = findViewById(R.id.displacement);
fuel_type = findViewById(R.id.fuel_type);
transmission = findViewById(R.id.transmission);
mileage = findViewById(R.id.mileage);
owner_name = findViewById(R.id.owner_name);
address = findViewById(R.id.address);
phone_number = findViewById(R.id.phone_number);
email_adress = findViewById(R.id.email_adress);
facebook = findViewById(R.id.facebook);
/*TextView Area*/
btnClose = findViewById(R.id.btnClose);
btnCreate = findViewById(R.id.btnCreate);
/*Button Area*/
upload_car = findViewById(R.id.iv);
preview = findViewById(R.id.iv);
upload_car.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showPictureDialog();
}
});
btnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Addvehicle.this, Home.class));
}
});
btnCreate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showLoader();
addVehicle(getStringImage(bitmap));
}
});
}
private void showPictureDialog(){
AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
pictureDialog.setTitle("Select Action");
String[] pictureDialogItems = {
"Select photo from gallery",
"Capture photo from camera" };
pictureDialog.setItems(pictureDialogItems,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
choosePhotoFromGallary();
break;
case 1:
takePhotoFromCamera();
break;
}
}
});
pictureDialog.show();
}
public void choosePhotoFromGallary() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, GALLERY);
}
private void takePhotoFromCamera() {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == this.RESULT_CANCELED) {
return;
}
if (requestCode == GALLERY) {
if (data != null) {
Uri filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), filePath);
String path = getStringImage(bitmap);
Toast.makeText(Addvehicle.this, "Image Saved!", Toast.LENGTH_SHORT).show();
preview.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(Addvehicle.this, "Failed!", Toast.LENGTH_SHORT).show();
}
addVehicle(getStringImage(bitmap));
}
} else if (requestCode == CAMERA) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
preview.setImageBitmap(thumbnail);
getStringImage(thumbnail);
Toast.makeText(Addvehicle.this, "Image Saved!", Toast.LENGTH_SHORT).show();
}
addVehicle(getStringImage(bitmap));
}
private void addVehicle(final String stringImage) {
final String plate_number = this.plate_number.getText().toString().trim();
final String vin = this.vin.getText().toString().trim();
final String car_make = this.car_make.getText().toString().trim();
final String car_model = this.car_model.getText().toString().trim();
final String car_year = this.car_year.getText().toString().trim();
final String displacement = this.displacement.getText().toString().trim();
final String fuel_type = this.fuel_type.getText().toString().trim();
final String transmission = this.transmission.getText().toString().trim();
final String mileage = this.mileage.getText().toString().trim();
final String owner_name = this.owner_name.getText().toString().trim();
final String address = this.address.getText().toString().trim();
final String phone_number = this.phone_number.getText().toString().trim();
final String email_adress = this.email_adress.getText().toString().trim();
final String facebook = this.facebook.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_ADD_VEHICLE,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i(TAG, response.toString());
try {
JSONObject jsonObject = new JSONObject(response);
String Success = jsonObject.getString("success");
if (Success.equals("1")){
hideLoader();
Toast.makeText(Addvehicle.this,"Vehicle Added Successfully",Toast.LENGTH_SHORT).show();
}else if (Success.equals("0")){
hideLoader();
Toast.makeText(Addvehicle.this,"Vehicle Already Exist",Toast.LENGTH_SHORT).show();
}
}catch (JSONException e){
e.printStackTrace();
hideLoader();
Toast.makeText(Addvehicle.this,"Vehicle Added Error"+e.toString(),Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
Toast.makeText(Addvehicle.this,"Vehicle Added Error"+error.toString(),Toast.LENGTH_SHORT).show();
hideLoader();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError{
Map<String, String> params = new HashMap<>();
params.put("plate_number", plate_number);
params.put("vin", vin);
params.put("car_make", car_make);
params.put("car_model", car_model);
params.put("car_year", car_year);
params.put("displacement", displacement);
params.put("fuel_type", fuel_type);
params.put("transmission", transmission);
params.put("mileage", mileage);
params.put("owner_name", owner_name);
params.put("address", address);
params.put("phone_number", phone_number);
params.put("email_adress", email_adress);
params.put("facebook", facebook);
params.put("photo", stringImage);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
public void showLoader(){
ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Adding Vehicle...");
progressDialog.show();
}
public void hideLoader(){
ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.hide();
}
public String getStringImage(Bitmap bitmap){
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byte[] imageByteArray = byteArrayOutputStream.toByteArray();
String encodedImage = Base64.encodeToString(imageByteArray, Base64.DEFAULT);
return encodedImage;
}
private void requestMultiplePermissions(){
Dexter.withActivity(this)
.withPermissions(
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new MultiplePermissionsListener() {
#Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
// check if all permissions are granted
if (report.areAllPermissionsGranted()) {
Toast.makeText(getApplicationContext(), "All permissions are granted by user!", Toast.LENGTH_SHORT).show();
}
// check for permanent denial of any permission
if (report.isAnyPermissionPermanentlyDenied()) {
// show alert dialog navigating to Settings
//openSettingsDialog();
}
}
#Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
token.continuePermissionRequest();
}
}).
withErrorListener(new PermissionRequestErrorListener() {
#Override
public void onError(DexterError error) {
Toast.makeText(getApplicationContext(), "Some Error! ", Toast.LENGTH_SHORT).show();
}
})
.onSameThread()
.check();
}
This is my server api file (mysqli) which is giving me the error response from logcat with this url : "http://abcde/server/api/addvehicle.php"
error_reporting(E_ALL); ini_set('display_errors', 1);
require '../core/connect.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$plate_number=$_POST['plate_number'];
$vin=$_POST['vin'];
$car_make=$_POST['car_make'];
$car_model=$_POST['car_model'];
$car_year=$_POST['car_year'];
$displacement=$_POST['displacement'];
$fuel_type=$_POST['fuel_type'];
$transmission=$_POST['transmission'];
$mileage=$_POST['mileage'];
$owner_name=$_POST['owner_name'];
$address=$_POST['address'];
$phone_number=$_POST['phone_number'];
$email_adress=$_POST['email_adress'];
$facebook=$_POST['facebook'];
$adddate = date("d/m/Y");
$photo = $_POST['photo'];
$id=uniqid();
$path = "vehicle_upload/$id.jpeg";
$finalpath =
"http://abcde/server/api/addvehicle.php".$path;
$sql1=mysqli_query($connect,"SELECT * FROM _addvehicle WHERE
PlateNumber='$plate_number'");
if (mysqli_num_rows($sql1) > 0) {
$result['success'] = "0";
$result['message'] = "error";
echo json_encode($result);
}else{
$sql = mysqli_query($connect, "INSERT IGNORE INTO
_addvehicle(PlateNumber, Vin, Make, Model, Year, Displacement, FuelType,
Transmission, Mileage, OwnerorCompany, HomeorCompanyAddress, ContactNumber,
EmailAddress, FacebookID, AddDate, vehicleImage)VALUES('$plate_number','$vin','$car_make','$car_model','$car_year','$displacement','$fuel_type','$transmission','$mileage','$owner_name','$address','$phone_number','$email_adress','$facebook','$adddate','$finalpath')");
if ($sql) {
if (file_put_contents($path, base64_decode($photo))) {
$result['success'] = "1";
$result['message'] = "success";
echo json_encode($result);
//mysqli_close($connect);
}
}
}
I am having a hard time identifying what went wrong. Although I am seeing that logcat points me to the php file, it doesn't specifically tell me what to change. This page was working a couple of days ago.

Android client for kurento room

i can connect ios app with kurento room for conference call without any issue but i cannot connect it with android, here i am following tutorial Kurento WebRTC Peer For Android to make android client to connect with kurento room.
Here is the code what i am trying
public class MainActivity extends AppCompatActivity implements
RoomListener,NBMWebRTCPeer.Observer {
private LooperExecutor executor;
private static KurentoRoomAPI kurentoRoomAPI;
private EglBase rootEglBase;
private NBMWebRTCPeer nbmWebRTCPeer;
private SurfaceViewRenderer localView;
private SurfaceViewRenderer remoteView;
private VideoRenderer.Callbacks localRender;
private SessionDescription localSdp;
private SessionDescription remoteSdp;
NBMMediaConfiguration.NBMVideoFormat receiverVideoFormat = new NBMMediaConfiguration.NBMVideoFormat(1280, 720, ImageFormat.YUV_420_888, 30);
NBMMediaConfiguration mediaConfiguration = new NBMMediaConfiguration(NBMMediaConfiguration.NBMRendererType.OPENGLES, NBMMediaConfiguration.NBMAudioCodec.OPUS, 0, NBMMediaConfiguration.NBMVideoCodec.VP8, 0, receiverVideoFormat, NBMMediaConfiguration.NBMCameraPosition.FRONT);
private boolean isMyVideoPublished = false;
private boolean isMyIceCandidateSent = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int hasCameraPermission = checkSelfPermission(Manifest.permission.CAMERA);
List<String> permissions = new ArrayList<String>();
if (hasCameraPermission != PackageManager.PERMISSION_GRANTED) {
permissions.add(Manifest.permission.CAMERA);
}
if (!permissions.isEmpty()) {
requestPermissions(permissions.toArray(new String[permissions.size()]), 111);
}
}
executor = new LooperExecutor();
executor.requestStart();
String wsRoomUri = "wss://172.16.1.9:8443/room";
kurentoRoomAPI = new KurentoRoomAPI(executor, wsRoomUri, this);
kurentoRoomAPI.connectWebSocket();
localView = (SurfaceViewRenderer) findViewById(R.id.gl_surface_local);
remoteView = (SurfaceViewRenderer) findViewById(R.id.gl_surface_remote);
localView.init(EglBase.create().getEglBaseContext(), null);
localView.setZOrderMediaOverlay(true);
localView.setScalingType(RendererCommon.ScalingType.SCALE_ASPECT_FILL);
localView.setMirror(true);
localView.requestLayout();
remoteView.init(EglBase.create().getEglBaseContext(), null);
remoteView.setZOrderMediaOverlay(true);
remoteView.setScalingType(RendererCommon.ScalingType.SCALE_ASPECT_FILL);
remoteView.setMirror(true);
remoteView.requestLayout();
nbmWebRTCPeer = new NBMWebRTCPeer(mediaConfiguration, this, localView, this);
nbmWebRTCPeer.initialize();
//nbmWebRTCPeer.generateOffer("local", true);
//nbmWebRTCPeer.generateOffer("MyRemotePeer", false);
}
#Override
public void onRoomResponse(RoomResponse response) {
Log.d("onRoomResponse", "******** onRoomResponse : "+response.toString());
if (response.getId() == 123) {
Log.d("onRoomResponse", "Successfully connected to the room!");
nbmWebRTCPeer.generateOffer("Jeeva", true);
//kurentoRoomAPI.sendMessage("112233", "Jeeva Moto", "Hello room!", 125);
} else if (response.getId() == 125) {
Log.d("onRoomResponse", "The server received my message!");
} else if (response.getId() == 126) {
}else if (response.getId() == 129) {
}
}
#Override
public void onRoomError(RoomError error) {
Log.d("onRoomError", "******** onRoomError : "+error.toString());
}
#Override
public void onRoomNotification(RoomNotification notification) {
if(notification.getMethod().equals(RoomListener.METHOD_SEND_MESSAGE)) {
final String username = notification.getParam("user").toString();
final String message = notification.getParam("message").toString();
Log.d("onRoomNotification", "Oh boy! " + username + " sent me a message: " + message);
}
Log.d("onRoomNotification", "******** RoomNotification : " + notification);
if(notification.getMethod().equals("iceCandidate"))
{
Map<String, Object> map = notification.getParams();
Log.d("onRoomNotification", "******** Map RoomNotification : " + map);
String sdpMid = map.get("sdpMid").toString();
int sdpMLineIndex = Integer.valueOf(map.get("sdpMLineIndex").toString());
String sdp = map.get("candidate").toString();
IceCandidate ic = new IceCandidate(sdpMid, sdpMLineIndex, sdp);
nbmWebRTCPeer.addRemoteIceCandidate(ic, "remote");
}
}
#Override
public void onRoomConnected() {
Log.d("onRoomConnected","******** Called");
kurentoRoomAPI.sendJoinRoom("Jeeva", "112233", true, 123);
}
#Override
public void onRoomDisconnected() {
}
#Override
public void onInitialize() {
}
#Override
public void onLocalSdpOfferGenerated(SessionDescription localSdpOffer, NBMPeerConnection connection) {
Log.d("onLclSdpOfrGen","******** localSdpOffer : "+localSdpOffer.description+" connection : "+connection.getConnectionId());
if (!isMyVideoPublished) {
kurentoRoomAPI.sendPublishVideo(localSdpOffer.description,false,129);
//String username = "qwerty";
//kurentoRoomAPI.sendReceiveVideoFrom(username, "webcam", localSdpOffer.description, 129);
isMyVideoPublished = true;
}else {
String username = "qwerty";
kurentoRoomAPI.sendReceiveVideoFrom(username, "webcam", localSdpOffer.description, 129);
}
}
#Override
public void onLocalSdpAnswerGenerated(SessionDescription localSdpAnswer, NBMPeerConnection connection) {
Log.d("onLclSdpAnsGen","******** localSdpAnswer : "+localSdpAnswer.description+" connection : "+connection.getConnectionId());
}
#Override
public void onIceCandidate(IceCandidate iceCandidate, NBMPeerConnection nbmPeerConnection) {
Log.d("onIceCandidate", "******** iceCandidate : " + iceCandidate.sdp + " nbmPeerConnection : " + nbmPeerConnection.getConnectionId());
if (!isMyIceCandidateSent){
isMyIceCandidateSent = true;
kurentoRoomAPI.sendOnIceCandidate("Jeeva", iceCandidate.sdp, iceCandidate.sdpMid, Integer.toString(iceCandidate.sdpMLineIndex),129);
} else {
kurentoRoomAPI.sendOnIceCandidate("qwerty", iceCandidate.sdp,
iceCandidate.sdpMid, Integer.toString(iceCandidate.sdpMLineIndex), 129);
nbmWebRTCPeer.addRemoteIceCandidate(iceCandidate, iceCandidate.sdp);
}
}
#Override
public void onIceStatusChanged(PeerConnection.IceConnectionState state, NBMPeerConnection connection) {
Log.d("onIceStatusChanged","******** state : "+state+" connection : "+connection);
}
#Override
public void onRemoteStreamAdded(MediaStream stream, NBMPeerConnection connection) {
Log.d("onRemoteStreamAdded","******** stream : "+stream+" connection : "+connection);
nbmWebRTCPeer.attachRendererToRemoteStream(remoteView, stream);
}
#Override
public void onRemoteStreamRemoved(MediaStream stream, NBMPeerConnection connection) {
Log.d("onRemoteStreamRemoved","******** stream : "+stream+" connection : "+connection);
}
#Override
public void onPeerConnectionError(String error) {
Log.d("onPeerConnectionError","******** error : "+error);
}
#Override
public void onDataChannel(DataChannel dataChannel, NBMPeerConnection connection) {
Log.d("onDataChannel","******** dataChannel : "+dataChannel+" connection : "+connection);
}
#Override
public void onBufferedAmountChange(long l, NBMPeerConnection connection, DataChannel channel) {
Log.d("onBufferedAmountChange","******** channel : "+channel+" connection : "+connection);
}
#Override
public void onStateChange(NBMPeerConnection connection, DataChannel channel) {
Log.d("onStateChange","******** channel : "+channel+" connection : "+connection);
}
#Override
public void onMessage(DataChannel.Buffer buffer, NBMPeerConnection connection, DataChannel channel) {
Log.d("onMessage","******** channel : "+channel+" buffer : "+buffer+" connection : "+connection);
}}
I am looking for any working sample for android client which connects kurento room for conference call.
Kurento also has completed Android client with simple UI.
It allows to connect to "kurento-room" server using of their KurentoAPI.
It has only 2p2, but contain implementation of all needed signaling, so it may be a good start point.
More details are there.

Google Drive API for android requestSync always returns "sync request limit exceeded"

I am using google drive api for android to access files in google drive. When a new file is uploaded it takes anywhere from 3 to 15 minutes for the file to be accessible by my app. I tried to add requestSync to occasionally force a sync but every time I run it I get "sync request limit exceeded". Is there something that can be causing me to hit the limit already, or is there a different issue?
RequestSync portion of code:
Drive.DriveApi.requestSync(getGoogleApiClient()).setResultCallback(syncCallback);
final private ResultCallback<com.google.android.gms.common.api.Status> syncCallback = new ResultCallback<com.google.android.gms.common.api.Status>() {
#Override
public void onResult(Status status) {
if (!status.getStatus().isSuccess()) {
showMessage(status.toString());
} else {
showMessage("updated");
}
}
};
Full class:
public class SD_UAV_TEST_RESULTS extends SD_UAV_TEST_MAIN {
TextView numberOfCows_text,picsProcessed_text;
public static int previousCount = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sd__uav__test__results);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
numberOfCows_text = (TextView) findViewById(R.id.numberOfCows);
picsProcessed_text = (TextView) findViewById(R.id.picsProcessed);
}
public void refreshResults(View view)
{
getContnets();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
String temp = data.getStringExtra("parse");
String[] lines = temp.split(":");
int cow_count = 0;
for(int i=0;i<lines.length;i++)
{
cow_count += Integer.parseInt(lines[i].split(",")[1]);
}
numberOfCows_text.setText(Integer.toString(cow_count));
picsProcessed_text.setText(Integer.toString(lines.length));
}
if (requestCode == 8) {
}
}
public void getContnets(){
if(file_id != null) {
Drive.DriveApi.fetchDriveId(getGoogleApiClient(), file_id)
.setResultCallback(idCallback);
}
}
public void parseFileRead(String temp)
{
String[] lines = temp.split(":");
int cow_count = 0;
for(int i=0;i<lines.length;i++)
{
cow_count += Integer.parseInt(lines[i].split(",")[1]);
}
if(lines.length == previousCount)
{
fnfCount = fnfCount + 1;
}
if(fnfCount >= 5)
{
Drive.DriveApi.requestSync(getGoogleApiClient()).setResultCallback(syncCallback);
fnfCount = 0;
}
numberOfCows_text.setText(Integer.toString(cow_count));
picsProcessed_text.setText(Integer.toString(lines.length));
previousCount = lines.length;
}
final private ResultCallback<com.google.android.gms.common.api.Status> syncCallback = new ResultCallback<com.google.android.gms.common.api.Status>() {
#Override
public void onResult(Status status) {
if (!status.getStatus().isSuccess()) {
showMessage(status.toString());
} else {
showMessage("updated");
}
}
};
//----------------------------------------------------------------------------------------------
final private ResultCallback<DriveApi.DriveIdResult> idCallback = new ResultCallback<DriveApi.DriveIdResult>() {
#Override
public void onResult(DriveApi.DriveIdResult result) {
DriveId temp = result.getDriveId();
new RetrieveDriveFileContentsAsyncTask(
SD_UAV_TEST_RESULTS.this).execute(temp);
}
};
final private class RetrieveDriveFileContentsAsyncTask
extends ApiClientAsyncTask<DriveId, Boolean, String> {
public RetrieveDriveFileContentsAsyncTask(Context context) {
super(context);
}
#Override
protected String doInBackgroundConnected(DriveId... params) {
String contents = null;
DriveFile file = params[0].asDriveFile();
DriveApi.DriveContentsResult driveContentsResult =
file.open(getGoogleApiClient(), DriveFile.MODE_READ_ONLY, null).await();
if (!driveContentsResult.getStatus().isSuccess()) {
return null;
}
DriveContents driveContents = driveContentsResult.getDriveContents();
BufferedReader reader = new BufferedReader(
new InputStreamReader(driveContents.getInputStream()));
StringBuilder builder = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
builder.append(line);
}
contents = builder.toString();
} catch (IOException e) {
}
driveContents.discard(getGoogleApiClient());
return contents;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result == null) {
showMessage("Error while reading from the file");
return;
}
parseFileRead(result);
}
}
}
The operation failed because the application attempted the operation too often. As per official DriveApi docs,
In order to avoid excessive load on the device and the server, sync
requests are rate limited. In this case, the operation will fail with
DRIVE_RATE_LIMIT_EXCEEDED status, which indicates that a sync already
happened quite recently so there is no need for another sync. The
operation will succeed when reattempted after a sufficient backoff
duration.

Message keeps failing to send with Sinch

I've been following this tutorial at https://www.sinch.com/tutorials/android-messaging-tutorial-using-sinch-and-parse/#message and I'm having trouble sending the message to another user. When I write a message and send it. I keep getting a toast message that says "Message Failed To Send".
This is my MessageService Activity:
public class MessageService extends Service implements SinchClientListener {
private static final String APP_KEY = "xxxx";
private static final String APP_SECRET = "yyyy";
private static final String ENVIRONMENT = "sandbox.sinch.com";
private final MessageServiceInterface serviceInterface = new MessageServiceInterface();
private SinchClient sinchClient = null;
private MessageClient messageClient = null;
private String currentUserId;
private Intent broadcastIntent = new Intent("com.jordanpeterson.textly.messages.ListUsersActivity");
private LocalBroadcastManager broadCaster;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// get the current user id from parse
currentUserId = ParseUser.getCurrentUser().getObjectId();
if (currentUserId != null && !isSinchClientStarted()) {
startSinchClient(currentUserId);
}
broadCaster = LocalBroadcastManager.getInstance(this);
return super.onStartCommand(intent, flags, startId);
}
private void startSinchClient(String userame) {
sinchClient = Sinch.getSinchClientBuilder().context(this)
.userId(userame).applicationKey(APP_KEY)
.applicationSecret(APP_SECRET).environmentHost(ENVIRONMENT)
.build();
// this client listener requires that you define
// a few methods below
sinchClient.addSinchClientListener(this);
// Messaging is "turned-on", but calling is not
sinchClient.setSupportMessaging(true);
sinchClient.setSupportActiveConnectionInBackground(true);
sinchClient.checkManifest();
sinchClient.start();
}
private boolean isSinchClientStarted() {
return sinchClient != null && sinchClient.isStarted();
}
// The next 5 methods are for the sinch client listener
#Override
public void onClientFailed(SinchClient client, SinchError error) {
broadcastIntent.putExtra("success", false);
broadCaster.sendBroadcast(broadcastIntent);
sinchClient = null;
}
#Override
public void onClientStarted(SinchClient client) {
broadcastIntent.putExtra("success", true);
broadCaster.sendBroadcast(broadcastIntent);
client.startListeningOnActiveConnection();
messageClient = client.getMessageClient();
}
#Override
public void onClientStopped(SinchClient client) {
sinchClient = null;
}
#Override
public void onRegistrationCredentialsRequired(SinchClient client,
ClientRegistration clientRegistration) {
// No code in here yet
}
#Override
public void onLogMessage(int level, String area, String message) {
// No code in here yet either
}
#Override
public IBinder onBind(Intent intent) {
return serviceInterface;
}
public void sendMessage(String recipientUserId, String textBody) {
if (messageClient != null) {
WritableMessage message = new WritableMessage(recipientUserId,
textBody);
messageClient.send(message);
}
}
public void addMessageClientListener(MessageClientListener listener) {
if (messageClient != null) {
messageClient.addMessageClientListener(listener);
}
}
public void removeMessageClientListener(MessageClientListener listener) {
if (messageClient != null) {
messageClient.removeMessageClientListener(listener);
}
}
#Override
public void onDestroy() {
sinchClient.stopListeningOnActiveConnection();
sinchClient.terminate();
}
// Public interface for ListUsersActivity & MessagingActivity
public class MessageServiceInterface extends Binder {
public void sendMessage(String recipientUserId, String textBody) {
MessageService.this.sendMessage(recipientUserId, textBody);
}
public void addMessageClientListener(MessageClientListener listener) {
MessageService.this.addMessageClientListener(listener);
}
public void removeMessageClientListener(MessageClientListener listener) {
MessageService.this.removeMessageClientListener(listener);
}
public boolean isSinchClientStarted() {
return MessageService.this.isSinchClientStarted();
}
}
}
This is my MessagingActivity:
private String mRecipientId;
private EditText mMessageBodyField;
private String mMessageBody;
private MessageService.MessageServiceInterface messageService;
private String mCurrentUserId;
private ServiceConnection serviceConnection = new MyServiceConnection();
private MessageClientListener messageClientListener = new MyMessageClientListener();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.messaging_sinch);
bindService(new Intent(this, MessageService.class), serviceConnection,
BIND_AUTO_CREATE);
// Get RecipientId from the intent
Intent intent = getIntent();
mRecipientId = intent.getStringExtra("RECIPIENT_ID");
mCurrentUserId = ParseUser.getCurrentUser().getObjectId();
mMessageBodyField = (EditText) findViewById(R.id.messageBodyField);
// Listen for a click on the send button
findViewById(R.id.sendButton).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
// Send The Message!
mMessageBody = mMessageBodyField.getText().toString();
if (mMessageBody.isEmpty()) {
Toast.makeText(MessagingActivity.this,
"Please enter a message", Toast.LENGTH_LONG)
.show();
return;
}
messageService.sendMessage(mRecipientId, mMessageBody);
mMessageBodyField.setText("");
}
});
}
// Unbind the service when the activity is destroyed
#Override
protected void onDestroy() {
messageService.removeMessageClientListener(messageClientListener);
unbindService(serviceConnection);
super.onDestroy();
}
private class MyServiceConnection implements ServiceConnection {
#Override
public void onServiceConnected(ComponentName componentName,
IBinder iBinder) {
messageService = (MessageService.MessageServiceInterface) iBinder;
messageService.addMessageClientListener(messageClientListener);
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
messageService = null;
}
}
private class MyMessageClientListener implements MessageClientListener {
#Override
public void onMessageFailed(MessageClient client, Message message,
MessageFailureInfo failureInfo) {
Toast.makeText(MessagingActivity.this, "Message failed to send.",
Toast.LENGTH_LONG).show();
}
#Override
public void onIncomingMessage(MessageClient client, Message message) {
// Display an incoming message
}
#Override
public void onMessageSent(MessageClient client, Message message,
String recipientId) {
// Display the message that was just sent
// Later, I'll show you how to store the
// Message in Parse, so you can retrieve and
// display them every time the conversation is opened
}
#Override
public void onMessageDelivered(MessageClient client,
MessageDeliveryInfo deliveryInfo) {
}
// Don't worry about this right now
#Override
public void onShouldSendPushData(MessageClient client, Message message,
List<PushPair> pushPairs) {
}
}
}
And this is my ListUsersActivity:
public class ListUsersActivity extends Activity {
private String mCurrentUserId;
private ArrayAdapter<String> mNamesArrayAdapter;
private ArrayList<String> mNames;
private ListView mUsersListView;
private Button mLogoutButton;
private ProgressDialog mProgressDialog;
private BroadcastReceiver mReceiver = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_users);
mCurrentUserId = ParseUser.getCurrentUser().getObjectId();
mNames = new ArrayList<String>();
ParseQuery<ParseUser> query = ParseUser.getQuery();
// Don't include yourself!
query.whereNotEqualTo("objectId", mCurrentUserId);
query.findInBackground(new FindCallback<ParseUser>() {
#Override
public void done(List<ParseUser> userList, ParseException e) {
if (e == null) {
for (int i = 0; i < userList.size(); i++) {
mNames.add(userList.get(i).getUsername().toString());
}
mUsersListView = (ListView) findViewById(R.id.usersListView);
mNamesArrayAdapter = new ArrayAdapter<String>(
getApplicationContext(), R.layout.user_list_item,
mNames);
mUsersListView.setAdapter(mNamesArrayAdapter);
mUsersListView
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a,
View v, int i, long l) {
openConversation(mNames, i);
}
private void openConversation(
ArrayList<String> mNames, int pos) {
ParseQuery<ParseUser> query = ParseUser
.getQuery();
query.whereEqualTo("username",
mNames.get(pos));
query.findInBackground(new FindCallback<ParseUser>() {
#Override
public void done(List<ParseUser> user,
ParseException e) {
if (e == null) {
Intent intent = new Intent(ListUsersActivity.this, MessagingActivity.class);
intent.putExtra("RECIPIENT_ID", user.get(0).getObjectId());
startActivity(intent);
} else {
Toast.makeText(
getApplicationContext(),
"Error finding that user!",
Toast.LENGTH_LONG)
.show();
}
}
});
}
});
} else {
Toast.makeText(ListUsersActivity.this,
"Error loading user list", Toast.LENGTH_LONG)
.show();
}
}
});
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setTitle("Loading");
mProgressDialog.setMessage("Please Wait...");
mProgressDialog.show();
// broadcast receiver to listen for the broadcast
// from MessageService
mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Boolean success = intent.getBooleanExtra("success", false);
Toast.makeText(ListUsersActivity.this, "Sinch has started and is working!", Toast.LENGTH_LONG).show();
mProgressDialog.dismiss();
// Show a toast message is the Sinch service failed to start
if (!success) {
Toast.makeText(ListUsersActivity.this,
"Messaging service failed to start",
Toast.LENGTH_LONG).show();
}
}
};
LocalBroadcastManager
.getInstance(this)
.registerReceiver(
mReceiver,
new IntentFilter(
"com.jordanpeterson.textly.messages.ListUsersActivity"));
}
}
Try to print the message error because you may have it for many reasons.
Under onMessageFailed function, add this to see the failure message:
Toast.makeText(MessagingActivity.this,failureInfo.getSinchError().getMessage(), Toast.LENGTH_LONG).show();

Flickr Sign out in Android programmatically

I am getting some issue when image is uploaded to flickr,oath token as well as user credentials get stored in the web browser cache.As a result am not being able to sign out from it.So when I go to flickr to upload my image again,it automatically uploads it rather than opening the login page.Now when I clear all the default browser cookies,then it ask for the login page.Is there any other way to sign out it automatically when I am redirected back to my application.Any kind of support will be appreciated.
Thanks in advance...
try this ,here....,FlickerHelper.java
public final class FlickrHelper {
private static FlickrHelper instance = null;
private static final String API_KEY = ""; //$NON-NLS-1$
public static final String API_SEC = ""; //$NON-NLS-1$
private FlickrHelper() {
}
public static FlickrHelper getInstance() {
if (instance == null) {
instance = new FlickrHelper();
}
return instance;
}
public Flickr getFlickr() {
try {
Flickr f = new Flickr(API_KEY, API_SEC, new REST());
return f;
} catch (ParserConfigurationException e) {
return null;
}
}
public Flickr getFlickrAuthed(String token, String secret) {
Flickr f = getFlickr();
RequestContext requestContext = RequestContext.getRequestContext();
OAuth auth = new OAuth();
auth.setToken(new OAuthToken(token, secret));
requestContext.setOAuth(auth);
return f;
}
public InterestingnessInterface getInterestingInterface() {
Flickr f = getFlickr();
if (f != null) {
return f.getInterestingnessInterface();
} else {
return null;
}
}
public PhotosInterface getPhotosInterface() {
Flickr f = getFlickr();
if (f != null) {
return f.getPhotosInterface();
} else {
return null;
}
}
}
FlickerjActivity.java
public class FlickrjActivity extends Activity {
public static final String CALLBACK_SCHEME = "flickrj-android-sample-oauth"; //$NON-NLS-1$
public static final String PREFS_NAME = "flickrj-android-sample-pref"; //$NON-NLS-1$
public static final String KEY_OAUTH_TOKEN = "flickrj-android-oauthToken"; //$NON-NLS-1$
public static final String KEY_TOKEN_SECRET = "flickrj-android-tokenSecret"; //$NON-NLS-1$
public static final String KEY_USER_NAME = "flickrj-android-userName"; //$NON-NLS-1$
public static final String KEY_USER_ID = "flickrj-android-userId"; //$NON-NLS-1$
String path;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getIntent().getExtras() != null) {
if (getIntent().getExtras().containsKey("flickImagePath")) {
path = getIntent().getStringExtra("flickImagePath");
}
}
new Thread() {
public void run() {
h.post(init);
};
}.start();
}
Handler h = new Handler();
Runnable init = new Runnable() {
#Override
public void run() {
OAuth oauth = getOAuthToken();
if (oauth == null || oauth.getUser() == null) {
OAuthTask task = new OAuthTask(getContext());
task.execute();
} else {
load(oauth);
}
}
};
private void load(OAuth oauth) {
if (oauth != null) {
UploadPhotoTask taskUpload = new UploadPhotoTask(this, new File(
path));
taskUpload.setOnUploadDone(new UploadPhotoTask.onUploadDone() {
#Override
public void onComplete() {
finish();
}
});
taskUpload.execute(oauth);
}
}
#Override
protected void onNewIntent(Intent intent) {
setIntent(intent);
}
#Override
public void onResume() {
super.onResume();
Intent intent = getIntent();
String scheme = intent.getScheme();
OAuth savedToken = getOAuthToken();
if (CALLBACK_SCHEME.equals(scheme)
&& (savedToken == null || savedToken.getUser() == null)) {
Uri uri = intent.getData();
String query = uri.getQuery();
String[] data = query.split("&"); //$NON-NLS-1$
if (data != null && data.length == 2) {
String oauthToken = data[0].substring(data[0].indexOf("=") + 1); //$NON-NLS-1$
String oauthVerifier = data[1]
.substring(data[1].indexOf("=") + 1); //$NON-NLS-1$
OAuth oauth = getOAuthToken();
if (oauth != null && oauth.getToken() != null
&& oauth.getToken().getOauthTokenSecret() != null) {
GetOAuthTokenTask task = new GetOAuthTokenTask(this);
task.execute(oauthToken, oauth.getToken()
.getOauthTokenSecret(), oauthVerifier);
}
}
}
}
public void onOAuthDone(OAuth result) {
if (result == null) {
Toast.makeText(this, "Authorization failed", //$NON-NLS-1$
Toast.LENGTH_LONG).show();
} else {
User user = result.getUser();
OAuthToken token = result.getToken();
if (user == null || user.getId() == null || token == null
|| token.getOauthToken() == null
|| token.getOauthTokenSecret() == null) {
Toast.makeText(this, "Authorization failed", //$NON-NLS-1$
Toast.LENGTH_LONG).show();
return;
}
String message = String
.format(Locale.US,
"Authorization Succeed: user=%s, userId=%s, oauthToken=%s, tokenSecret=%s", //$NON-NLS-1$
user.getUsername(), user.getId(),
token.getOauthToken(), token.getOauthTokenSecret());
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
saveOAuthToken(user.getUsername(), user.getId(),
token.getOauthToken(), token.getOauthTokenSecret());
load(result);
}
}
public OAuth getOAuthToken() {
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
String oauthTokenString = settings.getString(KEY_OAUTH_TOKEN, null);
String tokenSecret = settings.getString(KEY_TOKEN_SECRET, null);
if (oauthTokenString == null && tokenSecret == null) {
// logger.warn("No oauth token retrieved"); //$NON-NLS-1$
return null;
}
OAuth oauth = new OAuth();
String userName = settings.getString(KEY_USER_NAME, null);
String userId = settings.getString(KEY_USER_ID, null);
if (userId != null) {
User user = new User();
user.setUsername(userName);
user.setId(userId);
oauth.setUser(user);
}
OAuthToken oauthToken = new OAuthToken();
oauth.setToken(oauthToken);
oauthToken.setOauthToken(oauthTokenString);
oauthToken.setOauthTokenSecret(tokenSecret);
return oauth;
}
public void saveOAuthToken(String userName, String userId, String token,
String tokenSecret) {
SharedPreferences sp = getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
Editor editor = sp.edit();
editor.putString(KEY_OAUTH_TOKEN, token);
editor.putString(KEY_TOKEN_SECRET, tokenSecret);
editor.putString(KEY_USER_NAME, userName);
editor.putString(KEY_USER_ID, userId);
editor.commit();
}
private Context getContext() {
return this;
}
}
GetAouthToken.java
public class GetOAuthTokenTask extends AsyncTask<String, Integer, OAuth> {
private FlickrjActivity activity;
public GetOAuthTokenTask(FlickrjActivity context) {
this.activity = context;
}
#Override
protected OAuth doInBackground(String... params) {
String oauthToken = params[0];
String oauthTokenSecret = params[1];
String verifier = params[2];
Flickr f = FlickrHelper.getInstance().getFlickr();
OAuthInterface oauthApi = f.getOAuthInterface();
try {
return oauthApi.getAccessToken(oauthToken, oauthTokenSecret,
verifier);
} catch (Exception e) {
return null;
}
}
#Override
protected void onPostExecute(OAuth result) {
if (activity != null) {
activity.onOAuthDone(result);
}
}
}
Oauthtask.java
public class OAuthTask extends AsyncTask<Void, Integer, String> {
private static final Uri OAUTH_CALLBACK_URI = Uri
.parse(FlickrjActivity.CALLBACK_SCHEME + "://oauth"); //$NON-NLS-1$
private Context mContext;
private ProgressDialog mProgressDialog;
public OAuthTask(Context context) {
super();
this.mContext = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = ProgressDialog.show(mContext,
"", "Generating the authorization request..."); //$NON-NLS-1$ //$NON-NLS-2$
mProgressDialog.setCanceledOnTouchOutside(true);
mProgressDialog.setCancelable(true);
mProgressDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dlg) {
OAuthTask.this.cancel(true);
}
});
}
#Override
protected String doInBackground(Void... params) {
try {
Flickr f = FlickrHelper.getInstance().getFlickr();
OAuthToken oauthToken = f.getOAuthInterface().getRequestToken(
OAUTH_CALLBACK_URI.toString());
saveTokenSecrent(oauthToken.getOauthTokenSecret());
URL oauthUrl = f.getOAuthInterface().buildAuthenticationUrl(
Permission.WRITE, oauthToken);
return oauthUrl.toString();
} catch (Exception e) {
return "error:" + e.getMessage(); //$NON-NLS-1$
}
}
private void saveTokenSecrent(String tokenSecret) {
FlickrjActivity act = (FlickrjActivity) mContext;
act.saveOAuthToken(null, null, null, tokenSecret);
}
#Override
protected void onPostExecute(String result) {
if (mProgressDialog != null) {
mProgressDialog.dismiss();
}
if (result != null && !result.startsWith("error")) { //$NON-NLS-1$
mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(result)));
} else {
Toast.makeText(mContext, result, Toast.LENGTH_LONG).show();
}
}
}
uploadphototask.java
public class UploadPhotoTask extends AsyncTask<OAuth, Void, String> {
private final FlickrjActivity flickrjAndroidSampleActivity;
private File file;
public UploadPhotoTask(FlickrjActivity flickrjAndroidSampleActivity,
File file) {
this.flickrjAndroidSampleActivity = flickrjAndroidSampleActivity;
this.file = file;
}
private ProgressDialog mProgressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = ProgressDialog.show(flickrjAndroidSampleActivity,
"", "Uploading..."); //$NON-NLS-1$ //$NON-NLS-2$
mProgressDialog.setCanceledOnTouchOutside(true);
mProgressDialog.setCancelable(true);
mProgressDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dlg) {
UploadPhotoTask.this.cancel(true);
}
});
}
#Override
protected String doInBackground(OAuth... params) {
OAuth oauth = params[0];
OAuthToken token = oauth.getToken();
try {
Flickr f = FlickrHelper.getInstance().getFlickrAuthed(
token.getOauthToken(), token.getOauthTokenSecret());
UploadMetaData uploadMetaData = new UploadMetaData();
uploadMetaData.setTitle("" + file.getName());
return f.getUploader().upload(file.getName(),
new FileInputStream(file), uploadMetaData);
} catch (Exception e) {
Log.e("boom!!", "" + e.toString());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String response) {
if (mProgressDialog != null) {
mProgressDialog.dismiss();
}
if (response != null) {
Log.e("", "" + response);
} else {
}
if (monUploadDone != null) {
monUploadDone.onComplete();
}
Toast.makeText(flickrjAndroidSampleActivity.getApplicationContext(),
response, Toast.LENGTH_SHORT).show();
}
onUploadDone monUploadDone;
public void setOnUploadDone(onUploadDone monUploadDone) {
this.monUploadDone = monUploadDone;
}
public interface onUploadDone {
void onComplete();
}
}
mainactivty.java
public class MainActivity extends Activity {
File fileUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnFlickr = (Button) findViewById(R.id.btnFlickr);
btnFlickr.setOnClickListener(mFlickrClickListener);
Button btnPick = (Button) findViewById(R.id.btnPick);
btnPick.setOnClickListener(mPickClickListener);
}
View.OnClickListener mPickClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivityForResult(intent, 102);
}
};
View.OnClickListener mFlickrClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if (fileUri == null) {
Toast.makeText(getApplicationContext(), "Please pick photo",
Toast.LENGTH_SHORT).show();
return;
}
Intent intent = new Intent(getApplicationContext(),
FlickrjActivity.class);
intent.putExtra("flickImagePath", fileUri.getAbsolutePath());
startActivity(intent);
}
};
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 102) {
if (resultCode == Activity.RESULT_OK) {
Uri tmp_fileUri = data.getData();
((ImageView) findViewById(R.id.imageView1))
.setImageURI(tmp_fileUri);
String selectedImagePath = getPath(tmp_fileUri);
fileUri = new File(selectedImagePath);
Debug.e("", "fileUri : " + fileUri.getAbsolutePath());
}
}
};
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
usercard.java
public class UserCard {
public String name;
public String url;
public int upVotes;
public int downVotes;
}
debug.java
public class Debug {
private static final boolean DEBUG = true;
public static void e(String tag, String msg) {
if (DEBUG) {
Log.e(tag, msg);
}
}public static void i(String tag, String msg) {
if (DEBUG) {
Log.i(tag, msg);
}
}
public static void w(String tag, String msg) {
if (DEBUG) {
Log.w(tag, msg);
}
}
public static void d(String tag, String msg) {
if (DEBUG) {
Log.d(tag, msg);
}
}
}

Categories

Resources