Java android java.util.ConcurrentModificationException - java

I have a service in which I have a AsyncTask
if (s != null) {
if (!MainActivity.photoListSend.isEmpty()) {
if (MainActivity.photoListSend.size() > 0) {
File file = MainActivity.photoListSend.get(0);
if (file.exists())
file.delete();
MainActivity.photoListSend.remove(0);
Gson gson = new Gson();
String jsonCurProduct = gson.toJson(MainActivity.photoListSend);
SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("TAG", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("TAG", jsonCurProduct);
editor.apply();
File imagesFolder = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
assert imagesFolder != null;
}
}
}
On this line :
String jsonCurProduct = gson.toJson(MainActivity.photoListSend);
I have java.util.ConcurrentModificationException
And this is my all class :
ublic class Sendrer extends Service {
public static boolean running = false;
private Timer timer = new Timer();
private SendPhotoTask asyncSender;
private Context context;
private SharedPreferences sp;
private SharedPreferences.Editor editor;
public static String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
#Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
sp = getSharedPreferences("pfref", Activity.MODE_PRIVATE);
editor = sp.edit();
Gson gson = new Gson();
List<File> productFromShared = new ArrayList<>();
SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("TAG", Context.MODE_PRIVATE);
String jsonPreferences = sharedPref.getString("TAG", "");
Type type = new TypeToken<List<File>>() {
}.getType();
productFromShared = gson.fromJson(jsonPreferences, type);
MainActivity.photoListSend = null;
MainActivity.photoListSend = new ArrayList<>();
if (productFromShared != null)
MainActivity.photoListSend.addAll(productFromShared);
Log.e("tworzenie serwisu ", "tworzenie");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("Dziełanie serwisu ", "Dziełanie");
if (!running) {
running = true;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
asyncSender = new SendPhotoTask();
asyncSender.execute();
}
}, 1000 * 60 * 2);
}
return START_STICKY;
}
#Override
public void onDestroy() {
if (running) {
timer.cancel();
asyncSender = new SendPhotoTask();
asyncSender.cancel(true);
running = false;
}
Log.e("service ", "nie działa");
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
public boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
class SendPhotoTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... strings) {
running = true;
if (MainActivity.photoListSend != null) {
if (!MainActivity.photoListSend.isEmpty())
if (NetworkUtil.isNetworkAvailable(context)) {
if (MainActivity.photoListSend.size() > 0) {
MainActivity.isSend = true;
running = true;
InputStream responseInputStream = null;
Log.e("start wysłania ", "start");
try {
if (MainActivity.photoListSend.get(0).isFile()) {
responseInputStream = HttpConnectionsUtil.sendPhotoRequest(getApplicationContext(), true, MainActivity.photoListSend.get(0).getName());
if (responseInputStream != null) {
String input = convertStreamToString(responseInputStream);
if (input.equals("empty"))
return "BAD";
else {
try {
int tt = ResponseParser.getType(input);
Log.e("TaG", tt + " ");
if (tt == 0) {
return null;
} else if (tt == -1) {
return null;
}
} catch (UnknownAnswerName e) {
e.printStackTrace();
return null;
}
}
}
} else {
return "BAD";
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
// Log.e("Wysyłanie zdjęcia ", convertStreamToString(responseInputStream));
if (responseInputStream != null)
return convertStreamToString(responseInputStream);
}
}
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (NetworkUtil.isNetworkAvailable(context)) {
if (sp.getBoolean("workOffLine", false)) {
editor.putBoolean("workOffLine", false);
editor.commit();
isConnect.setVisibility(View.VISIBLE);
imgIsSend.setVisibility(View.VISIBLE);
imgIsNet.setVisibility(View.GONE);
}
}
if (s != null) {
if (!MainActivity.photoListSend.isEmpty()) {
if (MainActivity.photoListSend.size() > 0) {
File file = MainActivity.photoListSend.get(0);
if (file.exists())
file.delete();
MainActivity.photoListSend.remove(0);
Gson gson = new Gson();
String jsonCurProduct = gson.toJson(MainActivity.photoListSend);
SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("TAG", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("TAG", jsonCurProduct);
editor.apply();
File imagesFolder = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
assert imagesFolder != null;
}
}
}
if (s == null) {
MainActivity.isSend = false;
}
if (!MainActivity.photoListSend.isEmpty()) {
if (NetworkUtil.isNetworkAvailable(context)) {
if (MainActivity.photoListSend.size() > 0) {
asyncSender = new SendPhotoTask();
asyncSender.execute();
Log.e("Wysyłanie kolejnego ", "zdjecia");
} else {
context.stopService(new Intent(context, Sendrer.class));
asyncSender.cancel(true);
context.startService(new Intent(context, Sendrer.class));
}
} else {
context.stopService(new Intent(context, Sendrer.class));
asyncSender.cancel(true);
context.startService(new Intent(context, Sendrer.class));
}
} else {
MainActivity.isSend = false;
context.stopService(new Intent(context, Sendrer.class));
asyncSender.cancel(true);
context.startService(new Intent(context, Sendrer.class));
}
running = false;
}
}
}

That's because another thread is modifying MainActivity meanwhile. You can branch the line with
synchronized(MainActivity.this) {
String jsonCurProduct = gson.toJson(MainActivity.photoListSend);
}
however you should be aware of possible performance issues because now all threads will be waiting till toJson method ends
Read more about the exception and how to avoid this

Related

Error while saving files in External Android storage

When I open the activity, I request for the directory permission. Once the permission is allowed, I write the name and content of the file and then I press the save button. There is a confirmation dialog before saving the file. I choose YES there and then the following error appears.
2019-07-17 04:29:31.063 17879-17879/com.halimlab.catatanharian E/WindowManager: android.view.WindowLeaked: Activity com.halimlab.catatanharian.InsertAndViewActivity has leaked window DecorView#56fdc15[InsertAndViewActivity] that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:538)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:346)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:94)
at android.app.Dialog.show(Dialog.java:329)
at androidx.appcompat.app.AlertDialog$Builder.show(AlertDialog.java:1007)
at com.halimlab.catatanharian.InsertAndViewActivity.konfirmasiSave(InsertAndViewActivity.java:191)
at com.halimlab.catatanharian.InsertAndViewActivity.onBackPressed(InsertAndViewActivity.java:197)
at com.halimlab.catatanharian.InsertAndViewActivity.buatDanUbah(InsertAndViewActivity.java:177)
at com.halimlab.catatanharian.InsertAndViewActivity$1.onClick(InsertAndViewActivity.java:188)
at androidx.appcompat.app.AlertController$ButtonHandler.handleMessage(AlertController.java:167)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6739)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:495)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:859)
Here is my code.
public class InsertAndViewActivity extends AppCompatActivity implements View.OnClickListener {
public static final int REQUEST_CODE_STORAGE = 100;
int eventID = 0;
EditText edtFileName, edtContent;
Button btnSimpan;
boolean isEditable = false;
String fileName = "";
String tempCatatan = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert_and_view);
// button back
ActionBar menu = getSupportActionBar();
menu.setDisplayShowHomeEnabled(true);
menu.setDisplayHomeAsUpEnabled(true);
// input
edtFileName = findViewById(R.id.editFilename);
edtContent = findViewById(R.id.editContent);
// button
btnSimpan = findViewById(R.id.btnSimpan);
btnSimpan.setOnClickListener(this);
Bundle extras = getIntent().getExtras();
if (extras != null) {
fileName = extras.getString("filename");
edtFileName.setText(fileName);
getSupportActionBar().setTitle("Ubah Catatan");
} else {
getSupportActionBar().setTitle("Tambah Catatan");
}
eventID = 1;
if (Build.VERSION.SDK_INT >= 23) {
if (periksaIzin()) {
bacaFile();
}
} else {
bacaFile();
}
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btnSimpan :
eventID = 2;
if (!tempCatatan.equals(edtContent.getText().toString())) {
if (Build.VERSION.SDK_INT >= 23) {
konfirmasiSave();
}
} else {
konfirmasiSave();
}
break;
}
}
public boolean periksaIzin() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == getPackageManager().PERMISSION_GRANTED) {
return true;
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_STORAGE);
return false;
}
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_CODE_STORAGE :
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (eventID == 1) {
bacaFile();
} else {
konfirmasiSave();
}
}
break;
}
}
void bacaFile() {
String path = Environment.getExternalStorageDirectory().toString() + "/halimlab.catatan";
File file = new File(path, edtFileName.getText().toString());
if (file.exists()) {
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line = br.readLine();
while (line != null) {
text.append(line);
line = br.readLine();
}
br.close();
} catch (Exception e) {
System.out.println("ERROR" + e.getMessage());
}
tempCatatan = text.toString();
edtContent.setText(text.toString());
}
}
void buatDanUbah() {
String state = Environment.getExternalStorageState();
if (!Environment.MEDIA_MOUNTED.equals(state)) {
return;
}
String path = Environment.getExternalStorageDirectory().toString() + "/halimlab.catatan";
File parent = new File(path);
if (parent.exists()) {
File file = new File(path, edtFileName.getText().toString());
FileOutputStream outputStream = null;
try {
file.createNewFile();
outputStream = new FileOutputStream(file);
OutputStreamWriter streamWriter = new OutputStreamWriter(outputStream);
streamWriter.append(edtContent.getText());
streamWriter.flush();
streamWriter.close();
streamWriter.flush();
streamWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
} else {
parent.mkdir();
File file = new File(path, edtFileName.getText().toString());
FileOutputStream outputStream = null;
try {
file.createNewFile();
outputStream = new FileOutputStream(file, false);
outputStream.write(edtContent.getText().toString().getBytes());
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
onBackPressed();
}
void konfirmasiSave () {
new AlertDialog.Builder(this)
.setTitle("Simpan Catatan")
.setMessage("Apakah anda akan menyimpan catatan ini ?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
buatDanUbah();
}
})
.setNegativeButton(android.R.string.no, null).show();
}
#Override
public void onBackPressed() {
if (!tempCatatan.equals(edtContent.getText().toString())) {
konfirmasiSave();
}
super.onBackPressed();
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
}
I have the necessary permissions in my AndroidManifest.xml.
<uses-permission android:name = "android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name = "android.permission.READ_EXTERNAL_STORAGE"/>
You need to modify the onBackPressed function like the following.
#Override
public void onBackPressed() {
if (!tempCatatan.equals(edtContent.getText().toString()))
konfirmasiSave();
else super.onBackPressed(); // Do that in the else part.
}
Because in the konfirmasiSave function you are opening a dialog which is not being closed or any action is being taken upon it and hence you are calling the super.onBackPressed which is trying to return back to the previous activity and hence causing the window leak error.
And handle the value of the tempCatatan variable before exiting so that your onBackPressed function performs as expected.

Android TTS how to display speaking word in textview

How can i display tts output as text view when word speaking.
Actually i want to display tts output words in textview. I have 1 edittext in which i enter some data and then when click on play button it performs speech but i also want to display speaking words in text view how can i do this any one can help me. i also think about convert text into array form and then pass but, i don't think it useful any other solution ?
Code which i do currently.
For Example: If TTS is speaking this string: How are you! and when it reaches 'how', how can I display 'how' in text view only single word.
Initializations();
textToSpeech = new TextToSpeech(MainActivity.this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = textToSpeech.setLanguage(Locale.ENGLISH);
if (result == TextToSpeech.LANG_MISSING_DATA) {
Toast.makeText(MainActivity.this, "Sorry ! Language data missing", Toast.LENGTH_SHORT).show();
} else if (result == TextToSpeech.LANG_NOT_SUPPORTED) {
Toast.makeText(MainActivity.this, "Sorry ! Language not supported", Toast.LENGTH_SHORT).show();
} else {
speek.setEnabled(true);
}
} else if (status == TextToSpeech.ERROR) {
Toast.makeText(MainActivity.this, "Sorry ! Text to speech can't be initialized", Toast.LENGTH_SHORT).show();
speek.setEnabled(false);
}
}
});
speek.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SpeekOut();
}
});
private void SpeekOut() {
String text = etTextToSpeech.getText().toString();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null, null);
} else {
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
Try this to read
add this in any button click.
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
Intent i = new Intent(MainService.ACTION);
if (isServiceRunning()) {
stopService(i);
((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
.cancelAll();
} else {
startService(i);
runAsForeground();
}
try { startActivityForResult(intent, RESULT_SPEECH);
txtText.setText("");
} catch (ActivityNotFoundException a) {
Toast t = Toast.makeText(getApplicationContext(), "Opps! Your device doesn't support Speech to Text", Toast.LENGTH_SHORT); t.show();
}
//runAsForeground function here
private void runAsForeground(){
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent=PendingIntent.getActivity(this, 0,
notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
Notification notification=new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(getString(R.string.app_name))
.setContentText("Night Mode")
.setContentIntent(pendingIntent).build();
NotificationManager notificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notification.flags = notification.flags
| Notification.FLAG_ONGOING_EVENT;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);
}
To display in the textview
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_SPEECH: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> text = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txtText.setText(text.get(0));
}
break;
}
}
}
//MainService
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.os.PowerManager;
import android.provider.ContactsContract.PhoneLookup;
import android.util.Log;
public class MainService extends Service {
public static final String ACTION = "com.thul.CallRecorder.CALL_RECORD";
public static final String STATE = "STATE";
public static final String START = "START";
public static final String STORAGE = "STORAGE";
public static final String INCOMING = "INCOMING";
public static final String OUTGOING = "OUTGOING";
public static final String BEGIN = "BEGIN";
public static final String END = "END";
protected static final String TAG = MainService.class.getName();
protected static final boolean DEBUG = false;
private static final String AMR_DIR = "/callrec/";
private static final String IDLE = "";
private static final String INCOMING_CALL_SUFFIX = "_i";
private static final String OUTGOING_CALL_SUFFIX = "_o";
private Context cntx;
private volatile String fileNamePrefix = IDLE;
private volatile MediaRecorder recorder;
private volatile PowerManager.WakeLock wakeLock;
private volatile boolean isMounted = false;
private volatile boolean isInRecording = false;
#Override
public IBinder onBind(Intent i) {
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
this.cntx = getApplicationContext();
this.prepareAmrDir();
log("service create");
}
#Override
public void onDestroy() {
log("service destory");
this.stopRecording();
this.cntx = null;
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (null == intent || !ACTION.equals(intent.getAction())) {
return super.onStartCommand(intent, flags, startId);
}
String state = intent.getStringExtra(STATE);
String phoneNo = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
log("state: " + state + " phoneNo: " + phoneNo);
if (OUTGOING.equals(state)) {
fileNamePrefix = getContactName(this.getContext(), phoneNo)
+ OUTGOING_CALL_SUFFIX;
} else if (INCOMING.equals(state)) {
fileNamePrefix = getContactName(this.getContext(), phoneNo)
+ INCOMING_CALL_SUFFIX;
} else if (BEGIN.equals(state)) {
startRecording();
} else if (END.equals(state)) {
stopRecording();
} else if (STORAGE.equals(state)) {
String mountState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(mountState)) {
prepareAmrDir();
} else {
isMounted = false;
}
if (!isInRecording) {
stopSelf();
}
}
return START_STICKY;
}
public Context getContext() {
return cntx;
}
private void stopRecording() {
if (isInRecording) {
isInRecording = false;
recorder.stop();
recorder.release();
recorder = null;
releaseWakeLock();
stopSelf();
log("call recording stopped");
}
}
private String getDateTimeString() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd'_'HHmmss");
Date now = new Date();
return sdf.format(now);
}
private String getMonthString() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
Date now = new Date();
return sdf.format(now);
}
private String getDateString() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Date now = new Date();
return sdf.format(now);
}
private String getTimeString() {
SimpleDateFormat sdf = new SimpleDateFormat("HHmmss");
Date now = new Date();
return sdf.format(now);
}
private void startRecording() {
if (!isMounted)
return;
stopRecording();
try {
File amr = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath()
+ AMR_DIR
+ getDateTimeString()
+ "_"
+ fileNamePrefix + ".amr");
log("Prepare recording in " + amr.getAbsolutePath());
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(amr.getAbsolutePath());
recorder.prepare();
recorder.start();
isInRecording = true;
acquireWakeLock();
log("Recording in " + amr.getAbsolutePath());
} catch (Exception e) {
Log.w(TAG, e);
}
}
private void prepareAmrDir() {
isMounted = Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED);
if (!isMounted)
return;
File amrRoot = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + AMR_DIR);
if (!amrRoot.isDirectory())
amrRoot.mkdir();
}
private String getContactName(Context cntx, String phoneNo) {
if (null == phoneNo)
return "";
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(phoneNo));
ContentResolver cr = cntx.getContentResolver();
Cursor c = cr.query(uri, new String[] { PhoneLookup.DISPLAY_NAME },
null, null, null);
if (null == c) {
log("getContactName: The cursor was null when query phoneNo = "
+ phoneNo);
return phoneNo;
}
try {
if (c.moveToFirst()) {
String name = c.getString(0);
name = name.replaceAll("(\\||\\\\|\\?|\\*|<|:|\"|>)", "");
log("getContactName: phoneNo: " + phoneNo + " name: " + name);
return name;
} else {
log("getContactName: Contact name of phoneNo = " + phoneNo
+ " was not found.");
return phoneNo;
}
} finally {
c.close();
}
}
private void log(String info) {
if (DEBUG && isMounted) {
File log = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath()
+ AMR_DIR
+ "log_"
+ getMonthString()
+ ".txt");
try {
BufferedWriter out = new BufferedWriter(new FileWriter(log,
true));
try {
synchronized (out) {
out.write(getDateString()+getTimeString());
out.write(" ");
out.write(info);
out.newLine();
}
} finally {
out.close();
}
} catch (IOException e) {
Log.w(TAG, e);
}
}
}
private void acquireWakeLock() {
if (wakeLock == null) {
log("Acquiring wake lock");
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this
.getClass().getCanonicalName());
wakeLock.acquire();
}
}
private void releaseWakeLock() {
if (wakeLock != null && wakeLock.isHeld()) {
wakeLock.release();
wakeLock = null;
log("Wake lock released");
}
}
}
//isServiceRunning
private boolean isServiceRunning() {
ActivityManager myManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
ArrayList<RunningServiceInfo> runningService = (ArrayList<RunningServiceInfo>) myManager
.getRunningServices(30);
for (int i = 0; i < runningService.size(); i++) {
if (runningService.get(i).service.getClassName().equals(
MainService.class.getName())) {
return true;
}
}
return false;
}

