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.
Related
I'm new in android develop and I'm developing an app that transmit/receive data to a BLE module via Uart service.
With smartphone android 5.x.x the app works fine, it connects with the hardware and receive/transmit data.
With smartphone android 7.x.x the app doesn't connects.
Below you can see a snippet of MainActivity.java:
private final BroadcastReceiver UARTStatusChangeReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
final Intent mIntent = intent;
//*********************//
if (action.equals(UartService.ACTION_GATT_CONNECTED)) {
runOnUiThread(new Runnable() {
public void run() {
Log.d(TAG, "HW_CONNECT_MSG");
DisconnectButton.setEnabled(true);
DeviceInfo.setText("Device Information:");
DeviceName.setText(mDevice.getName() + " - Connected");
mState = UART_PROFILE_CONNECTED;
isConnected = true;
if(isConnected) {
//Serial protocol to send command on MCU
Connectcmd[0] = (byte) STX;
Connectcmd[1] = (byte) 0x02;
Connectcmd[2] = (byte) 0x43; // 'C';
Connectcmd[3] = (byte) 0x54; // 'T'
Connectcmd[4] = (byte) ETX;
try {
//send data to UART service
SendData(Connectcmd);
sleep(500); // wait 500ms to send data
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new Handler().postDelayed(mUpdateTimeTask, 2000);
}
else
{
isConnected = false;
}
}
});
}
It's seem that when SendData, the GATT operation is not yet finished. Smartphone show the message "Device doesn't support UART over BLE. Disconnecting..." due to action.equals(UartService.DEVICE_DOES_NOT_SUPPORT_BLE_UART).
If I delete the if(isConnected)...else... statement also smartphone with android 7.x.x will connects.
My question is what's happen and how can I resolve this issue?
My goal is to send a command to hardware via BLE so when the mcu is connected, a buzzer make a sound.
Thanks for help….
EDIT
Below you can find the whole MainActivity:
public class MainActivity extends Activity implements RadioGroup.OnCheckedChangeListener {
public static final String TAG = "DEBUG ";
public static final String DEV_NAME_FILTER = "";
private static final int REQUEST_SELECT_DEVICE = 1;
private static final int REQUEST_ENABLE_BT = 2;
private static final int UART_PROFILE_READY = 10;
private static final int UART_PROFILE_CONNECTED = 20;
public static final int UART_PROFILE_DISCONNECTED = 21;
private static final int STATE_OFF = 10;
private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
TextView mRemoteRssiVal;
RadioGroup mRg;
private int mState = UART_PROFILE_DISCONNECTED;
private static UartService mService = null;
private static BluetoothDevice mDevice = null;
private BluetoothAdapter mBtAdapter = null;
private ListView messageListView;
private ArrayAdapter<String> listAdapter;
private Button SelectButton, DisconnectButton;
private EditText edtMessage;
private static Context context;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
private static TextView DeviceInfo;
private static TextView DeviceName;
private static TextView Manufacturer;
public static boolean isConnected;
public static boolean isSetting;
public static boolean isReading;
public static boolean isManual;
public static boolean isFunctional;
public static boolean isBootloader;
public static byte[] SettingValues;
public static byte[] ReadingValues;
public static byte[] ManualValues;
public static byte[] FunctionalValues;
private static byte[] Connectcmd = new byte[5];
public static int STX = 0x3E; // '>'
public static int ETX = 0x23; // '#'
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DeviceInfo = (TextView) findViewById(R.id.deviceInfo);
DeviceName = (TextView) findViewById(R.id.deviceName);
Manufacturer= (TextView) findViewById(R.id.manufacturer);
isConnected = false;
isSetting = false;
isReading = false;
isManual = false;
isFunctional = false;
isBootloader = false;
context = this;
//Enable location
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// Android M Permission check
if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("This app needs location access");
builder.setMessage("Please grant location access so this app can detect beacons.");
builder.setPositiveButton(android.R.string.ok, null);
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
#TargetApi(Build.VERSION_CODES.M)
public void onDismiss(DialogInterface dialog) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
}
});
builder.show();
}
}
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBtAdapter == null) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
SelectButton = (Button) findViewById(R.id.button);
DisconnectButton = (Button) findViewById(R.id.disconnect);
DisconnectButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Serial protocol to send command on MCU
Connectcmd[0] = (byte) STX;
Connectcmd[1] = (byte) 0x02;
Connectcmd[2] = (byte) 0x44; // 'D';
Connectcmd[3] = (byte) 0x43; // 'C'
Connectcmd[4] = (byte) ETX;
try {
//send data to Banner service
SendData(Connectcmd);
sleep(500); // Wait 500ms to send data
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
MainActivity.disconnected();
setContentView(R.layout.activity_main);
finish();
} catch (Exception e) {
Log.e(TAG, "Disconnect error");
}
}
});
// Handle Select device button
SelectButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!mBtAdapter.isEnabled()) {
Log.i(TAG, "onClick - BT not enabled yet");
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
} else {
if (SelectButton.getText().equals("SELECT CELU")) {
//Connect button pressed, open DeviceListActivity class, with popup windows that scan for devices
Log.i(TAG, "Push button CONNECT");
Intent newIntent = new Intent(context, DeviceListActivity.class);
((Activity) context).startActivityForResult(newIntent, MainActivity.REQUEST_SELECT_DEVICE);
} else {
//Disconnect button pressed
disconnected();
}
}
}
});
// Set initial UI state
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
//UART service connected/disconnected
private ServiceConnection mServiceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder rawBinder) {
mService = ((UartService.LocalBinder) rawBinder).getService();
Log.d(TAG, "onServiceConnected mService= " + mService);
if (!mService.initialize()) {
Log.e(TAG, "Unable to initialize Bluetooth");
finish();
}
}
public void onServiceDisconnected(ComponentName classname) {
//// mService.disconnect(mDevice);
mService = null;
}
};
private Handler mHandler = new Handler() {
#Override
//Handler events that received from UART service
public void handleMessage(Message msg) {
}
};
private final BroadcastReceiver UARTStatusChangeReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
final Intent mIntent = intent;
//*********************//
if (action.equals(UartService.ACTION_GATT_CONNECTED)) {
runOnUiThread(new Runnable() {
public void run() {
String currentDateTimeString = DateFormat.getTimeInstance().format(new Date());
Log.d(TAG, "CELU_CONNECT_MSG");
//btnConnectDisconnect.setText("Disconnect");
//edtMessage.setEnabled(true);
DisconnectButton.setEnabled(true);
DeviceInfo.setText("Device Information:");
DeviceName.setText(mDevice.getName() + " - Connected");
mState = UART_PROFILE_CONNECTED;
isConnected = true;
//IF COMMENTED THE APP CONNECTS!!!!!!!!!!!!!!!!!!
//ELSE IF NOT COMMENTED THE APP NEVER CONNECTS
/*if(isConnected) {
//Serial protocol to send command on MCU
Connectcmd[0] = (byte) STX;
Connectcmd[1] = (byte) 0x02;
Connectcmd[2] = (byte) 0x43; // 'C';
Connectcmd[3] = (byte) 0x54; // 'T'
Connectcmd[4] = (byte) ETX;
try {
//send data to UART service
SendData(Connectcmd);
sleep(500); // Wait 500ms to send data
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new Handler().postDelayed(mUpdateTimeTask, 2000);
}
else
{
isConnected = false;
}*/
new Handler().postDelayed(mUpdateTimeTask, 2000);
}
});
}
//*********************//
if (action.equals(UartService.ACTION_GATT_DISCONNECTED)) {
runOnUiThread(new Runnable() {
public void run() {
Log.d(TAG, "HW_DISCONNECT_MSG");
DisconnectButton.setEnabled(false);
DeviceName.setText("Not Connected");
mState = UART_PROFILE_DISCONNECTED;
mService.close();
//setUiState();
}
});
}
//Enable notifivcation on UART service//
if (action.equals(UartService.ACTION_GATT_SERVICES_DISCOVERED)) {
mService.enableTXNotification();
}
//*********************//
if (action.equals(UartService.ACTION_DATA_AVAILABLE)) {
final byte[] txValue = intent.getByteArrayExtra(UartService.EXTRA_DATA);
try {
ParsingPacket(txValue);
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
//*********************//
if (action.equals(UartService.DEVICE_DOES_NOT_SUPPORT_BLE_UART)) {
showMessage("Device doesn't support UART over BLE Celu . Disconnecting");
mService.disconnect();
}
}
};
private static void ParsingPacket(byte[] packet) throws Exception {
if (packet.length == 0) {
// received empty packet
isConnected = false;
isSetting = false;
isReading = false;
isManual = false;
isFunctional = false;
isBootloader = false;
}
if(isSetting){
isSetting = false;
SettingValues = packet.clone();
String text = new String(SettingValues, "UTF-8");
Log.d(TAG, text);
}
if(isReading){
ReadingValues= packet;
ReadActivity.updateMeasure(ReadingValues);
//ReadActivity.addData(packet);
//String text = new String(ReadingValues, "UTF-8");
Log.d("Length ", String.format("%02d", (int) ReadingValues.length));
for(int i=0; i<ReadingValues.length; i++) {
String text = String.format("%02x", (int) ReadingValues[i]);
Log.d(TAG, text);
}
}
if(isManual){
isManual = false;
ManualValues = packet.clone();
String text = new String(ManualValues, "UTF-8");
Log.d(TAG, text);
}
if(isFunctional){
isFunctional = false;
FunctionalValues = packet.clone();
String text = new String(FunctionalValues, "UTF-8");
Log.d(TAG, text);
}
if(isBootloader){
isBootloader = false;
// do samething
}
}
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
if(DeviceName.getText()!="Not Connected") {
Intent connectedIntent = new Intent(getApplicationContext(), MenuActivity.class); //new Intent("com.antertech.mybleapplication.MenuActivity");
startActivity(connectedIntent);
}
}
};
private void service_init() {
Intent bindIntent = new Intent(this, UartService.class);
bindService(bindIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
LocalBroadcastManager.getInstance(this).registerReceiver(UARTStatusChangeReceiver, makeGattUpdateIntentFilter());
}
private static IntentFilter makeGattUpdateIntentFilter() {
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(UartService.ACTION_GATT_CONNECTED);
intentFilter.addAction(UartService.ACTION_GATT_DISCONNECTED);
intentFilter.addAction(UartService.ACTION_GATT_SERVICES_DISCOVERED);
intentFilter.addAction(UartService.ACTION_DATA_AVAILABLE);
intentFilter.addAction(UartService.DEVICE_DOES_NOT_SUPPORT_BLE_UART);
return intentFilter;
}
#Override
public void onStart() {
super.onStart();// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy()");
try {
LocalBroadcastManager.getInstance(this).unregisterReceiver(UARTStatusChangeReceiver);
} catch (Exception ignore) {
Log.e(TAG, ignore.toString());
}
unbindService(mServiceConnection);
mService.stopSelf();
mService = null;
}
#Override
protected void onStop() {
Log.d(TAG, "onStop");
super.onStop();// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
AppIndex.AppIndexApi.end(client, getIndexApiAction());
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.disconnect();
}
#Override
protected void onPause() {
Log.d(TAG, "onPause");
super.onPause();
}
#Override
protected void onRestart() {
super.onRestart();
Log.d(TAG, "onRestart");
}
#Override
public void onResume() {
super.onResume();
Log.d(TAG, "onResume");
if (!mBtAdapter.isEnabled()) {
Log.i(TAG, "onResume - BT not enabled yet");
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_SELECT_DEVICE:
//When the DeviceListActivity return, with the selected device address
if (resultCode == Activity.RESULT_OK && data != null) {
String deviceAddress = data.getStringExtra(BluetoothDevice.EXTRA_DEVICE);
mDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(deviceAddress);
Log.d(TAG, "... onActivityResultdevice.address==" + mDevice + " mserviceValue " + mService);
mService.connect(deviceAddress);
//setContentView(R.layout.activity_setting);
((TextView) findViewById(R.id.deviceName)).setText(mDevice.getName() + " - Connecting...");
}
break;
case REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
Toast.makeText(this, "Bluetooth has turned on ", Toast.LENGTH_SHORT).show();
} else {
// User did not enable Bluetooth or an error occurred
Log.d(TAG, "BT not enabled");
Toast.makeText(this, "Problem in BT Turning ON ", Toast.LENGTH_SHORT).show();
finish();
}
break;
default:
Log.e(TAG, "wrong request code");
break;
}
}
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
}
public static void SendData(byte[] text) {
mService.writeRXCharacteristic(text);
Log.i(TAG, "Message send to Target");
}
public static void disconnected() {
if (mDevice != null) {
mService.disconnect();
Log.i(TAG, "Push Button DISCONNECT");
}
}
private void showMessage(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
#Override
public void onBackPressed() {
if (mState == UART_PROFILE_CONNECTED) {
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
showMessage("CELU TPE running in background.\n Disconnect to exit");
} else {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(R.string.popup_title)
.setMessage(R.string.popup_message)
.setPositiveButton(R.string.popup_yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton(R.string.popup_no, null)
.show();
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[],
int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_COARSE_LOCATION: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "coarse location permission granted");
} else {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Functionality limited");
builder.setMessage("Since location access has not been granted, this app will not be able to discover beacons when in the background.");
builder.setPositiveButton(android.R.string.ok, null);
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
}
});
builder.show();
}
return;
}
}
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Main Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
}
I have some problem with printing image to AGPtEK 58mm Mini Bluetooth Pocket POS Thermal Receipt Printer. I am trying to convert webview content into image (this is working fine) and after that I want to print it with this printer but it prints only solid black background. Here is my code:
public class PrintDemo extends Activity {
private static final int REQUEST_ENABLE_BT = 2;
private static final int REQUEST_CONNECT_DEVICE = 1;
private static final int PERMISSIONS_REQUEST_BLUETOOTH = 1;
private static final String TAG_REQUEST_PERMISSION = "Request permission";
private static final int PERMISSIONS_REQUEST_INTERNET = 0;
private static final int PERMISSIONS_REQUEST_BT_ADMIN = 2;
private static final int PERMISSIONS_REQUEST_LOCATION = 3;
private static final String WEB_SITE = "Remembered Web Site";
private static final String IS_CHECKED = "Check box";
#Bind(R.id.btn_search)
Button btnSearch;
#Bind(R.id.btn_print)
Button btnSendDraw;
#Bind(R.id.btn_open)
Button btnSend;
#Bind(R.id.btn_close)
Button btnClose;
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case BluetoothService.MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case BluetoothService.STATE_CONNECTED:
Toast.makeText(getApplicationContext(), "Connect successful",
Toast.LENGTH_SHORT).show();
btnClose.setEnabled(true);
btnSend.setEnabled(true);
btnSendDraw.setEnabled(true);
break;
case BluetoothService.STATE_CONNECTING:
Log.d("State", "Connecting...");
break;
case BluetoothService.STATE_LISTEN:
case BluetoothService.STATE_NONE:
Log.d("State", "Not found");
break;
}
break;
case BluetoothService.MESSAGE_CONNECTION_LOST:
Toast.makeText(getApplicationContext(), "Device connection was lost",
Toast.LENGTH_SHORT).show();
btnClose.setEnabled(false);
btnSend.setEnabled(true);
btnSendDraw.setEnabled(false);
break;
case BluetoothService.MESSAGE_UNABLE_CONNECT:
Toast.makeText(getApplicationContext(), "Unable to connect device",
Toast.LENGTH_SHORT).show();
break;
}
}
};
String path;
File dir;
File file;
#Bind(R.id.check_box)
CheckBox checkBox;
#Bind(R.id.txt_content)
EditText edtContext;
#Bind(R.id.web_view)
WebView webView;
BluetoothService mService;
BluetoothDevice con_dev;
private SharedPreferences sharedPref;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fabric.with(this, new Crashlytics());
setContentView(R.layout.main);
ButterKnife.bind(this);
mService = new BluetoothService(this, mHandler);
if (!mService.isAvailable()) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
}
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDefaultTextEncodingName("utf-8");
webView.setWebViewClient(new WebViewClient() {
#SuppressLint("SdCardPath")
#Override
public void onPageFinished(final WebView view, String url) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
siteToImage(view);
}
}, 5000);
}
});
sharedPref = this.getPreferences(Context.MODE_PRIVATE);
checkPermissions();
}
private void siteToImage(WebView view) {
Picture picture = view.capturePicture();
Bitmap b = Bitmap.createBitmap(
picture.getWidth(), picture.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
picture.draw(c);
FileOutputStream fos;
try {
path = Environment.getExternalStorageDirectory().toString();
dir = new File(path, "/PrintDemo/media/img/");
if (!dir.isDirectory()) {
dir.mkdirs();
}
String arquivo = "darf_" + System.currentTimeMillis() + ".jpg";
file = new File(dir, arquivo);
fos = new FileOutputStream(file);
String imagePath = file.getAbsolutePath();
//scan the image so show up in album
MediaScannerConnection.scanFile(PrintDemo.this, new String[]{imagePath},
null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
});
if (fos != null) {
b.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void setRememberedWeb() {
if (checkBox.isChecked()) {
String rememberedWeb = sharedPref.getString(WEB_SITE, "");
if (!rememberedWeb.equals("")) {
edtContext.setText(rememberedWeb);
}
}
}
#Override
protected void onPause() {
super.onPause();
saveState(checkBox.isChecked());
}
#Override
protected void onResume() {
super.onResume();
checkBox.setChecked(load());
setRememberedWeb();
}
private void saveState(boolean isChecked) {
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean(IS_CHECKED, isChecked);
if (isChecked) {
editor.putString(WEB_SITE, edtContext.getText().toString());
} else {
editor.putString(WEB_SITE, getString(R.string.txt_content));
}
editor.apply();
}
private boolean load() {
return sharedPref.getBoolean(IS_CHECKED, false);
}
private boolean checkPermissions() {
int permissionCheck =
ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH);
int permissionInternet =
ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET);
int permissionBTAdmin =
ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_ADMIN);
int permissionLocation =
ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION);
if (permissionCheck == PackageManager.PERMISSION_DENIED) {
edtContext.setText(R.string.no_bluetooth_permissions);
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.BLUETOOTH)) {
Toast.makeText(PrintDemo.this, TAG_REQUEST_PERMISSION, Toast.LENGTH_SHORT).show();
} else {
requestBTPermission();
}
return false;
} else if (permissionInternet == PackageManager.PERMISSION_DENIED) {
edtContext.setText(R.string.no_internet_permissions);
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.INTERNET)) {
Toast.makeText(PrintDemo.this, TAG_REQUEST_PERMISSION, Toast.LENGTH_SHORT).show();
} else {
requestInternetPermission();
}
return false;
} else if (permissionBTAdmin == PackageManager.PERMISSION_DENIED) {
edtContext.setText(R.string.no_bt_admin_permissions);
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.INTERNET)) {
Toast.makeText(PrintDemo.this, TAG_REQUEST_PERMISSION, Toast.LENGTH_SHORT).show();
} else {
requestBTAdminPermission();
}
return false;
} else if (permissionLocation == PackageManager.PERMISSION_DENIED) {
edtContext.setText(R.string.no_location_permissions);
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_COARSE_LOCATION)) {
Toast.makeText(PrintDemo.this, TAG_REQUEST_PERMISSION, Toast.LENGTH_SHORT).show();
} else {
requestLocationPermission();
}
return false;
} else {
return true;
}
}
private void requestLocationPermission() {
ActivityCompat
.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
PERMISSIONS_REQUEST_LOCATION);
}
private void requestBTAdminPermission() {
ActivityCompat
.requestPermissions(this, new String[]{Manifest.permission.BLUETOOTH_ADMIN},
PERMISSIONS_REQUEST_BT_ADMIN);
}
private void requestInternetPermission() {
ActivityCompat
.requestPermissions(this, new String[]{Manifest.permission.INTERNET},
PERMISSIONS_REQUEST_INTERNET);
}
private void requestBTPermission() {
ActivityCompat
.requestPermissions(this, new String[]{Manifest.permission.BLUETOOTH},
PERMISSIONS_REQUEST_BLUETOOTH);
}
#Override
public void onStart() {
super.onStart();
if (!mService.isBTopen()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}
try {
btnSendDraw = (Button) this.findViewById(R.id.btn_print);
btnSendDraw.setOnClickListener(new ClickEvent());
btnSearch = (Button) this.findViewById(R.id.btn_search);
btnSearch.setOnClickListener(new ClickEvent());
btnSend = (Button) this.findViewById(R.id.btn_open);
btnSend.setOnClickListener(new ClickEvent());
btnClose = (Button) this.findViewById(R.id.btn_close);
btnClose.setOnClickListener(new ClickEvent());
edtContext = (EditText) findViewById(R.id.txt_content);
btnClose.setEnabled(false);
btnSend.setEnabled(true);
btnSendDraw.setEnabled(false);
} catch (Exception ex) {
Log.e("TAG", ex.getMessage());
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mService != null)
mService.stop();
mService = null;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_ENABLE_BT:
if (resultCode == Activity.RESULT_OK) {
Toast.makeText(this, "Bluetooth open successful", Toast.LENGTH_LONG).show();
} else {
finish();
}
break;
case REQUEST_CONNECT_DEVICE:
if (resultCode == Activity.RESULT_OK) {
String address = data.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
con_dev = mService.getDevByMac(address);
mService.connect(con_dev);
}
break;
}
}
#SuppressLint("SdCardPath")
private void printImage() {
byte[] sendData;
PrintPic pg = new PrintPic();
pg.initCanvas(384);
pg.initPaint();
pg.drawImage(0, 0, file.getPath());
sendData = pg.printDraw();
mService.write(sendData);
}
public void downloadContent() {
if (!edtContext.getText().toString().equals("") && !edtContext.getText().toString().equals("https://")) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(edtContext.getText().toString())
.build();
HttpService service = retrofit.create(HttpService.class);
Call<ResponseBody> result = service.getContent();
result.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Response<ResponseBody> response) {
try {
if (response.body() != null) {
String summary = response.body().string();
webView.loadData(summary, "text/html; charset=utf-8", null);
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable t) {
}
});
}
}
public interface HttpService {
#GET("/")
Call<ResponseBody> getContent();
}
class ClickEvent implements View.OnClickListener {
public void onClick(View v) {
if (v == btnSearch) {
Intent serverIntent = new Intent(PrintDemo.this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
} else if (v == btnSend) {
downloadContent();
} else if (v == btnClose) {
mService.stop();
} else if (v == btnSendDraw) {
printImage();
}
}
}
}
The result is almost what I want you can see by yourself, but the printed image is not clear:
I fixed it guys, this was the problem, the method siteToImage(). Here are the changes I hope it will helps someone:
private void siteToImage() {
webView.measure(View.MeasureSpec.makeMeasureSpec(
View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
webView.setDrawingCacheEnabled(true);
webView.buildDrawingCache();
Bitmap b = Bitmap.createBitmap(webView.getMeasuredWidth(),
webView.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
Paint paint = new Paint();
int iHeight = b.getHeight();
c.drawBitmap(b, 0, iHeight, paint);
webView.draw(c);
FileOutputStream fos;
try {
path = Environment.getExternalStorageDirectory().toString();
dir = new File(path, "/PrintDemo/media/img/");
if (!dir.isDirectory()) {
dir.mkdirs();
}
String arquivo = "darf_" + System.currentTimeMillis() + ".jpg";
file = new File(dir, arquivo);
fos = new FileOutputStream(file);
String imagePath = file.getAbsolutePath();
//scan the image so show up in album
MediaScannerConnection.scanFile(PrintDemo.this, new String[]{imagePath},
null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
});
b.compress(Bitmap.CompressFormat.PNG, 50, fos);
fos.flush();
fos.close();
b.recycle();
} catch (Exception e) {
e.printStackTrace();
}
}
I am developing an audio recorder with Sony Smart Eyeglass, but it does not work well.
My application records just a voice from phone microphone, not from Smart Eyeglass microphone.
I'd like to record a voice just only from Smart Eyeglass microphone.
Any ideas?
Here is my code.
public class AudioRecordControl extends ControlExtension {
private final AudioManager _audioManager;
private final File _file;
private SmartEyeglassControlUtils _util;
private static final int SMARTEYEGLASS_API_VERSION = 1;
private MediaRecorder _recorder;
private MediaPlayer _player;
enum State {
STOP,
RECORDING,
PLAYING,
}
private State _state;
public AudioRecordControl(Context context, String hostAppPackageName) {
super(context, hostAppPackageName);
_util = new SmartEyeglassControlUtils(hostAppPackageName, new SmartEyeglassEventListener() {
#Override
public void onDialogClosed(int code) {
super.onDialogClosed(code);
doNextAction(code);
showCurrentLayout();
}
});
_util.setRequiredApiVersion(SMARTEYEGLASS_API_VERSION);
_util.activate(context);
_audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
_audioManager.setMode(AudioManager.MODE_IN_CALL);
_audioManager.startBluetoothSco();
_state = State.STOP;
File directoryPath = Environment.getExternalStoragePublicDirectory("AudioRecord");
if (!directoryPath.exists()) {
if (!directoryPath.mkdirs()) {
Log.e(Constants.LOG_TAG, "failed to create directory '" + directoryPath.toString() + "'");
}
}
_file = new File(directoryPath, "record.3gp");
showCurrentLayout();
}
private void showCurrentLayout() {
showLayout(R.layout.layout, null);
switch (_state) {
case STOP:
String[] buttons;
if (_file.exists()) {
buttons = new String[]{
mContext.getString(R.string.record),
mContext.getString(R.string.play)};
} else {
buttons = new String[]{mContext.getString(R.string.record)};
}
_util.showDialogMessage(
mContext.getString(R.string.title),
mContext.getString(R.string.choose_one), buttons);
break;
case RECORDING:
_util.showDialogMessage(
mContext.getString(R.string.stop_recording),
com.sony.smarteyeglass.SmartEyeglassControl.Intents.DIALOG_MODE_OK);
break;
case PLAYING:
_util.showDialogMessage(
mContext.getString(R.string.stop_playing),
com.sony.smarteyeglass.SmartEyeglassControl.Intents.DIALOG_MODE_OK);
break;
default:
break;
}
}
private void doNextAction(int code) {
if (code == -1) {
stopRequest();
}
showLayout(R.layout.layout, null);
switch (_state) {
case STOP:
if (code == 0) {
Log.d(Constants.LOG_TAG, "start recording");
try {
_startRecording();
} catch (IOException e) {
Log.e(Constants.LOG_TAG, "failed to record", e);
_util.showDialogMessage(
mContext.getString(R.string.failed_to_record),
SmartEyeglassControl.Intents.DIALOG_MODE_TIMEOUT);
_recorder = null;
return;
}
_state = State.RECORDING;
} else if (code == 1) {
Log.d(Constants.LOG_TAG, "start playing");
try {
_play();
} catch (IOException e) {
Log.e(Constants.LOG_TAG, "failed to play", e);
_util.showDialogMessage(
mContext.getString(R.string.failed_to_pla),
SmartEyeglassControl.Intents.DIALOG_MODE_TIMEOUT);
_player = null;
return;
}
_state = State.PLAYING;
} else {
stopRequest();
}
break;
case RECORDING:
Log.d(Constants.LOG_TAG, "stop recording");
_stopRecord();
_state = State.STOP;
break;
case PLAYING:
Log.d(Constants.LOG_TAG, "stop playing");
_stopPlay();
_state = State.STOP;
break;
default:
_state = State.STOP;
break;
}
}
private void _startRecording() throws IOException {
if (_recorder == null) {
_recorder = new MediaRecorder();
_recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
_recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
_recorder.setOutputFile(String.valueOf(_file));
_recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
_recorder.prepare();
_recorder.start();
}
}
private void _stopRecord() {
if (_recorder != null) {
_recorder.stop();
_recorder.reset();
_recorder.release();
_recorder = null;
}
}
private void _play() throws IOException {
if (_player == null) {
_player = new MediaPlayer();
_player.setDataSource(String.valueOf(_file));
_player.prepare();
_player.start();
}
}
private void _stopPlay() {
if (_player != null) {
_player.stop();
_player.reset();
_player.release();
_player= null;
}
}
#Override
public void onResume() {
showCurrentLayout();
}
#Override
public void onTap(int action, long timeStamp) {
super.onTap(action, timeStamp);
showCurrentLayout();
}
#Override
public void onDestroy() {
Log.d(Constants.LOG_TAG, "Control On Desuptroy");
_util.deactivate();
_audioManager.setMode(AudioManager.MODE_NORMAL);
_audioManager.stopBluetoothSco();
}
}
Some phones require an extra method call after setMode:
private AudioManager m_amAudioManager;
m_amAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
m_amAudioManager.setMode(AudioManager.MODE_IN_CALL);
m_amAudioManager.setSpeakerphoneOn(false);
To learn more about rest of the operation, there is a guide on Audio I/O with SmartEyeglass:
https://developer.sony.com/develop/wearables/smarteyeglass-sdk/guides/use-bluetooth-for-audio-io/
Would you put your recording code in the Activity and test without using the eyeglass first?
As you are using the phone's capability only, it should work if you can record from microphone in Activity alone. Please ensure you have added uses-permission tag in AndroidManifest.xml
I am android developer and want to create a android apps.In this apps ,it needed to show the android default ringtone list.But i can not show it.How to get the android default ringtone list .
Please help to me.
I have upvote Yuichi's answer but it did not completely work for me. For each ringtone I was getting same URI (different title thought). Following code worked for me -
public void listRingtones() {
RingtoneManager manager = new RingtoneManager(this);
manager.setType(RingtoneManager.TYPE_RINGTONE);
Cursor cursor = manager.getCursor();
while (cursor.moveToNext()) {
String title = cursor.getString(RingtoneManager.TITLE_COLUMN_INDEX);
Uri ringtoneURI = manager.getRingtoneUri(cursor.getPosition());
// Do something with the title and the URI of ringtone
}
}
You can see the working app on playstore.
This question/answer should provide what you're after: How to bring up list of available notification sounds on Android
You'll just need to swap out the RingtoneManager.TYPE_NOTIFICATION for RingtoneManager.TYPE_RINGTONE
You can get the list of Ringtones using RingtoneManager
public void listRingtones() {
RingtoneManager manager = new RingtoneManager(this);
manager.setType(RingtoneManager.TYPE_RINGTONE);
Cursor cursor = manager.getCursor();
while (cursor.moveToNext()) {
String title = cursor.getString(RingtoneManager.TITLE_COLUMN_INDEX);
String uri = cursor.getString(RingtoneManager.URI_COLUMN_INDEX);
// Do something with the title and the URI of ringtone
}
}
Get a List of All ringTones with default ringtones in a list :
public static Map<String, Uri> getRingtones(Activity activity) {
RingtoneManager manager = new RingtoneManager(activity);
manager.setType(RingtoneManager.TYPE_RINGTONE);
Cursor cursor = manager.getCursor();
Map<String, Uri> list = new LinkedHashMap<>();
String title = "Set to Default";
Uri defaultRingtoneUri = RingtoneManager.getActualDefaultRingtoneUri(activity, RingtoneManager.TYPE_RINGTONE);
list.put(title, defaultRingtoneUri); // first add the default, to get back if select another
while (cursor.moveToNext()) {
String notificationTitle = cursor.getString(RingtoneManager.TITLE_COLUMN_INDEX);
Uri notificationUri = manager.getRingtoneUri(cursor.getPosition());
list.put(notificationTitle, notificationUri);
}
return list;
}
Then Create a dialog for select :
public static void getRingtonesDialog(Activity activity, Collection<String> items, int selected, DialogInterface.OnClickListener itemClickListener, DialogInterface.OnClickListener okClickListener, final DialogInterface.OnClickListener cancelClickListener) {
AlertDialog.Builder builderSingle = new AlertDialog.Builder(activity);
builderSingle.setTitle("Select Ringtone");
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(activity, android.R.layout.select_dialog_singlechoice);
arrayAdapter.addAll(items);
builderSingle.setNegativeButton(android.R.string.cancel, cancelClickListener);
builderSingle.setPositiveButton(android.R.string.ok, okClickListener);
builderSingle.setSingleChoiceItems(arrayAdapter, selected, itemClickListener);
builderSingle.setCancelable(false);
builderSingle.show();
}
Then Select And Play them to test : (Here AppSettings settings is SharedPreferences in your App ) :
Map<String, Uri> mRingtonesMap;
private Uri mLastSelectedRingtone = null;
private String mLastSelectedRingtoneName = "Default";
private MediaPlayer mMediaPlayer;
AppSettings settings;
TextView mRingtone ;
in Oncreate :
mRingtone = (TextView)findViewById(R.id.mRingtone);
settings = AppSettings.getInstance(this);
mRingtone.setText(getString(R.string.set_alarm_select_ringtone,
settings.getString(AppSettings.Key.SELECTED_RINGTONE_NAME, mLastSelectedRingtoneName)));
mRingtone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setupRingtoneSelection();
}
});
Then :
private void setupRingtoneSelection() {
mRingtonesMap = AlarmUtils.getRingtones(SelectionsActivity.this);
mRingtone.setText(getString(R.string.set_alarm_select_ringtone,
settings.getString(AppSettings.Key.SELECTED_RINGTONE_NAME, mLastSelectedRingtoneName)));
mRingtone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final List<String> ringtoneKeys = new ArrayList<>(mRingtonesMap.keySet());
String ringtoneUri = settings.getString(AppSettings.Key.SELECTED_RINGTONE, "");
int selected = -1;
for (int i = 0; i < ringtoneKeys.size(); i++) {
String ring = ringtoneKeys.get(i);
if (mRingtonesMap.get(ring).toString().equalsIgnoreCase(ringtoneUri)) {
selected = i;
break;
}
}
AlarmUtils.getRingtonesDialog(SelectionsActivity.this, ringtoneKeys, selected, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) { //item selected
String name = ringtoneKeys.get(which);
mLastSelectedRingtoneName = name;
mLastSelectedRingtone = mRingtonesMap.get(name);
try {
if (mMediaPlayer == null) {
mMediaPlayer = new MediaPlayer();
} else {
mMediaPlayer.stop();
mMediaPlayer.reset();
}
mMediaPlayer.setDataSource(SelectionsActivity.this, mLastSelectedRingtone);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setLooping(false);
mMediaPlayer.prepare();
mMediaPlayer.start();
} catch (IOException ioe) {
//do nothing
}
}
}, new DialogInterface.OnClickListener() { //ok
#Override
public void onClick(DialogInterface dialog, int which) {
if (mMediaPlayer != null) {
mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
}
settings.set(AppSettings.Key.SELECTED_RINGTONE, mLastSelectedRingtone.toString());
settings.set(AppSettings.Key.SELECTED_RINGTONE_NAME, mLastSelectedRingtoneName);
//Update the textview
mRingtone.setText(getString(R.string.set_alarm_select_ringtone,
settings.getString(AppSettings.Key.SELECTED_RINGTONE_NAME, mLastSelectedRingtoneName)));
dialog.dismiss();
}
}, new DialogInterface.OnClickListener() { //cancel
#Override
public void onClick(DialogInterface dialog, int which) {
if (mMediaPlayer != null) {
mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
}
dialog.dismiss();
}
});
}
});
}
#Override
protected void onDestroy() {
if (mMediaPlayer != null) {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.stop();
}
mMediaPlayer.release();
mMediaPlayer = null;
}
mRingtone.setOnClickListener(null);
super.onDestroy();
}
You can set and change ringtone, and after you want, can get back to default.
I am making an app in whic h i hava to you stream you tube video and show in my app but i am getting error message an error occured during retrieval of video.My code snippet is as follows:
public class Rads extends Activity {
public static final String SCHEME_YOUTUBE_VIDEO = "ytv";
public static final String SCHEME_YOUTUBE_PLAYLIST = "ytpl";
static final String YOUTUBE_VIDEO_INFORMATION_URL = "http://www.youtube.com/get_video_info?&video_id=";
static final String YOUTUBE_PLAYLIST_ATOM_FEED_URL = "http://gdata.youtube.com/feeds/api/playlists/";
protected ProgressBar mProgressBar;
protected TextView mProgressMessage;
protected VideoView mVideoView;
public final static String MSG_INIT = "com.keyes.video.msg.init";
protected String mMsgInit = "Initializing";
public final static String MSG_DETECT = "com.keyes.video.msg.detect";
protected String mMsgDetect = "Detecting Bandwidth";
public final static String MSG_PLAYLIST = "com.keyes.video.msg.playlist";
protected String mMsgPlaylist = "Determining Latest Video in YouTube Playlist";
public final static String MSG_TOKEN = "com.keyes.video.msg.token";
protected String mMsgToken = "Retrieving YouTube Video Token";
public final static String MSG_LO_BAND = "com.keyes.video.msg.loband";
protected String mMsgLowBand = "Buffering Low-bandwidth Video";
public final static String MSG_HI_BAND = "com.keyes.video.msg.hiband";
protected String mMsgHiBand = "Buffering High-bandwidth Video";
public final static String MSG_ERROR_TITLE = "com.keyes.video.msg.error.title";
protected String mMsgErrorTitle = "Communications Error";
public final static String MSG_ERROR_MSG = "com.keyes.video.msg.error.msg";
protected String mMsgError = "An error occurred during the retrieval of the video. This could be due to network issues or YouTube protocols. Please try again later.";
/** Background task on which all of the interaction with YouTube is done */
protected QueryYouTubeTask mQueryYouTubeTask;
protected String mVideoId = null;
#Override
protected void onCreate(Bundle pSavedInstanceState) {
super.onCreate(pSavedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
// create the layout of the view
setupView();
// determine the messages to be displayed as the view loads the video
extractMessages();
// set the flag to keep the screen ON so that the video can play without the screen being turned off
getWindow().setFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
mProgressBar.bringToFront();
mProgressBar.setVisibility(View.VISIBLE);
mProgressMessage.setText(mMsgInit);
// extract the playlist or video id from the intent that started this video
Uri lVideoIdUri = this.getIntent().getData();
if(lVideoIdUri == null){
Log.i(this.getClass().getSimpleName(), "No video ID was specified in the intent. Closing video activity.");
finish();
}
String lVideoSchemeStr = lVideoIdUri.getScheme();
String lVideoIdStr = lVideoIdUri.getEncodedSchemeSpecificPart();
if(lVideoIdStr == null){
Log.i(this.getClass().getSimpleName(), "No video ID was specified in the intent. Closing video activity.");
finish();
}
if(lVideoIdStr.startsWith("//")){
if(lVideoIdStr.length() > 2){
lVideoIdStr = lVideoIdStr.substring(2);
} else {
Log.i(this.getClass().getSimpleName(), "No video ID was specified in the intent. Closing video activity.");
finish();
}
}
///////////////////
// extract either a video id or a playlist id, depending on the uri scheme
YouTubeId lYouTubeId = null;
if(lVideoSchemeStr != null && lVideoSchemeStr.equalsIgnoreCase(SCHEME_YOUTUBE_PLAYLIST)){
lYouTubeId = new PlaylistId(lVideoIdStr);
}
else if(lVideoSchemeStr != null && lVideoSchemeStr.equalsIgnoreCase(SCHEME_YOUTUBE_VIDEO)){
lYouTubeId = new VideoId(lVideoIdStr);
}
if(lYouTubeId == null){
Log.i(this.getClass().getSimpleName(), "Unable to extract video ID from the intent. Closing video activity.");
finish();
}
mQueryYouTubeTask = (QueryYouTubeTask) new QueryYouTubeTask().execute(lYouTubeId);
}
/**
* Determine the messages to display during video load and initialization.
*/
private void extractMessages() {
Intent lInvokingIntent = getIntent();
String lMsgInit = lInvokingIntent.getStringExtra(MSG_INIT);
if(lMsgInit != null){
mMsgInit = lMsgInit;
}
String lMsgDetect = lInvokingIntent.getStringExtra(MSG_DETECT);
if(lMsgDetect != null){
mMsgDetect = lMsgDetect;
}
String lMsgPlaylist = lInvokingIntent.getStringExtra(MSG_PLAYLIST);
if(lMsgPlaylist != null){
mMsgPlaylist = lMsgPlaylist;
}
String lMsgToken = lInvokingIntent.getStringExtra(MSG_TOKEN);
if(lMsgToken != null){
mMsgToken = lMsgToken;
}
String lMsgLoBand = lInvokingIntent.getStringExtra(MSG_LO_BAND);
if(lMsgLoBand != null){
mMsgLowBand = lMsgLoBand;
}
String lMsgHiBand = lInvokingIntent.getStringExtra(MSG_HI_BAND);
if(lMsgHiBand != null){
mMsgHiBand = lMsgHiBand;
}
String lMsgErrTitle = lInvokingIntent.getStringExtra(MSG_ERROR_TITLE);
if(lMsgErrTitle != null){
mMsgErrorTitle = lMsgErrTitle;
}
String lMsgErrMsg = lInvokingIntent.getStringExtra(MSG_ERROR_MSG);
if(lMsgErrMsg != null){
mMsgError = lMsgErrMsg;
}
}
/**
* Create the view in which the video will be rendered.
*/
private void setupView() {
LinearLayout lLinLayout = new LinearLayout(this);
lLinLayout.setId(1);
lLinLayout.setOrientation(LinearLayout.VERTICAL);
lLinLayout.setGravity(Gravity.CENTER);
lLinLayout.setBackgroundColor(Color.BLACK);
LayoutParams lLinLayoutParms = new LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT);
lLinLayout.setLayoutParams(lLinLayoutParms);
this.setContentView(lLinLayout);
RelativeLayout lRelLayout = new RelativeLayout(this);
lRelLayout.setId(2);
lRelLayout.setGravity(Gravity.CENTER);
lRelLayout.setBackgroundColor(Color.BLACK);
android.widget.RelativeLayout.LayoutParams lRelLayoutParms = new android.widget.RelativeLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT);
lRelLayout.setLayoutParams(lRelLayoutParms);
lLinLayout.addView(lRelLayout);
mVideoView = new VideoView(this);
mVideoView.setId(3);
android.widget.RelativeLayout.LayoutParams lVidViewLayoutParams = new android.widget.RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lVidViewLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
mVideoView.setLayoutParams(lVidViewLayoutParams);
lRelLayout.addView(mVideoView);
mProgressBar = new ProgressBar(this);
mProgressBar.setIndeterminate(true);
mProgressBar.setVisibility(View.VISIBLE);
mProgressBar.setEnabled(true);
mProgressBar.setId(4);
android.widget.RelativeLayout.LayoutParams lProgressBarLayoutParms = new android.widget.RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lProgressBarLayoutParms.addRule(RelativeLayout.CENTER_IN_PARENT);
mProgressBar.setLayoutParams(lProgressBarLayoutParms);
lRelLayout.addView(mProgressBar);
mProgressMessage = new TextView(this);
mProgressMessage.setId(5);
android.widget.RelativeLayout.LayoutParams lProgressMsgLayoutParms = new android.widget.RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lProgressMsgLayoutParms.addRule(RelativeLayout.CENTER_HORIZONTAL);
lProgressMsgLayoutParms.addRule(RelativeLayout.BELOW, 4);
mProgressMessage.setLayoutParams(lProgressMsgLayoutParms);
mProgressMessage.setTextColor(Color.LTGRAY);
mProgressMessage.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
mProgressMessage.setText("...");
lRelLayout.addView(mProgressMessage);
}
#Override
protected void onDestroy() {
super.onDestroy();
YouTubeUtility.markVideoAsViewed(this, mVideoId);
if(mQueryYouTubeTask != null){
mQueryYouTubeTask.cancel(true);
}
if(mVideoView != null){
mVideoView.stopPlayback();
}
// clear the flag that keeps the screen ON
getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
this.mQueryYouTubeTask = null;
this.mVideoView = null;
}
public void updateProgress(String pProgressMsg){
try {
mProgressMessage.setText(pProgressMsg);
} catch(Exception e) {
Log.e(this.getClass().getSimpleName(), "Error updating video status!", e);
}
}
private class ProgressUpdateInfo {
public String mMsg;
public ProgressUpdateInfo(String pMsg){
mMsg = pMsg;
}
}
/**
* Task to figure out details by calling out to YouTube GData API. We only use public methods that
* don't require authentication.
*
*/
private class QueryYouTubeTask extends AsyncTask<YouTubeId, ProgressUpdateInfo, Uri> {
private boolean mShowedError = false;
#Override
protected Uri doInBackground(YouTubeId... pParams) {
String lUriStr = null;
String lYouTubeFmtQuality = "17"; // 3gpp medium quality, which should be fast enough to view over EDGE connection
String lYouTubeVideoId = null;
if(isCancelled())
return null;
try {
publishProgress(new ProgressUpdateInfo(mMsgDetect));
WifiManager lWifiManager = (WifiManager) Rads.this.getSystemService(Context.WIFI_SERVICE);
TelephonyManager lTelephonyManager = (TelephonyManager) Rads.this.getSystemService(Context.TELEPHONY_SERVICE);
////////////////////////////
// if we have a fast connection (wifi or 3g), then we'll get a high quality YouTube video
if( (lWifiManager.isWifiEnabled() && lWifiManager.getConnectionInfo() != null && lWifiManager.getConnectionInfo().getIpAddress() != 0) ||
( (lTelephonyManager.getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS ||
/* icky... using literals to make backwards compatible with 1.5 and 1.6 */
lTelephonyManager.getNetworkType() == 9 /*HSUPA*/ ||
lTelephonyManager.getNetworkType() == 10 /*HSPA*/ ||
lTelephonyManager.getNetworkType() == 8 /*HSDPA*/ ||
lTelephonyManager.getNetworkType() == 5 /*EVDO_0*/ ||
lTelephonyManager.getNetworkType() == 6 /*EVDO A*/)
&& lTelephonyManager.getDataState() == TelephonyManager.DATA_CONNECTED)
){
lYouTubeFmtQuality = "18";
}
///////////////////////////////////
// if the intent is to show a playlist, get the latest video id from the playlist, otherwise the video
// id was explicitly declared.
if(pParams[0] instanceof PlaylistId){
publishProgress(new ProgressUpdateInfo(mMsgPlaylist));
lYouTubeVideoId = YouTubeUtility.queryLatestPlaylistVideo((PlaylistId) pParams[0]);
}
else if(pParams[0] instanceof VideoId){
lYouTubeVideoId = pParams[0].getId();
}
mVideoId = lYouTubeVideoId;
publishProgress(new ProgressUpdateInfo(mMsgToken));
if(isCancelled())
return null;
////////////////////////////////////
// calculate the actual URL of the video, encoded with proper YouTube token
lUriStr = YouTubeUtility.calculateYouTubeUrl(lYouTubeFmtQuality, true, lYouTubeVideoId);
if(isCancelled())
return null;
if(lYouTubeFmtQuality.equals("17")){
publishProgress(new ProgressUpdateInfo(mMsgLowBand));
} else {
publishProgress(new ProgressUpdateInfo(mMsgHiBand));
}
} catch(Exception e) {
Log.e(this.getClass().getSimpleName(), "Error occurred while retrieving information from YouTube.", e);
}
if(lUriStr != null){
return Uri.parse(lUriStr);
} else {
return null;
}
}
#Override
protected void onPostExecute(Uri pResult) {
super.onPostExecute(pResult);
try {
if(isCancelled())
return;
if(pResult == null){
throw new RuntimeException("Invalid NULL Url.");
}
mVideoView.setVideoURI(pResult);
if(isCancelled())
return;
// TODO: add listeners for finish of video
mVideoView.setOnCompletionListener(new OnCompletionListener(){
public void onCompletion(MediaPlayer pMp) {
if(isCancelled())
return;
Rads.this.finish();
}
});
if(isCancelled())
return;
final MediaController lMediaController = new MediaController(Rads.this);
mVideoView.setMediaController(lMediaController);
lMediaController.show(0);
//mVideoView.setKeepScreenOn(true);
mVideoView.setOnPreparedListener( new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer pMp) {
if(isCancelled())
return;
Rads.this.mProgressBar.setVisibility(View.GONE);
Rads.this.mProgressMessage.setVisibility(View.GONE);
}
});
if(isCancelled())
return;
mVideoView.requestFocus();
mVideoView.start();
} catch(Exception e){
Log.e(this.getClass().getSimpleName(), "Error playing video!", e);
if(!mShowedError){
showErrorAlert();
}
}
}
private void showErrorAlert() {
try {
Builder lBuilder = new AlertDialog.Builder(Rads.this);
lBuilder.setTitle(mMsgErrorTitle);
lBuilder.setCancelable(false);
lBuilder.setMessage(mMsgError);
lBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface pDialog, int pWhich) {
Rads.this.finish();
}
});
AlertDialog lDialog = lBuilder.create();
lDialog.show();
} catch(Exception e){
Log.e(this.getClass().getSimpleName(), "Problem showing error dialog.", e);
}
}
#Override
protected void onProgressUpdate(ProgressUpdateInfo... pValues) {
super.onProgressUpdate(pValues);
Rads.this.updateProgress(pValues[0].mMsg);
}
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
}
}