I have an app that generates music after a user authenticates with OAuth on a webview activity, looking something like this: main player activity-OAuth Activity-back to main player activity. However, the onCreate method is being called twice when going from the OAuth activity, resulting in two audio tracks generated and played at the same time.
Here's part of the code from the MainActivity:
public class MainActivity extends Activity {
int pitch=60;
private static final float VISUALIZER_HEIGHT_DIP = 50f;
Random rn;
boolean isRunning = true;
boolean isPlaying=false;
SeekBar fSlider;
double sliderval;
MediaPlayer mediaPlayer=new MediaPlayer();
ImageButton startStopButton;
ImageButton stopButton;
SeekBar vSlider;
VisualizerView mVisualizerView;
private Visualizer mVisualizer;
ImageButton connectButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// point the slider to the GUI widget
rn = new Random();
fSlider = (SeekBar) findViewById(R.id.frequency);
fSlider.setProgress(0);
vSlider= (SeekBar) findViewById(R.id.seekBar2);
vSlider.setMax(10);
vSlider.setProgress(0);
TextView viewinterval=(TextView) findViewById(R.id.textView2);
viewinterval.setText("");
startStopButton=(ImageButton) findViewById(R.id.imageButton2);
View activity= this.findViewById(R.id.playerActivity);
stopButton=(ImageButton) findViewById(R.id.imageButton1);
RelativeLayout.LayoutParams params= new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, (int)(VISUALIZER_HEIGHT_DIP * getResources().getDisplayMetrics().density));
params.addRule(RelativeLayout.BELOW, R.id.seekBar2);
mVisualizerView = new VisualizerView(this);
mVisualizerView.setLayoutParams(params);
((ViewGroup) activity).addView(mVisualizerView);
connectButton=(ImageButton) findViewById(R.id.imageButton3);
connectButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
mediaPlayer.pause();
Intent intent= new Intent(getApplicationContext(), WebViewActivity.class);
startActivity(intent);
}
});
if(riskscores.length !=0){
viewinterval.setText("generating audio");
new MIDISequence().execute();
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onPause() {
super.onPause();
if(mediaPlayer.isPlaying()){
mediaPlayer.pause();
}
}
class MIDISequence extends AsyncTask<String,Void,String>{
Here's the code from my OAuth Activity
public class WebViewActivity extends Activity {
private WebView gWebView;
final String REDIRECT_URI = "https://localhost:5000/receive_code";
final String CLIENT_ID = "can't post it here";
final String CLIENT_SECRET = "can't post it here";
final String SCOPE = "basic names genomes analyses";
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
gWebView = (WebView) findViewById(R.id.webView1);
gWebView.loadUrl("https://api.23andme.com/authorize/?redirect_uri="
+ REDIRECT_URI + "&response_type=code&client_id=" + CLIENT_ID
+ "&scope=" + SCOPE);
Log.d("WEBVIEW", "got to webpage");
gWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (url.startsWith(REDIRECT_URI)) {
Log.d("WEBVIEW", "onpagefinished is called");
System.out.println("got to override");
if (url.indexOf("code=") != -1) {
//if the query contains code
String queryString = null;
try {
queryString = new URL(url).getQuery();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(queryString);
String[] params = queryString.split("&");
String code = null;
for (String param : params) {
if (param.startsWith("code=")) {
code = param.substring(param.indexOf('=') + 1);
}
}
gWebView.setVisibility(View.GONE);
new PostRequest().execute(code);
// don't go to redirectUri
}
}
}
});
}
class PostRequest extends AsyncTask<String,Void,String>{
#Override
protected String doInBackground(String... params) {
code retrieving client data.....
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
System.out.println("CPE" + e);
} catch(SocketException ex)
{
Log.e("Error : " , "Error on soapPrimitiveData() " + ex.getMessage());
ex.printStackTrace();
return "error occured";
} catch (JSONException e) {
e.printStackTrace();
return "error occured";
} catch (IllegalStateException e) {
e.printStackTrace();
return "error occured";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "error occured";
}
}
return "request complete";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.d("Post result", result);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}
}
The onCreate method of the MainActivity is called twice for some reason... What is going on here?
There seems to be a mistake in your implementation. The thing is, you are trying to use an Intent object to navigate back to your MainActivity form WebActvitity. This is a problem. You shouldn't be doing that.
Whenever you wanna move back to your previous activity, you should simply be calling finish() in the current Activity.
In our scenario,the by using Intent in your WebActivity you are creating a new instance for your MainActivity which already exists in the stack(background). Simply calling finish() in the WebActivity should close it and your MainActivity should be visible.
Do the following changes,
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.d("Post result", result);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
Replace the above method like this,
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.d("Post result", result);
finish();
}
Other than the expected cases, I have observed that only those activities (onCreate) are called twice which are creating new Thread or Runnable, AsyncTask in your case. (I believe this to be a bug in Android).
The solution is simple (though you may not like it :p)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
if(savedInstanceState == null){
// everything else that doesn't update UI
}
}
It seems you are getting multiple instance of your first activity. use this in manifest of 1st activity:
android:launchMode="singleTop"
else call finish() after doing startActivity() for 2nd activity
Related
I'm developing DES decryption in Android platform.
this is my main
package com.example.crack;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
public class Main extends Activity {
public final static String EXTRA_MESSAGE = "com.example.crack.MESSAGE";
public final static String EXTRA_PLAINTEXT = "com.example.crack.PLAINTEXT";
public final static int ENCRYPTION_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void sendMessage(View view) {
Intent intent = new Intent(this, encryption.class);
EditText editText = (EditText) findViewById(R.id.input_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivityForResult(intent, ENCRYPTION_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request it is that we're responding to
if (requestCode == ENCRYPTION_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
String result = data.getStringExtra(encryption.EXTRA_ENCRYPTION_RETURN);
Intent intent = new Intent(this, DisplayMessage.class);
intent.putExtra(EXTRA_MESSAGE, result);
startActivity(intent);
}
}
}
}
and this is the partial of my encrpytion
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.encryption);
Intent intent = getIntent();
message = intent.getStringExtra(Main.EXTRA_MESSAGE);
//Dictionary
is = getResources().openRawResource(R.raw.english);
in = new BufferedReader(new InputStreamReader(is));
readDic();
String result = "";
try {
result = decryptBruteForce();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent returnIntent = new Intent();
returnIntent.putExtra(EXTRA_ENCRYPTION_RETURN,result);
setResult(RESULT_OK,returnIntent);
finish();
}
when i click on the button, it calls the sendMessage function, while it is running the decryption the screen just black out until it finish running.
I had try using progress bar follow this guide, but not working, I need a button that can stop the process while running.
And is it possible to set a log on view, which show what the function is doing right now? like what is shown in the IDE log? Example, showing what key is the decryption trying right now.
Or maybe just a progress bar or please wait will do too.
I tried to change the sendMessage to this, yet it still black out and crash
public void sendMessage(View view) {
final Intent intent = new Intent(this, encryption.class);
view.setEnabled(false);
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
pd = new ProgressDialog(context);
pd.setTitle("Processing...");
pd.setMessage("Please wait.");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
}
#Override
protected Void doInBackground(Void... arg0) {
try {
//Do something...
EditText editText = (EditText) findViewById(R.id.input_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivityForResult(intent, ENCRYPTION_REQUEST);
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (pd!=null) {
pd.dismiss();
b.setEnabled(true);
}
}
};
task.execute((Void[])null);
}
if I put sleep to 50000, it did not crash, but still it black out.
You can do it with a Thread and a Handler. While you try each combination, you update the progress bar.
private int mProgressStatus = 0;
private Handler mHandler = new Handler();
protected void onCreate(Bundle savedInstanceState)
{
.... // Other initializations
mProgress = (ProgressBar) findViewById(R.id.progress_bar);
mProgress.setMax(dictionaryLength);
// Start lengthy operation in a background thread
new Thread(new Runnable() {
public void run() {
for (int i=0 ; i<dictionaryLength ; i++)
{
mProgressStatus = decryptBruteForce(i);
// Update the progress bar
mHandler.post(new Runnable() {
public void run() {
mProgress.setProgress(mProgressStatus);
}
});
}
}
}).start();
}
However i recommend you to use AsyncTask to do background operations while you need to update the UI to show the progress or info about whats going on.
http://developer.android.com/intl/es/reference/android/os/AsyncTask.html
Its a good habit to add a cancel control in your loop, so you can finish it from outside of the AsyncTask (for example another button in you UI).
private class DecryptTask extends AsyncTask<String, Integer, Long> {
protected Long doInBackground(String... words)
{
long wordsDecrypted = 0;
for (int i = 0; i < words.length ; i++) {
wordsDecrypted += decryptBruteForce(i);
publishProgress(i);
// Escape early if cancel() is called
if (isCancelled())
break;
}
return wordsDecrypted;
}
protected void onProgressUpdate(Integer... progress) {
mProgress.setProgress(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Decrypted " + result + " words");
}
}
And you can cancel the AsyncTask from outside with the cancel method:
http://developer.android.com/intl/es/reference/android/os/AsyncTask.html#cancel(boolean)
PD: Codes are not tested, just examples to show how it works
*I have class which load some files and update the UI...It takes some times to view the result,... So I want to add a loading bar or progress bar. Some data has been passed by other activity(Bundle extras1 = getIntent().getExtras();). But I am downloading one image per item... I think that takes more time. Any one can help me?
This is my code:
public class ShowSelectedEvents extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewdetailsevents);
Bundle extras1 = getIntent().getExtras();
String eventTitle = extras1.getString("eventTitle");
final String address = extras1.getString("address");
String date = extras1.getString("date");
String time = extras1.getString("time");
final String fix = extras1.getString("fix");
final String mobile = extras1.getString("mobile");
final String web = extras1.getString("web");
final String mail = extras1.getString("mail");
String imageLink = extras1.getString("imageLink");
final String videoLink = extras1.getString("videoLink");
// Add item image
Bitmap bitMap = null;
try {
bitMap = DownloadImage("imageLink);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ImageView imageItem = (ImageView) findViewById(R.id.imageItem);
imageItem.setImageBitmap(bitMap);
TextView viewTitle = (TextView) findViewById(R.id.viewTitle);
viewTitle.setText(eventTitle);
TextView viewDateTime = (TextView) findViewById(R.id.dateTime);
viewDateTime.setText("Event is on "+date +" # "+ time);
// View Address
TextView viewAdd = (TextView) findViewById(R.id.viewAddress);
viewAdd.setTypeface(Typeface.defaultFromStyle(Typeface.ITALIC),Typeface.ITALIC);
viewAdd.setText(address);
// On click open Navigation
if (!(address.equals("-"))){
ImageView navigationIcon = (ImageView) findViewById(R.id.imageMapNavigation);
navigationIcon.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String url = "google.navigation:q="+address;
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(i);
}
});
}else{
Context context = getApplicationContext();
CharSequence text = "Address is incomplete!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
// View Phone number
TextView viewPhoneNumber = (TextView) findViewById(R.id.viewPhoneNumber);
viewPhoneNumber.setTypeface(Typeface.defaultFromStyle(Typeface.ITALIC),Typeface.ITALIC);
viewPhoneNumber.setText(fix);
// On click open call
if (!(fix.equals("-"))){
viewPhoneNumber.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String url = "tel:"+fix;
Intent i = new Intent(Intent.ACTION_CALL, Uri.parse(url));
startActivity(i);
}
});
}
//View Mobile number
TextView viewMobileNumber = (TextView) findViewById(R.id.viewMobileNumber);
viewMobileNumber.setTypeface(Typeface.defaultFromStyle(Typeface.ITALIC),Typeface.ITALIC);
viewMobileNumber.setText(mobile);
// on click call mobile number
if (!(mobile.equals("-"))){
viewMobileNumber.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String url = "tel:"+mobile;
Intent i = new Intent(Intent.ACTION_CALL, Uri.parse(url));
startActivity(i);
}
});
}
//View web url
TextView viewWeb = (TextView) findViewById(R.id.viewWeb);
viewWeb.setTypeface(Typeface.defaultFromStyle(Typeface.ITALIC),Typeface.ITALIC);
viewWeb.setText(web);
//on click open web browser
if (!(web.equals("-"))){
viewWeb.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(web));
startActivity(i);
}
});
}
TextView viewMail = (TextView) findViewById(R.id.viewMailAddress);
viewMail.setTypeface(Typeface.defaultFromStyle(Typeface.ITALIC),Typeface.ITALIC);
viewMail.setText(mail);
if(!(mail.equals("-"))){
viewMail.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] {mail});
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Contact from tamilpage.ch");
emailIntent.setType("text/plain");
startActivity(Intent.createChooser(emailIntent, "Send a mail ..."));
}
});
}
// On click play the video
if (!(address.equals("-"))){
ImageView videoIcon = (ImageView) findViewById(R.id.videoButton);
videoIcon.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse(videoLink));
startActivity(browserIntent);
}
});
}else{
Context context = getApplicationContext();
CharSequence text = "No advert video for this event";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
private Bitmap DownloadImage(String url) throws Exception {
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(url);
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
private InputStream OpenHttpConnection(String url) throws Exception {
InputStream in = null;
int response = -1;
System.out.println("Nishi1");
URL url1 = new URL(url);
URLConnection conn = url1.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
System.out.println(in);
}
}
catch (Exception ex)
{
throw new IOException("Error connecting");
}
return in;
}
}
So I want to add a loading bar or progress bar
For your approach you need to use Threads. Especially i recommend to you have look at
Handler
AsyncTask
Both approaches offer work with Threads. AsyncTask is more complex than Handler also it's generic-type so offer more type-safe and faster work.
You should read some tutorials so
ProgressBar updating using Message Handler
Create A Custom Progress Bar Using
AsyncTask
And there is very awesome and useful tutorial at Vogella
Android Threads, Handlers and AsyncTask -
Tutorial
I would look at using AsyncTask. Here is a link that should help you get started: http://developer.android.com/reference/android/os/AsyncTask.html
The way you're going to want to do this is within an ASyncTask that has callbacks for updating a progress bar. I've included a sample below that doesn't actually do anything. You'd put your code for calling the download in doInBackground() and update the progress from onProgressUpdate.
public class BackgroundAsyncTask extends
AsyncTask<Void, Integer, Void> {
int myProgress;
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
Toast.makeText(AndroidAsyncTaskProgressBar.this,
"onPostExecute", Toast.LENGTH_LONG).show();
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
Toast.makeText(AndroidAsyncTaskProgressBar.this,
"onPreExecute", Toast.LENGTH_LONG).show();
myProgress = 0;
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
while(myProgress<100){
myProgress++;
publishProgress(myProgress);
SystemClock.sleep(100);
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
progressBar.setProgress(values[0]);
}
}
I currently have a listview and when you click on an item it runs a service with a mediaplayer. If I click on another item in the listview the service that's running should stop and run the new service. I am using a boolean isRunning set to false and when the service is created it returns true. Then in the listview I call that flag in an if statement. However, its not exactly working. I think I may be doing this wrong. Any ideas?
This probably sounds confusing the way I described it so Here is the code to my listview and my service. I am only testing this on case 3 (so I press this item to start the service and then click on case 2 to see if it will stop it).
Listview class:
public class PlaylistActivity extends ListActivity{
private static final String TAG = PlaylistActivity.class.getSimpleName();
// Data to put in the ListAdapter
private String[] sdrPlaylistNames = new String[] {
"Best of June 2011", "Best of May 2011", "Dubstep",
"House", "Other"};
private ListAdapter sdrListAdapter;
Intent playbackServiceIntentBOJ, playbackServiceIntentBOM, playbackServiceIntentDUB;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playlists_layout);
//fill the screen with the list adapter
playlistFillData();
playbackServiceIntentDUB = new Intent(this, DUBAudioService.class);
Log.d(TAG, "Made DUB Service Intent");
}
public void playlistFillData() {
//create and set up the Array adapter for the list view
ArrayAdapter sdrListAdapter = new ArrayAdapter(this, R.layout.list_item, sdrPlaylistNames);
setListAdapter(sdrListAdapter);
}
//set up the on list item Click
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
//create a switch so that each list item is a different playlist
switch(position){
case 0:
Intent BOJintent = new Intent(this, BOJAudioActivity.class);
// Create the view using PlaylistGroup's LocalActivityManager
View view = PlaylistGroup.group.getLocalActivityManager()
.startActivity("show_city", BOJintent
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView();
// Again, replace the view
PlaylistGroup.group.replaceView(view);
// playbackServiceIntentBOJ = new Intent(this, BOJAudioService.class);
Log.d(TAG, "Made BOJ Intent");
// startService(playbackServiceIntentBOJ);
Log.d(TAG, "started BOJ Service");
break;
case 1:
Intent BOMintent = new Intent(this, BOMAudioActivity.class);
// Create the view using PlaylistGroup's LocalActivityManager
View view2 = PlaylistGroup.group.getLocalActivityManager()
.startActivity("show_city", BOMintent
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView();
// Again, replace the view
PlaylistGroup.group.replaceView(view2);
Log.d(TAG, "Replace view");
//getApplicationContext().stopService(playbackServiceIntentBOJ);
//playbackServiceIntentBOM = new Intent(this, BOJAudioService.class);
Log.d(TAG, "Made BOM Service Intent");
// startService(playbackServiceIntentBOM);
Log.d(TAG, "started BOM Service");
if(DUBAudioActivity.isRunningDUB = true){
stopService(playbackServiceIntentDUB);
Log.d(TAG, "stop service isRunningDUB");
}
//
break;
case 2:
Intent DUBIntent = new Intent (this, DUBAudioActivity.class);
View view3 = PlaylistGroup.group.getLocalActivityManager()
.startActivity("show_city", DUBIntent
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView();
PlaylistGroup.group.replaceView(view3);
Log.d(TAG, "Replace view");
startService(playbackServiceIntentDUB);
Log.d(TAG, "started DUB service");
break;
}
}
}
Service Class:
public class DUBAudioService extends Service implements OnPreparedListener, OnCompletionListener{
Toast loadingMessage;
private static final String TAG = DUBAudioService.class.getSimpleName();
public static boolean isRunningDUB = false;
//to keep track of the playlist item
Vector<PlaylistFile> playlistItems;
MediaPlayer mediaPlayer;
String baseURL = "";
//keep track of which item from the vector we are on
int currentPlaylistltemNumber = 0;
public class DUBBackgroundAudioServiceBinder extends Binder {
DUBAudioService getService() {
return DUBAudioService.this;
}
}
private final IBinder basBinderDUB = new DUBBackgroundAudioServiceBinder();
#Override
public IBinder onBind(Intent intent) {
return basBinderDUB;
}
#Override
public void onCreate() {
Log.v("PLAYERSERVICE", "onCreate");
mediaPlayer = new MediaPlayer();
new MusicAsync().execute();
Log.d(TAG, "execute'd async");
mediaPlayer.setOnPreparedListener(this);
Log.d(TAG, "set on prepared listener");
mediaPlayer.setOnCompletionListener(this);
Log.d(TAG, "set on completion listener");
isRunningDUB = true;
Log.d(TAG, "isRunningRUB = true");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//if (!mediaPlayer.isPlaying()) {
// mediaPlayer.start();
//}
return START_STICKY;
}
class MusicAsync extends AsyncTask<Void,Void,Void>{
#Override
protected void onPreExecute(){
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
//create empty vector
playlistItems = new Vector<PlaylistFile>();
//HTTP client library
HttpClient httpClient = new DefaultHttpClient();
HttpGet getRequest = new HttpGet ("http://dl.dropbox.com/u/24535120/m3u%20playlist/DubstepPlaylist.m3u"); //i think you could add the m3u thing in here
Log.v("URI",getRequest.getURI().toString());
try {
HttpResponse httpResponse = httpClient.execute(getRequest);
if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
// ERROR MESSAGE
Log.v("HTTP ERROR",httpResponse.getStatusLine().getReasonPhrase());
}
else {
InputStream inputStream = httpResponse.getEntity().getContent();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bufferedReader.readLine()) != null) {
Log.v("PLAYLISTLINE","ORIG: " + line);
if (line.startsWith("#")) {
//Metadata
//Could do more with this but not fo now
} else if (line.length() > 0) {
String filePath = "";
if (line.startsWith("http://")) {
// Assume its a full URL
filePath = line;
} else {
//Assume it’s relative
filePath = getRequest.getURI().resolve(line).toString();
}
PlaylistFile playlistFile = new PlaylistFile(filePath);
playlistItems.add (playlistFile);
}
}
inputStream.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e. printStackTrace();
}
currentPlaylistltemNumber = 0;
if (playlistItems.size() > 0)
{
String path = ((PlaylistFile)playlistItems.get(currentPlaylistltemNumber)).getFilePath();
try {
mediaPlayer.setDataSource(path);
mediaPlayer.prepareAsync();}
catch (IllegalArgumentException e)
{ e.printStackTrace();
}catch (IllegalStateException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();}
}
return null;
}
//
protected void onPostExecute(Void result){
//playButton. setEnabled (false);
}
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
public void onDestroy() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
Log.d(TAG, "music stopp'd");
}
//mediaPlayer.release();
Log.d(TAG, "onDestroy");
}
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
// TODO Auto-generated method stub\
Log.d(TAG, "music is prepared and will start");
mediaPlayer.start();
}
public void onCompletion(MediaPlayer _mediaPlayer) {
Log.d(TAG, "Song completed, next song");
mediaPlayer.stop();
mediaPlayer.reset();
if (playlistItems.size() > currentPlaylistltemNumber + 1) {
currentPlaylistltemNumber++;
String path =
((PlaylistFile)playlistItems.get(currentPlaylistltemNumber)).getFilePath();
try {
mediaPlayer.setDataSource(path);
mediaPlayer.prepareAsync();
} catch (IllegalArgumentException e) {
e. printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class PlaylistFile {
String filePath;
public PlaylistFile(String _filePath) {
filePath = _filePath;
}
public void setFilePath(String _filePath) {
filePath = _filePath;
}
public String getFilePath() {
return filePath;
}
}
public void playSong(){
Log.d(TAG, "start'd");
mediaPlayer.start();
}
public void pauseSong(){
Log.d(TAG, "pause'd");
mediaPlayer.pause();
}
}
This gets pretty complicated but I used the following to see if my service was running:
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if ("com.example.MyService".equals(service.service.getClassName())) {
return true;
}
}
return false;
}
I added this in my listview class and put if statements in each case to see if it was running and if so would stop the service.
I also made my all of my binding conenctions public so that the listview class could access them and start them on click.
If anyone wants to further understand, etc message me.
let your app track the state, not your service.
private static String CONSUMER_KEY = "mrnCC41nxtwkdFAmToEhtg";
private static final String CONSUMER_SECRET = "kmmVuahEspGvdl14aCD1GSBZpeHbxvkpAez7aKaaQ";
EditText editPinCode;
LinearLayout lin;
public Logger slr;
LinearLayout container;
public LoginT(){
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.twitter);
editPinCode = new EditText(this);
lin = (LinearLayout)findViewById(R.id.LinearLayout01);
handleEvent = new Handler();
twitterConnection = new TwitterFactory().getInstance();
context = this;
oHelper = new OAuthHelp(this);
getTwitter(context);
}
/**
* Connects to twittter
* #param v
*/
public void getTwitter(Context ctx) { //updated code
handleEvent.post(new Runnable() {
// handleEvent.postAtFrontOfQueue(new Runnable() {
public void run() {
if (oHelper.hasAccessToken())
{
Log.e("run if","run");
oHelper.configureOAuth(twitterConnection);
try
{
i=i+1;
Log.e("run try","run");
twitterConnection.updateStatus(Calendar.MINUTE+i+"Hi this is Arun......");
//twitterConnection.se
Log.e("finish","start");
finish();
Log.e("finish","end");
}
catch (TwitterException e)
{
Log.d("TWEET", "Error Updating status " + e.getMessage());
e.printStackTrace();
}
}
else
{
Log.e("run else","run");
try {
twitterConnection.setOAuthConsumer(CONSUMER_KEY,CONSUMER_SECRET);
requestToken = twitterConnection.getOAuthRequestToken("");
Log.e("REQUEST_TOKEN",requestToken+"");
webViewDialog(requestToken.getAuthorizationURL(), 0);
}
catch (TwitterException e)
{
e.printStackTrace();
}
}
}});
}
/**
* Shows Dialog for authentications
*
* #param authorizationURL
* #param type
*/
private void webViewDialog(final String authorizationURL, final int type) {
Log.e("webViewDialog","webViewDialog");
container = new LinearLayout(this);
container.setMinimumWidth(200);
container.setMinimumHeight(320);
webView = new WebView(this);
webView.setMinimumWidth(200);
webView.setMinimumHeight(380);
webView.getSettings().setJavaScriptEnabled(true);
// webView.dispatchWindowFocusChanged(true);
webView.setWebViewClient(new MyWebViewClient(this,LoginT.this));
webView.loadUrl(authorizationURL);
container.addView(webView);
lin.addView(container);
// Builder webDialog = new AlertDialog.Builder(this);
// webDialog.setView(container).setTitle("Twitter Client").setCancelable(true)
// .show();
}
/**
* Pin code dialog Requests the user to enter pin shown on twitter
*/
public void twitterPinCodeDialog() {
try {
// accessToken = twitterConnection.getOAuthAccessToken(requestToken,ss);
try{
accessToken = twitterConnection.getOAuthAccessToken(requestToken);
}
catch(Exception e1){
Log.w("Excep e1",e1+"");
}
oHelper.storeAccessToken(accessToken);
Log.w("ohelper",oHelper.toString());
twitterConnection.updateStatus("Tweeted Successfully"+new Date().toString());
Log.e(" ","2 "+accessToken);
Log.e(" ","3");
webView.destroy();
webView.removeAllViews();
container.removeAllViews();
this.finish();
// Log.i("Access Token:", accessToken.getToken());
// Log.i("Access Secret:", accessToken.getTokenSecret());
} catch (TwitterException te) {
oHelper.storeAccessToken(accessToken);
try {
twitterConnection.updateStatus("HI.... ");
} catch (TwitterException e) {
e.printStackTrace();
}
}
}
#Override
protected Dialog onCreateDialog(int id)
{
switch (id) {
// case DIALOG_LOADING:
// {
// // dialog = new ProgressDialog(this);
// dialog.setMessage("Please wait while loading...");
// dialog.setIndeterminate(true);
// dialog.setCancelable(true);
// return dialog;
// }
}
return null;
}
//
// #Override
public void dismiss() {
Log.w("dismiss","dismiss");
try{
// webView.destroy();
// webView.removeAllViews();
// container.removeAllViews();
// this.finish();
System.exit(0);
}catch(Exception e){
e.printStackTrace();
}
}
//
#Override
public boolean onSearchRequested() {
Log.e("Search","Search");
return super.onSearchRequested();
}
I use the above Code for making connection for twitter but it only works for one time if I want another time for connection then it never provide me second time connection.
Thankx
Could this be an Activity lifecycle issue? Your call to getTwitter() occurs in onCreate, which only gets called when the Activity is created. If a user navigates away then comes back to your app, it may still be running, so onCreate would not get called again. Have a look at the Activity lifecycle, and add some debug code to each of the lifecycle methods (onResume, onPause etc) to get an idea of when they are called.
I am new to android. I have a loginActivity which validates a user number and then starts a "searchactivity".
At runtime, I see the search activity coming up (after user is validated) but then android is having problems stopping the loginActivity.
I am getting a "java.lang.runtimeexception: Unable to stop activity {com.insruance/com.insurance.LoginActivity}: android.app.SuperNotCalledException : Activity
at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:3413)"
I would really appreciate if someone could point to what I am doing wrong.
Code :
public class LoginActivity extends Activity{
DatabaseWrapper myDbHelper;
private String agentNumber;
private OnClickListener btnClickListner = new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
// = new DataBaseHelper();
try {
Log.d("LoginActivity->onClick", "Before findByID");
EditText editText = (EditText)findViewById(R.id.txtUserNumber);
Log.d("LoginActivity->onClick", "After findByID");
agentNumber = editText.getText().toString();
String msg = "";
AgentDbHelper agentHelper = new AgentDbHelper(myDbHelper.getDatabaseHandle());
Log.d("LoginActivity->onClick", "Before agentIDExists");
if (agentHelper.agentIDExists(agentNumber))
msg = "Login success";
else
msg = "Login failed";
Log.d("LoginActivity->onClick", "After agentByID");
myDbHelper.closeDatabase();
myDbHelper = null;
Toast.makeText(getBaseContext(),
"User " + agentNumber + " found!",
Toast.LENGTH_LONG).show();
callSearchActivity();
}
catch(SQLException sqlEx)
{
Log.d("login - onclick", sqlEx.toString());
}
catch (Exception e) {
// TODO: handle exception
Log.d("login - onclick", e.toString());
}
}
};
private void callSearchActivity()
{
Intent intent = new Intent(getBaseContext(), SearchActivity.class);
Bundle bun = new Bundle();
bun.putString("agentNumber", agentNumber);
intent.putExtras(bun);
startActivity(intent);
}
#Override
public void onStop() {
try {
Log.d("In LoginActivity->onStop", "about to close myDbHelper");
if (myDbHelper != null)
{
myDbHelper.closeDatabase();
Log.d("In LoginActivity->onStop", "after myDbHelper is closed");
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("In LoginActivity->onStop exeption", e.toString());
//e.printStackTrace();
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.login);
Button loginButton = (Button)this.findViewById(R.id.btnLogin);
loginButton.setOnClickListener(btnClickListner);
myDbHelper = new DatabaseWrapper(this);
myDbHelper.openDatabase();
}
catch(Exception e) {
Log.e("ERROR", "ERROR IN CODE:"+e.toString());
}
}
}
A little more digging pointed me to this.
I was not calling super.onStop() within the overriden onStop.
I would have thought that Eclipse would have scripted this line when it created the onStop for me.