Android Tumblr login issue "JumblrException: Not Authorized"

Why following code giving me such type of exception com.tumblr.jumblr.exceptions.JumblrException: Not Authorized
I saw this question , but i am not able to resolved this issue...plz help me
public class MainActivity extends Activity implements OnClickListener {
private static final String TAG = "TumblrDemo";
private static final String PREFERENCE_NAME = "tumblr";
public static final String REQUEST_TOKEN_URL = "https://www.tumblr.com/oauth/request_token";
public static final String ACCESS_TOKEN_URL = "https://www.tumblr.com/oauth/access_token";
public static final String AUTH_URL = "https://www.tumblr.com/oauth/authorize";
// public static final String CALLBACK_URL =
// "tumblrdemo://tumblrdemo.com/ok";
public static final String OAUTH_CALLBACK_SCHEME = "oauthflow-tumblr";
public static final String OAUTH_CALLBACK_HOST = "callback";
public static final String CALLBACK_URL = OAUTH_CALLBACK_SCHEME + "://"
+ OAUTH_CALLBACK_HOST;
private TransparentProgressDialog progressDialog;
private Button loginTumblrBtn;
private SharedPreferences preferences;
private CommonsHttpOAuthConsumer consumer;
private CommonsHttpOAuthProvider provider;
private String token, token_secret, oauth_verifier;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
consumer = new CommonsHttpOAuthConsumer(Constant.CONSUMER_KEY,
Constant.CONSUMER_SECRET);
provider = new CommonsHttpOAuthProvider(REQUEST_TOKEN_URL,
ACCESS_TOKEN_URL, AUTH_URL);
preferences = getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
loginTumblrBtn = (Button) findViewById(R.id.login_tumblr);
Uri uri = this.getIntent().getData();
if (uri != null && uri.getScheme().equals(OAUTH_CALLBACK_SCHEME)) {
loginTumblrBtn.setText(getString(R.string.logout_tumblr));
try {
oauth_verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);
Log.d(TAG, uri.toString());
// provider.retrieveAccessToken(consumer, oauth_verifier);
// token = consumer.getToken();
// token_secret = consumer.getTokenSecret();
token = uri.getQueryParameter("oauth_token");
token_secret = uri.getQueryParameter("oauth_verifier");
consumer.setTokenWithSecret(token, token_secret);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(Constant.TOKEN, token);
editor.putString(Constant.TOKEN_SECRET, token_secret);
editor.commit();
getUserDetails();
} catch (Exception e) {
e.printStackTrace();
}
} else {
loginTumblrBtn.setText(getString(R.string.login_tumblr));
}
loginTumblrBtn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.login_tumblr) {
if (isTumblrConnected()) {
SharedPreferences.Editor editor = preferences.edit();
editor.putString(Constant.TOKEN, null);
editor.putString(Constant.TOKEN_SECRET, null);
editor.commit();
loginTumblrBtn.setText(getString(R.string.login_tumblr));
} else {
new AsyncTaskClass().execute();
}
}
}
private boolean isTumblrConnected() {
return preferences.getString(Constant.TOKEN, null) != null;
}
private class AsyncTaskClass extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
String authUrl = provider.retrieveRequestToken(consumer,
CALLBACK_URL);
startActivity(new Intent("android.intent.action.VIEW",
Uri.parse(authUrl)));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new TransparentProgressDialog(MainActivity.this,
R.drawable.loading);
progressDialog.show();
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (progressDialog != null && progressDialog.isShowing())
progressDialog.dismiss();
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if (isTumblrConnected()) {
token = preferences.getString(Constant.TOKEN, null);
token_secret = preferences.getString(Constant.TOKEN_SECRET, null);
loginTumblrBtn.setText(getString(R.string.logout_tumblr));
getUserDetails();
} else {
loginTumblrBtn.setText(getString(R.string.login_tumblr));
}
}
private void getUserDetails() {
new Thread(new Runnable() {
#Override
public void run() {
try {
JumblrClient client = new JumblrClient(
Constant.CONSUMER_KEY, Constant.CONSUMER_SECRET);
client.setToken(token, token_secret);
// Write the user's name
User user = client.user();
System.out.println(user.getName());
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
Ya finally got solution after too much work, i misunderstood between access token and request token.
Here it is working solution for above issue.Hope it works for you.
public class MainActivity extends Activity implements OnClickListener {
private Button loginTumblrBtn;
private CommonsHttpOAuthConsumer consumer;
private CommonsHttpOAuthProvider provider;
private SharedPreferences preferences;
private Uri uri;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
preferences = getSharedPreferences("tumblr", Context.MODE_PRIVATE);
loginTumblrBtn = (Button) findViewById(R.id.login_tumblr);
loginTumblrBtn.setOnClickListener(this);
consumer = new CommonsHttpOAuthConsumer(Constant.CONSUMER_KEY,
Constant.CONSUMER_SECRET);
provider = new CommonsHttpOAuthProvider(Constant.REQUEST_TOKEN_URL,
Constant.ACCESS_TOKEN_URL, Constant.AUTH_URL);
uri = this.getIntent().getData();
if (uri != null
&& uri.getScheme().equals(Constant.OAUTH_CALLBACK_SCHEME)) {
loginTumblrBtn.setText(getString(R.string.logout_tumblr));
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
consumer.setTokenWithSecret(
preferences.getString("requestToken", ""),
preferences.getString("requestSecret", ""));
provider.setOAuth10a(true);
provider.retrieveAccessToken(consumer,
uri.getQueryParameter(OAuth.OAUTH_VERIFIER));
consumer.setTokenWithSecret(consumer.getToken(),
consumer.getTokenSecret());
SharedPreferences.Editor editor = preferences.edit();
editor.putString("token", consumer.getToken());
editor.putString("token_secret",
consumer.getTokenSecret());
editor.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
loginTumblrBtn.setText(getString(R.string.login_tumblr));
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.login_tumblr:
if (preferences.getString("token", null) != null) {
loginTumblrBtn.setText(getString(R.string.login_tumblr));
SharedPreferences.Editor editor = preferences.edit();
editor.putString("token", null);
editor.putString("token_secret", null);
editor.commit();
} else {
progressDialog = ProgressDialog.show(this, "Loading",
"Please Wait...");
new Thread(new Runnable() {
#Override
public void run() {
try {
String authUrl = provider.retrieveRequestToken(
consumer, Constant.CALLBACK_URL);
SharedPreferences.Editor editor = preferences
.edit();
editor.putString("requestToken",
consumer.getToken());
editor.putString("requestSecret",
consumer.getTokenSecret());
editor.commit();
startActivity(new Intent(
"android.intent.action.VIEW", Uri
.parse(authUrl)));
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
break;
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if (preferences.getString("token", null) != null) {
loginTumblrBtn.setText(getString(R.string.logout_tumblr));
} else {
loginTumblrBtn.setText(getString(R.string.login_tumblr));
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
and put this intent-filter code inside manifest>application>activity (where callback is done)
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="callback"
android:scheme="oauthflow-tumblr" />
</intent-filter>
Image sharing on TUMBLR
public void shareImageOnTumblr(final File imgFile, final String caption,
final Handler handler) {
new Thread(new Runnable() {
#Override
public void run() {
try {
PhotoPost photoPost = client.newPost(client.user()
.getBlogs().get(0).getName(), PhotoPost.class);
if (!caption.isEmpty())
photoPost.setCaption(caption);
photoPost.setPhoto(new Photo(imgFile));
photoPost.save();
Bundle bundle = new Bundle();
Message message = new Message();
bundle.putInt("method",
UploadActivity.SHARED_PHOTO_SUCCESSFULLY);
message.setData(bundle);
handler.sendMessage(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
Video sharing on TUMBLR
public void shareVideoOnTumblr(final File videoFile, final String caption,
final Handler handler) {
new Thread(new Runnable() {
#Override
public void run() {
try {
VideoPost videoPost = client.newPost(client.user()
.getBlogs().get(0).getName(), VideoPost.class);
if (!caption.toString().isEmpty())
videoPost.setCaption(caption.toString());
videoPost.setData(videoFile);
videoPost.save();
Bundle bundle = new Bundle();
Message message = new Message();
bundle.putInt("method",
UploadActivity.SHARED_VIDEO_SUCCESSFULLY);
message.setData(bundle);
handler.sendMessage(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}

Android Socket sending data to WPF application

So i have a registration Android app that in main activity creates a socket connection on create opensocket(). Everything runs perfectly on the first submit, the debugger out put looks great and it sends/recieves data back from my WPF app. Now It goes to a thanks activity which onclick leads back to my mainactivity. Now when i hit submit, it works fine, but is showing its hitting my socket methods twice (only inserts the records once on my WPF app) , and so on as many times i submit. I realize i'm not closing or reusing my socket connection correctly?! I've tried several things, but can't seem to get this to either reuse the same opensocket instance or can't just close and reopen on reload. I'm quite new to android and sockets all together, any help is greatly appreciated!
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
settingsCheck();
openSocket();
sett.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
launchSettings();
}
});
mainLogo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
RefreshMain();
}
});
btn_register.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
tv_errors.setText("");
errorMsg = "";
nameCheck(et_lName.getText().toString(),et_fName.getText().toString());
emailCheck(et_email.getText().toString());
partnerCheck();
mobileCheck(et_mobile.getText().toString());
if (SocketHandler.SocketConnected){
if(errorMsg == ""){
//tv_errors.setText("");
if(checkForSD() == true){
sendRegistrantInfo(et_fName.getText() + "," + et_lName.getText() + "," + et_email.getText() + "," + et_mobile.getText() + "," + et_partEmail.getText() + "," + cb_terms1.isChecked() + "," + cb_terms2.isChecked() );
}
else{
tv_errors.setText("**Please insert an SD Card.");
}
}
else{
//tv_errors.setText(errorMsg);
}
}
else
{
connectionStatus.setText("Connection Error.");
tv_errors.setText("**Connection lost, please try again.");
//openSocket();
}
}
});
}
public void RefreshMain()
{
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
public void launchLogin()
{
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
}//end launchLogin
public void launchSettings()
{
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
}//end launchSettings
public void settingsCheck()
{
SharedPreferences settings = getSharedPreferences("prefs",MODE_PRIVATE);
String currentIP = settings.getString("IPSetting", "");
String currentPort = settings.getString("PORTSetting", "");
currentMem = settings.getString("SDSize", "");
if (currentIP == "" || currentPort == ""){
Intent myIntent = new Intent(this,SettingsActivity.class);
startActivity(myIntent);
}
}//end settingsCheck()
public void launchRingDialog(String id) {
final String idYo = id;
final ProgressDialog ringProgressDialog = ProgressDialog.show(MainActivity.this, "Formatting SD Card","Formatting SD Card, please wait this could take several minutes...", true);
new Thread(new Runnable() {
#Override
public void run() {
try {
fileToSD(idYo);
Thread.sleep(10000);
} catch (Exception e) {
}
ringProgressDialog.dismiss();
}
}).start();
}
public boolean checkForSD()
{
String root = "/storage/removable/sdcard1/";
double memInGigs = round(sizeMatters(root),2);
if(memInGigs >0){
return true;
}
else
{
return false;
}
}
private double sizeMatters(String path)
{
StatFs stat = new StatFs(path);
double availSize = (double)stat.getAvailableBlocks() * (double)stat.getBlockSize();
double ingigs = availSize/ 1073741824;
return ingigs;
}//end sizeMatters()
private void sendRegistrantInfo(String reg){
_sh.sendMessage(reg);
}
private void openSocket(){
_sh = new SocketHandler();
_sh.setSocketHandlerListener(this);
SharedPreferences settings = getSharedPreferences("prefs",MODE_PRIVATE);
String currentIP = settings.getString("IPSetting", "");
String currentPort = settings.getString("PORTSetting", "");
_sh.open(currentIP, currentPort);
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onSocketConnected() {
Log.v(TAG, "onSocketConnected");
connectionStatus.setText("CONNECTED");
}
#Override
public void onSocketData(String msg) {
Log.v(TAG, "onSocketData - " + msg );
int usrID = Integer.parseInt(msg.trim());
if (msg != null & usrID > 0){
launchRingDialog(msg);
Intent intent = new Intent(this, ThanksActivity.class);
startActivity(intent);
}
else if(msg.trim().equals("-2") == true)
{
tv_errors.setText("**This email has already been registered for this event, please click Already Registered button to sign in.");
}
else{
tv_errors.setText("**Error, Please try submitting again.");
errorMsg = "-1";
}
}
#Override
public void onSocketDisconnected() {
Log.v(TAG, "onSocketDisconnected");
connectionStatus.setText("DISCONNECTED");
}
public class SocketHandler {
Socket sc;
public static boolean SocketConnected = false;
private static ClientThread cThread;
public String prefsFile = "prefs";
public String port = "8888";
public String ip = "192.168.1.4";
private String TAG = "SocketHandler";
protected SocketHandlerListener socketHandlerListener;
public interface SocketHandlerListener{
public void onSocketConnected();
public void onSocketData(String msg);
public void onSocketDisconnected();
}
public SocketHandler(){
}
public void setSocketHandlerListener(SocketHandlerListener shl){
socketHandlerListener = shl;
}
public void open(String ip, String port){
this.ip = ip;
this.port = port;
cThread = new ClientThread();
try{
cThread.start();
}catch (Exception ex){
Log.v(TAG, "Error connecting to socket");
}
}
public void close(){
if (cThread != null){
if (cThread.socket != null){
try {
cThread.socket.close();
} catch (Exception e) {
Log.v(TAG, "Error closing socket");
}
cThread.socket = null;
}
}
}
public void sendMessage(String msg){
cThread.sendMessage(msg);
}
public void messageRecieved(String msg){
dispatchSocketData(msg);
}
private void dispatchSocketConnected(){
if (socketHandlerListener != null){
socketHandlerListener.onSocketConnected();
}
}
private void dispatchSocketDisconnected(){
if (socketHandlerListener != null){
socketHandlerListener.onSocketDisconnected();
}
}
private void dispatchSocketData(String msg){
if (socketHandlerListener != null){
socketHandlerListener.onSocketData(msg);
}
}
public class ClientThread extends Thread {
public Socket socket;
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(ip);
Log.v(TAG, "C: Connecting..." + ip + ":" + port);
socket = new Socket(serverAddr, Integer.parseInt(port));
socket.setSoTimeout(0);
socket.setKeepAlive(true);
SocketConnected = true;
handler.post(new Runnable() {
#Override
public void run() {
dispatchSocketConnected();
}
});
// BLOCKING THE THREAD
while (SocketConnected) {
InputStream in = socket.getInputStream();
byte[] buffer = new byte[4096];
int line = in.read(buffer, 0, 4096);
while (line != -1) {
byte[] tempdata = new byte[line];
System.arraycopy(buffer, 0, tempdata, 0, line);
final String data = new String(tempdata);
handler.post(new Runnable() {
#Override
public void run() {
messageRecieved(data);
SocketConnected = false;
}
});
line = in.read(buffer, 0, 4096);
}
// break;
}
socket.close();
Log.v("Socket", "C: Closed.");
handler.post(new Runnable() {
#Override
public void run() {
dispatchSocketDisconnected();
}
});
SocketConnected = false;
} catch (Exception e) {
Log.v("Socket", "C: Error", e);
handler.post(new Runnable() {
#Override
public void run() {
dispatchSocketDisconnected();
}
});
SocketConnected = false;
}
}
Handler handler = new Handler();
public void sendMessage(String msg){
if (socket != null){
if (socket.isConnected()){
PrintWriter out;
try {
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), false);
out.print(msg);
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}

Android Shoutcast internet Radio Streaming

I developed Shoutcastinternet Radio Streaming and I'm able to stream and play Successfully.
But the problem is: when i execute my application,I'm able to stream and play Continuously for halfanhour,after that the stream is getting stopped(not able to play, after that if i click on again play the stream Continues and again after some time FileNotFoundException)?
I logged the Error, after Stream get stopped.
The Error is :
java.io.FileNotFoundException: /data/data/com.torilt/cache/downloadingMediaFile430 (No such file or directory)
Can't find file. Android must have deleted it on a clean up
Getting Exception in setupplayer()
Source Code:
public class StreamingMediaPlayer extends Service {
final static public String AUDIO_MPEG = "audio/mpeg";
final static public String BITERATE_HEADER = "icy-br";
public int INTIAL_KB_BUFFER ;
private Handler handler;
//= 96*10/8
final public int BIT = 8;
final public int SECONDS = 60;
int bitrate = 56;
public File downloadingMediaFile;
final public String DOWNFILE = "downloadingMediaFile";
public Context context;
public int counter;
public int playedcounter;
public int preparecounter;
public MediaPlayer mp1;
public MediaPlayer mp2;
public boolean mp1prepared;
public boolean mp2prepared;
public boolean mp1preparing;
public boolean mp2preparing;
public boolean downloadingformp1;
public boolean downloadingformp2;
public boolean prepareState;
public String SONGURL = "";
// playing is "true" for mp1 and "false" for mp2
public boolean mp1playing;
public boolean started;
public boolean processHasStarted;
public boolean processHasPaused;
public boolean regularStream;
public BufferedInputStream stream;
public URL url;
public URLConnection urlConn;
public String station;
public String audiourl;
public Intent startingIntent = null;
public boolean stopping;
Thread preparringthread;
boolean waitingForPlayer;
// Setup all the variables
private void setupVars() {
counter = 0;
playedcounter = 0;
preparecounter = 0;
mp1 = new MediaPlayer();
mp2 = new MediaPlayer();
mp1prepared = false;
mp2prepared = false;
mp1preparing = false;
mp2preparing = false;
downloadingformp1 = false;
downloadingformp2 = false;
prepareState = true;
mp1playing = false;
started = false;
processHasStarted = false;
processHasPaused = true;
regularStream = false;
stream = null;
url = null;
urlConn = null;
station = null;
audiourl = null;
stopping = false;
preparringthread = null;
waitingForPlayer = false;
}
// This object will allow other processes to interact with our service
private final IStreamingMediaPlayer.Stub ourBinder = new IStreamingMediaPlayer.Stub() {
// String TAG = "IStreamingMediaPlayer.Stub";
public String getStation() {
// Log.d(TAG, "getStation");
return station;
}
public String getUrl() {
// Log.d(TAG, "getUrl");
return audiourl;
}
public boolean playing() {
// Log.d(TAG, "playing?");
return isPlaying();
}
public boolean pause() {
// Log.d(TAG, "playing?");
return isPause();
}
public void startAudio() {
// Log.d(TAG, "startAudio");
Runnable r = new Runnable() {
public void run() {
onStart(startingIntent, 0);
}
};
new Thread(r).start();
}
public void stopAudio() {
// Log.d(TAG, "stopAudio");
stop();
}
};
#Override
public void onCreate() {
super.onCreate();
context = this;
}
#Override
public void onStart(Intent intent, int startId) throws NullPointerException {
super.onStart(intent, startId);
// final String TAG = "StreamingMediaPlayer - onStart";
context = this;
setupVars();
if (intent.hasExtra("audiourl")) {
raiseThreadPriority();
processHasStarted = true;
processHasPaused = false;
audiourl = intent.getStringExtra("audiourl");
station = intent.getStringExtra("station");
downloadingMediaFile = new File(context.getCacheDir(), DOWNFILE+ counter);
downloadingMediaFile.deleteOnExit();
Runnable r = new Runnable() {
public void run() {
try {
startStreaming(audiourl);
} catch (IOException e) {
// Log.d(TAG, e.toString());
}
}
};
Thread t = new Thread(r);
t.start();
}
}
#Override
public void onDestroy() {
super.onDestroy();
mp1.stop();
mp2.stop();
}
#Override
public IBinder onBind(Intent intent) {
startingIntent = intent;
context = this;
return ourBinder;
}
#Override
public boolean onUnbind(Intent intent) {
super.onUnbind(intent);
stopSelf();
return true;
}
/**
* Progressivly download the media to a temporary location and update the
* MediaPlayer as new content becomes available.
*/
public void startStreaming(final String mediaUrl) throws IOException {
try {
url = new URL(mediaUrl);
urlConn = (HttpURLConnection) url.openConnection();
urlConn.setReadTimeout(1000 * 20);
urlConn.setConnectTimeout(1000 * 5);
//The getContentType method is used by the getContent method to determine the type of the remote object; subclasses may find it convenient to override the getContentType method.
String ctype = urlConn.getContentType();
if (ctype == null) {
ctype = "";
} else {
ctype = ctype.toLowerCase();
}
if (ctype.contains(AUDIO_MPEG) || ctype.equals("")) {
String temp = urlConn.getHeaderField(BITERATE_HEADER);
if (temp != null) {
bitrate = new Integer(temp).intValue();
}
} else {
stopSelf();
return;
}
}
catch(NullPointerException ne)
{
}
catch (IOException ioe) {
// Log.e(TAG, "Could not connect to " + mediaUrl);
stopSelf();
return;
}
if (!regularStream) {
INTIAL_KB_BUFFER = bitrate * SECONDS / BIT;
Runnable r = new Runnable() {
public void run() {
try {
downloadAudioIncrement(mediaUrl);
Log.i("TAG12344444", "Unable to play");
stopSelf();
return;
} catch (IOException e) {
Log.i("TAG123", "Unable to initialize the MediaPlayer for Audio Url = "+mediaUrl, e);
stopSelf();
return;
} catch (NullPointerException e) {
stopSelf();
return;
}
}
};
Thread t = new Thread(r);
t.start();
}
}
/**
* Download the url stream to a temporary location and then call the
* setDataSource for that local file
*/
public void downloadAudioIncrement(String mediaUrl) throws IOException{
int bufsizeForDownload = 8 * 1024;
int bufsizeForfile = 64 * 1024;
stream = new BufferedInputStream(urlConn.getInputStream(),bufsizeForDownload);
Log.i("bufsize",Integer.toString(urlConn.getInputStream().available()));
try{
if(stream == null || stream.available() == 0){
stopSelf();
Log.i("unable to create ","stream null");
return;
}
}catch (NullPointerException e) {
stopSelf();
Log.i("return1","return1");
return;
}
BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(downloadingMediaFile), bufsizeForfile);
byte buf[] = new byte[bufsizeForDownload];
int totalBytesRead = 0, totalKbRead = 0, numread = 0;
do {
if (bout == null) {
counter++;
downloadingMediaFile = new File(context.getCacheDir(), DOWNFILE+ counter);
downloadingMediaFile.deleteOnExit();
bout = new BufferedOutputStream(new FileOutputStream(downloadingMediaFile), bufsizeForfile);
}
try {
numread = stream.read(buf);
} catch (IOException e) {
Log.d("Downloadingfile", "Bad read. Let's quit.");
// stop();
Log.i("return2","return2");
stopSelf();
// return;
}
catch (NullPointerException e) {
// Let's get out of here
e.printStackTrace();
break;
}
if (numread < 0) {
bout.flush();
stopSelf();
Log.i("Bad read from stream", "Bad read from stream3");
if(stream == null){
urlConn = new URL(mediaUrl).openConnection();
urlConn.setConnectTimeout(1000 * 30);
urlConn.connect();
stream = new BufferedInputStream(urlConn.getInputStream(),bufsizeForDownload);
}else{
handler.post(new Runnable() {
public void run() {
Log.i("Bad read from stream", "Bad read from xyz");
context.stopService(startingIntent);
Log.i("return3","return3");
return;
}
});
}
} else if (numread >= 1) {
bout.write(buf, 0, numread);
totalBytesRead += numread;
totalKbRead += totalBytesRead / 1000;
}
if (totalKbRead >= INTIAL_KB_BUFFER && stopping != true) {
bout.flush();
bout.close();
bout = null;
if (started == false) {
Runnable r = new Runnable() {
public void run() {
setupplayer();
}
};
Thread t = new Thread(r);
t.start();
}
totalBytesRead = 0;
totalKbRead = 0;
}
if (stopping == true) {
stream = null;
}
} while (stream != null);
}
/** oncompletelister for media player **/
class listener implements MediaPlayer.OnCompletionListener {
public void onCompletion(MediaPlayer mp) {
waitingForPlayer = false;
long timeInMilli = Calendar.getInstance().getTime().getTime();
long timeToQuit = (1000 * 30) + timeInMilli; // add 30 seconds
if (mp1playing)
{
mp1.reset();
removefile();
mp1prepared = false;
// Log.d(TAG, "mp1 is Free.");
if (downloadingformp2) {
if (mp2preparing && stopping == false) {
waitingForPlayer = true;
}
while (mp2preparing && stopping == false) {
if (timeInMilli > timeToQuit) {
stopSelf();
}
timeInMilli = Calendar.getInstance().getTime().getTime();
}
}
} else {
mp2.reset();
removefile();
mp2prepared = false;
if (downloadingformp1) {
if (mp1preparing && stopping == false) {
waitingForPlayer = true;
}
while (mp1preparing && stopping == false) {
if (timeInMilli > timeToQuit) {
stopSelf();
}
timeInMilli = Calendar.getInstance().getTime().getTime();
}
}
}
if (waitingForPlayer == true) {
// we must have been waiting
waitingForPlayer = false;
}
if (stopping == false) {
if (mp1playing) {
mp2.start();
mp1playing = false;
Runnable r = new Runnable() {
public void run() {
setupplayer();
}
};
Thread t = new Thread(r);
t.start();
} else {
mp1.start();
mp1playing = true;
Runnable r = new Runnable() {
public void run() {
setupplayer();
}
};
Thread t = new Thread(r);
t.start();
}
}
}
}
/** OnPreparedListener for media player **/
class preparelistener implements MediaPlayer.OnPreparedListener {
public void onPrepared(MediaPlayer mp) {
if (prepareState) {
prepareState = false;
mp1preparing = false;
mp1prepared = true;
if (started == false) {
started = true;
mp1.start();
mp1playing = true;
Runnable r = new Runnable() {
public void run() {
setupplayer();
}
};
Thread t = new Thread(r);
t.start();
}
} else {
prepareState = true;
mp2preparing = false;
mp2prepared = true;
}
}
};
/**
* Set Up player(s)
*/
public void setupplayer() {
final String TAG = "setupplayer";
Runnable r = new Runnable() {
public void run() {
try {
if (!mp1preparing && !mp1prepared) {
while (true) {
downloadingformp1 = true;
if (started == false)
break;
if (counter > preparecounter)
break;
}
File f = new File(context.getCacheDir(), DOWNFILE+ preparecounter);
FileInputStream ins = new FileInputStream(f);
mp1.setDataSource(ins.getFD());
mp1.setAudioStreamType(AudioManager.STREAM_MUSIC);//playing for live streaming
mp1.setOnCompletionListener(new listener());
mp1.setOnPreparedListener(new preparelistener());
if (started == false || waitingForPlayer == true){
}
mp1.prepareAsync();// .prepare();
mp1preparing = true;
downloadingformp1 = false;
preparecounter++;
} else if (!mp2preparing && !mp2prepared) {
while (true) {
downloadingformp2 = true;
if (started == false)
break;
if (counter > preparecounter)
break;
}
File f = new File(context.getCacheDir(), DOWNFILE+ preparecounter);
FileInputStream ins = new FileInputStream(f);
mp2.setDataSource(ins.getFD());
mp2.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp2.setOnCompletionListener(new listener());
mp2.setOnPreparedListener(new preparelistener());
mp2.prepareAsync();
mp2preparing = true;
downloadingformp2 = false;
preparecounter++;
// }
} else
Log.d(TAG, "No Media player is available to setup.");
return;
} catch (FileNotFoundException e) {
Log.e(TAG, e.toString());
Log.e(TAG,"Can't find file. Android must have deleted it on a clean up ");
stop();
return;
} catch (IllegalStateException e) {
Log.e(TAG, e.toString());
stop();
} catch (IOException e) {
Log.e(TAG, e.toString());
stop();
}
}
};
preparringthread = new Thread(r);
preparringthread.start();
try {
preparringthread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void removefile() {
File temp = new File(context.getCacheDir(), DOWNFILE + playedcounter);
temp.delete();
playedcounter++;
}
public boolean stop() {
final String TAG = "STOP";
stopping = true;
try {
if (mp1.isPlaying()){
if (!(stream == null)) {
Log.i("IN STOP", "MP1 is nill");
stopSelf();
}
mp1.stop();
}
if (mp2.isPlaying()){
Log.i("IN STOP", "MP2 is nill");
if (!(stream == null)){
stopSelf();
}
mp2.stop();
}
} catch (Exception e) {
Log.e(TAG, "error stopping players");
}
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
Log.e(TAG, "error closing open connection");
}
}
stream = null;
processHasStarted = false;
processHasPaused = true;
if (preparringthread != null) {
preparringthread.interrupt();
}
stopSelf();
return true;
}
public boolean isPlaying() {
return processHasStarted;
}
public boolean isPause() {
return processHasPaused;
}
private void raiseThreadPriority() {
Process.setThreadPriority(Process.THREAD_PRIORITY_AUDIO);
}
}
you should call release(), to free the resources. If not released, too many MediaPlayer instances may result in an exception
Write this code when on youe Service
Updated
private void releaseMediaPlayer() {
if (mediaPlayer != null) {
if(mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
mediaPlayer = null;
}
}
#Override
protected void onDestroy() {
super.onDestroy();
releaseMediaPlayer();
}
You can see this

Categories