How to call a webservice continuously in every seconds? - android

allVehiclesSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
String item=allVehiclesSpinner.getItemAtPosition(position).toString();
if(!item.equalsIgnoreCase("Select")){
position=0;
vdetails.vehicleNo = item;
dbhHelper.opendatabase();
vdetails=dbhHelper.getVehicleId(item);
dbhHelper.close();
getLiveTrackingsAsyncTask livetask=new getLiveTrackingsAsyncTask();
livetask.execute();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
public class getLiveTrackingsAsyncTask extends AsyncTask<String, Void, String> {
private ProgressDialog Dialog;
#Override
protected void onPreExecute() {
Dialog = new ProgressDialog(VTS_LiveTracking.this);
Dialog.setMessage(VTS_LiveTracking.this.getResources().getString(
R.string.loading));
Dialog.setCanceledOnTouchOutside(false);
Dialog.show();
Dialog.setContentView(R.layout.progress);
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String result="";
Log.d(WebServiceHelper.TAG, "AsyncTask>>>>>>>>>>>");
if(isInternetPresent){
try {
Log.d(WebServiceHelper.TAG, "AsyncTask CHeck Internet>>>>>>>>>>>");
Log.d(WebServiceHelper.TAG, "VehicleId CHeck Internet>>>>>>>>>>>"+vdetails.vehicleId);
vd=WebServiceHelper.getLiveTrackingDetails(ClientCode, SecretCode, vdetails.vehicleId);
//vd=WebServiceHelper.getLiveTrackingDetails(ClientCode, SecretCode, "2");
Log.d(WebServiceHelper.TAG, "VD>>>>>>>>"+vd.length);
for(int i=0;i<vd.length;i++){
Log.d(WebServiceHelper.TAG, "LiveTrackingElements1>>>>>>>>>>>>>>"+vd[i].deviceMobNo);
Log.d(WebServiceHelper.TAG, "LiveTrackingElements2>>>>>>>>>>>>>>"+vd[i].driverName);
vdetails.latitude=vd[i].latitude;
vdetails.longitude=vd[i].longitude;
Log.d(WebServiceHelper.TAG, "vdetails.latitudeLiveTrackingElements1>>>>>>>>>>>>>>"+vdetails.latitude);
Log.d(WebServiceHelper.TAG, "vdetails.longitudeLiveTrackingElements2>>>>>>>>>>>>>>"+vdetails.longitude);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
result="Success";
}else{
result="Failure";
}
return result;
}
#Override
protected void onPostExecute(String result) {
if(result.contentEquals("Success")){
Log.d(WebServiceHelper.TAG, "AsyncTaskonPostExecute>>>>>>>>>>>");
Log.d(WebServiceHelper.TAG, "statuslogin>>>>>>>>>>>"+vdetails.status_login);
if(vdetails.status_login.equals("success")){
String lat=vdetails.latitude;
String lon=vdetails.longitude;
latitude=Double.parseDouble(vdetails.latitude);
longitude=Double.parseDouble(vdetails.longitude);
Log.d(WebServiceHelper.TAG, "latitude>>>>"+vdetails.latitude);
Log.d(WebServiceHelper.TAG,"longitude>>>>"+vdetails.longitude);
latlng=new LatLng(latitude, longitude);
Marker m=map.addMarker(new MarkerOptions().position(latlng));
map.animateCamera(CameraUpdateFactory.newLatLngZoom(latlng, 15.0f));
map.setOnMarkerClickListener(new OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
final Dialog dialog = new Dialog(VTS_LiveTracking.this);
dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("Report");
TextView driver, speed,latitude,longitude,last_updated_time,gps_status,
driver_mobile_no,vehicle_idle_status,ac_status,device_mobile_no,engine_status;
driver = (TextView)dialog.findViewById(R.id.drivernametxt);
speed=(TextView)dialog.findViewById(R.id.speedvaluetxt);
latitude=(TextView)dialog.findViewById(R.id.latitudetxt);
longitude=(TextView)dialog.findViewById(R.id.longitudetxt);
last_updated_time=(TextView)dialog.findViewById(R.id.last_updated_timetxt);
gps_status=(TextView)dialog.findViewById(R.id.gps_statustxt);
driver_mobile_no=(TextView)dialog.findViewById(R.id.driver_mobile_notxt);
vehicle_idle_status=(TextView)dialog.findViewById(R.id.vehicle_idle_statustxt);
ac_status=(TextView)dialog. findViewById(R.id.ac_statustxt);
device_mobile_no=(TextView)dialog.findViewById(R.id.device_mobile_notxt);
engine_status=(TextView)dialog.findViewById(R.id.engine_statustxt);
driver.setText(vdetails.driverName);
speed.setText(vdetails.vehicleSpeed);
latitude.setText(vdetails.latitude);
longitude.setText(vdetails.longitude);
last_updated_time.setText(vdetails.lastUpdatedDateTime);
gps_status.setText(vdetails.gpsStatus);
driver_mobile_no.setText(vdetails.driverMobNo);
vehicle_idle_status.setText(vdetails.vehicleIdleStatus);
ac_status.setText(vdetails.acStatus);
device_mobile_no.setText(vdetails.deviceMobNo);
engine_status.setText(vdetails.engineStatus);
dialog.show();
Button cancel=(Button) dialog.findViewById(R.id.okbtn);
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
return false;
}
});
}else{
Toast.makeText(getApplicationContext(), vdetails.failReason, Toast.LENGTH_LONG).show();
}
}else if(result.contentEquals("Failure")){
Toast.makeText(getApplicationContext(), "Error in Login", Toast.LENGTH_LONG).show();
}
super.onPostExecute(result);
Dialog.dismiss();
Dialog=null;
}
}
}
Hi,
For my app,It is very necessary to display the location of a vehicle at a particular location.The location of the vehicle is given by the json webservices.Also the vehicle is moving and location is updated by the webservice.But according to my code the vehicle is not moving.How can I implement the movement of vehicle in my app?How can I implement the location change using timer?Is there any other methods to implement this?
Please help me
Here is my code

Use Timer..
mytimer = new Timer();
final TimerTask mytask = new TimerTask() {
public void run() {
//your code here
}
});
mytimer.scheduleAtFixedRate(mytask, int delay, int time);

Class To Start Service
allVehiclesSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
String item=allVehiclesSpinner.getItemAtPosition(position).toString();
if(!item.equalsIgnoreCase("Select")){
position=0;
vdetails.vehicleNo = item;
dbhHelper.opendatabase();
vdetails=dbhHelper.getVehicleId(item);
dbhHelper.close();
Intent intent = new Intent(A.this,
Service_A.class);
startService(intent);
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
USE SERVICE TO UPDATE WEBSERVICE AFTER 1 SEC
Service_ A extend service
{
private Handler handler = new Handler();
#Override
public void run() {
// TODO Auto-generated method stub
handler.postDelayed(Service_ A.this,1000);
}
//do you code
}

Try to use thread to invoke async task every second use below code to replace
getLiveTrackingsAsyncTask livetask=new getLiveTrackingsAsyncTask();
livetask.execute();
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(1 * 1000);
new getLiveTrackingsAsyncTask.execute();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();

Related

Use Multiple Android Activities

Anyone can help me to debug where I m going wrong. Test Code may get from:
https://drive.google.com/file/d/0Bz1lc03pNQm6Qkw3bE93dWxjdXc/view?usp=sharing
Scenario, I have 3 activities
Main, Splash and menu. First I call Splash activity for 5 seconds after 5 seconds I call menu activity its not working from menu I want to call Main activity. If I skip Menu activity than its working fine.
Splash Activity
public class Splash extends Activity{
MediaPlayer ourSong;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
ourSong = MediaPlayer.create(Splash.this, R.raw.dj);
ourSong.start();
Thread timer = new Thread()
{
public void run()
{
try
{
sleep(5000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
finally
{
Intent start = new Intent("com.example.test.menu");
startActivity(start);
}
}
};
timer.start();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
ourSong.release();
finish();
}
}
Menu Activity
public class menu extends ListActivity{
String classes[] = {"MainActivity", "example1", "example1", "example1", "example1"};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(menu.this, android.R.layout.simple_list_item_1, classes));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
String cheese = classes[position];
try
{
Class ourclass = Class.forName("com.example.test."+cheese);
Intent ourIntent = new Intent(menu.this, ourclass);
startActivity(ourIntent);
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
}
}
Main Activity
public class MainActivity extends Activity {
int counter;
Button add, subtruct;
TextView textarea;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counter = 0 ;
add = (Button)findViewById(R.id.button1);
subtruct = (Button)findViewById(R.id.button2);
textarea = (TextView)findViewById(R.id.textView1);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
textarea.setText("Your total is"+counter);
}
});
subtruct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter--;
textarea.setText("Your total is"+counter);
}
});
}
}
Your code:
Thread timer = new Thread()
{
public void run()
{
try
{
sleep(5000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
finally
{
Intent start = new Intent("com.example.test.menu");
startActivity(start);
}
}
};
timer.start();
Right code:
Thread timer = new Thread()
{
public void run()
{
try
{
sleep(5000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
finally
{
Intent start = new Intent(Splash.this, menu.class);
startActivity(start);
}
}
};
timer.start();
Tip: Don't use lowerCase for Class Names

Android: Not able to store location in SharedPreference

Here, I'm using the current location of the user as well as the a location which is stored previously and showing path between them.
I'm able to get the correct current location but the location I'm trying to store permanently in Shared Preferences are just getting stored until application is running. Once the application is removed and opened again the saved location gets initialised back to 0.0.
I want to store latitude and longitude permanently once after user press save/change location button.
Here's the code:
public class Fragment_ReachHome extends Fragment {
WebView wv;
ProgressDialog pg;
Background bg;
AlertDialog.Builder alert;
ConnectionDetector cd;
MediaPlayer exceptionNotifier;
boolean isInternetPresent = false;
LocationManager locationManager;
LocationListener locationListener;
float latitude;
float longitude;
Location loc;
public static float savelati, savelongi;
Boolean islocationmanagerrequested = false;
Button bsaveorchangeloc, bshowsavedloc;
SharedPreferences pref;
SharedPreferences.Editor edit;
Boolean islocsaved = false, isbpressed = false;
public Fragment_ReachHome() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_reach_home, container, false);
wv=(WebView)rootView.findViewById(R.id.webView1);
alert = new AlertDialog.Builder(getActivity());
cd = new ConnectionDetector(getActivity());
locationManager = (LocationManager) getActivity()
.getSystemService(Context.LOCATION_SERVICE);
Toast.makeText(getActivity(), "Loading... Please Wait..", Toast.LENGTH_LONG).show();
locationListener = new LocationListener() { //-----X0-- THIS SHOULD ALWAYS COME FIRST THEN X1 SHOULD BE WRITTEN
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
loc = location;
latitude = Float.valueOf((float) loc.getLatitude());
longitude = Float.valueOf((float) loc.getLongitude());
if(isbpressed){
Toast.makeText(getActivity(), "on loc change", Toast.LENGTH_LONG).show();
}
bg = new Background();
bg.execute();
}
};
try {
isInternetPresent = cd.isConnectingToInternet();
} catch (Exception e) {
Toast.makeText(getActivity(), e.toString(),
Toast.LENGTH_LONG).show();
}
if(isInternetPresent){
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0,
locationListener);
}else{
exceptionNotifier = MediaPlayer.create(getActivity(), R.raw.notify);
exceptionNotifier.start();
alert.setTitle("Alert!");
alert.setMessage("Internet Not Present..! ");
alert.setCancelable(true);
alert.setPositiveButton("Ok!",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
exceptionNotifier.release();
}
}).show();
}
pref = this.getActivity().getSharedPreferences("", 0);
edit=pref.edit();
bsaveorchangeloc =(Button)rootView.findViewById(R.id.button1);
bshowsavedloc =(Button)rootView.findViewById(R.id.button2);
islocsaved = pref.getBoolean("locsaved", false);
bsaveorchangeloc.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
progress();
try {
isInternetPresent = cd.isConnectingToInternet();
} catch (Exception e) {
Toast.makeText(getActivity(), e.toString(),
Toast.LENGTH_LONG).show();
}
if(isInternetPresent){
//ONLY AFTER X0 THIS MUST BE WRITTEN
Toast.makeText(getActivity(), "Saving Location!!", Toast.LENGTH_LONG).show();
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0,
locationListener);
isbpressed = true;
islocationmanagerrequested = true;
savelati = pref.getFloat("latestlati", Float.valueOf((float) loc.getLatitude())); //giving default value as 0
savelongi= pref.getFloat("latestlongi", Float.valueOf((float) loc.getLatitude()));
edit.putBoolean("locsaved", true);
edit.commit();
if(islocationmanagerrequested){
locationManager.removeUpdates(locationListener);
}
pg.dismiss();
}else{
exceptionNotifier = MediaPlayer.create(getActivity(), R.raw.notify);
exceptionNotifier.start();
alert.setTitle("Alert!");
alert.setMessage("Internet Not Present..! ");
alert.setCancelable(true);
alert.setPositiveButton("Ok!",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
exceptionNotifier.release();
}
}).show();
}
}
});
bshowsavedloc.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), savelati+","+savelongi, Toast.LENGTH_LONG).show();
}
});
wv.getSettings().setJavaScriptEnabled(true);
wv.getSettings().setLoadWithOverviewMode(true);
wv.getSettings().setUseWideViewPort(true);
wv.getSettings().setBuiltInZoomControls(true);
wv.setWebViewClient(new MyWebClient());
return rootView;
}
public void progress(){
pg = new ProgressDialog(getActivity());
pg.setTitle("");
pg.setMessage("Please Wait.........");
pg.setCancelable(false);
pg.setIndeterminate(true);
pg.show();
}
class Background extends AsyncTask<Void, Void, Void>
{
#SuppressLint("SetJavaScriptEnabled")
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
try{
if(islocsaved){
wv.loadUrl("http://maps.google.com/maps?saddr="+savelati+","+savelongi+"&daddr="+loc.getLatitude()+","+loc.getLongitude());
}else{
pg.dismiss();
exceptionNotifier = MediaPlayer.create(getActivity(), R.raw.notify);
exceptionNotifier.start();
alert.setTitle("Alert!");
alert.setMessage("Your home location is not saved yet..! ");
alert.setCancelable(true);
alert.setPositiveButton("Ok!",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
exceptionNotifier.release();
}
}).show();
}
}catch(Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
Toast.makeText(getActivity(), latitude+","+longitude, Toast.LENGTH_LONG).show();
locationManager.removeUpdates(locationListener);
}
#Override
protected void onPreExecute() {
progress();
}
}
public class MyWebClient extends WebViewClient
{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
pg.dismiss();
}
}
}
Please let me know the correct changes in the code to get store the location permanently...
You can saved value in preference on onPause() or any Button click event where you want using below code.
edit.putFloat("latestlati", Float.valueOf((float) loc.getLatitude()))
edit.putFloat("latestlongi", Float.valueOf((float) loc.getLatitude()));
edit.putBoolean("locsaved", true);
edit.commit();
You can get saved value from preference on onResume() using below code.
savelati = pref.getFloat("latestlati", 0.0);
savelongi= pref.getFloat("latestlongi", 0.0);
islocsaved=edit.getBoolean("locsaved", true);
and for more information go to Android Shared preferences example or http://www.vogella.com/tutorials/AndroidFileBasedPersistence/article.html
You need to save the value of longitide and latitude first in the shareprefrences.
edit.putFloat("latestlati", Float.valueOf((float) loc.getLatitude());
edit.putFloat("latestlongi", Float.valueOf((float) loc.getLongitude);
For the better suggestion you have to take your SharedPreferance instance globally
then in your onLocationChanged(Location location) change method you can do this code
edit.putFloat("latestlati", Float.valueOf((float) loc.getLatitude()))
edit.putFloat("latestlongi", Float.valueOf((float) loc.getLatitude()));
edit.putBoolean("locsaved", false);
edit.commit();
So, that every location change your value for the location is updated and after come to your activity you always get the refresh/latest value.
with onCreate() or onResume() you can get the
savelati = pref.getFloat("latestlati", 0.0);
savelongi= pref.getFloat("latestlongi", 0.0);
islocsaved=edit.getBoolean("locsaved", false);

Android Facebook sdk friend list in listview

I need to show my facebook friends in listview..
my code is here..
when i launch it in emulator it stop working..
pls help me...
I need to show my facebook friends in listview..
my code is here..
when i launch it in emulator it stop working..
pls help me...
i refer code is [1]: http://pastebin.com/5fCRxtL
public class LoginActivity extends Activity{
private static final String[] PERMISSIONS = new String[] {"publish_stream","publish_checkins", "read_stream", "offline_access"};
public static final String APP_ID = "**************";
private Facebook facebook = new Facebook(APP_ID);
private AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
private ProgressDialog mProgress;
private Handler mHandler = new Handler();
private ProgressDialog mSpinner;
private Handler mRunOnUi = new Handler();
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
public static ArrayList<String> friends ;
String _error;
// private FriendsArrayAdapter friendsArrayAdapter;
// SharedPreferences.Editor editor;
TextView tv;
Button loginButton;
private UiLifecycleHelper uiHelper;
private ContextWrapper uiActivity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
setContentView(R.layout.login);
friends= new ArrayList<String>();
tv=(TextView)LoginActivity.this.findViewById(R.id.textview1);
loginButton=(Button)findViewById(R.id.button_login);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (! facebook.isSessionValid()) {
facebook.authorize(LoginActivity.this, PERMISSIONS, new LoginDialogListener());
}
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d("FB Demo App", "onActivityResult(): " + requestCode);
facebook.authorizeCallback(requestCode, resultCode, data);
}
private class LoginDialogListener implements DialogListener {
public void onComplete(Bundle values) {
saveCredentials(facebook);
getAlbumsData task = new getAlbumsData();
task.execute();
mHandler.post(new Runnable() {
public void run() {
//--- Intent i = new Intent(LoginActivity.this,FrndActivity.class);
//--- i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//--- startActivity(i);
}
});
mAsyncRunner.request("me/friends", new FriendsRequestListener());
}
private void saveCredentials(Facebook facebook) {
// TODO Auto-generated method stub
}
public void onFacebookError(FacebookError error) {
showToast("Authentication with Facebook failed!");
}
public void onError(DialogError error) {
showToast("Authentication with Facebook failed!");
}
public void onCancel() {
showToast("Authentication with Facebook cancelled!");
}
}
public void showToast(String string) {
// TODO Auto-generated method stub
}
public class getAlbumsData {
public void execute() {
// TODO Auto-generated method stub
}
}
private class FriendsRequestListener implements RequestListener {
String friendData;
//Method runs when request is complete
public void onComplete(String response, Object state) {
Log.v("", "FriendListRequestONComplete");
//Create a copy of the response so i can be read in the run() method.
friendData = response;
Log.v("friendData--", ""+friendData);
//Create method to run on UI thread
LoginActivity.this.runOnUiThread(new Runnable() {
public void run() {
try {
//Parse JSON Data
JSONObject json;
json = Util.parseJson(friendData);
//Get the JSONArry from our response JSONObject
JSONArray friendArray = json.getJSONArray("data");
Log.v("friendArray--", ""+friendArray);
for(int i = 0; i< friendArray.length(); i++)
{
JSONObject frnd_obj = friendArray.getJSONObject(i);
friends.add(frnd_obj.getString("name")+"~~~"+frnd_obj.getString("id"));
}
Intent ide = new Intent(LoginActivity.this,FrndActivity.class);
ide.putStringArrayListExtra("friends", friends);
// ide.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(ide);
// ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1,android.R.id.text1, friends_list);
// lv.setAdapter(adapter);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FacebookError e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
#Override
public void onIOException(IOException e, Object state) {
// TODO Auto-generated method stub
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
// TODO Auto-generated method stub
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
// TODO Auto-generated method stub
}
#Override
public void onFacebookError(FacebookError e, Object state) {
// TODO Auto-generated method stub
}
}
Please pay attention...the AsyncFacebookRunner is deprecated,as it's shown on the Facebook documentation.
https://developers.facebook.com/docs/reference/android/current/AsyncFacebookRunner/

Running SoundPool on Background with AsyncTask

I am trying to play 5 SoundPool one after the other on Background using AsyncTask for it. But I wanna click an ImageView while sounds are running. The problem begins when SoundPool uses getBaseContext() that blocks my ImageView while doInBackground is running.
Does anyone know whats happening?
Thxs a lot!
Here is my code:
public class SensoriomotoraActivity extends Activity {
private boolean playing = false ;
private ImageView image ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sensoriomotora);
image = (ImageView) findViewById(R.id.img_sensoriomotora_pandereta);
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (playing){
Log.v("onClick","clicked while playing");
}
else {
Log.v("onClick","clicked while !playing");
}
}
});
new Thread (
new Runnable(){
#Override
public void run(){
// Waiting 2.5 secs before playing the beeps
try {
Thread.sleep(2500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
new PlaySoundBackground().execute();
}
});
}
}
).start();
}
private class PlaySoundBackground extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute() {
playing = true ;
}
#Override
protected Void doInBackground(Void... params) {
SoundPool sound;
sound = new SoundPool(1, AudioManager.STREAM_MUSIC,0);
sound.load(getBaseContext(), R.raw.beep, 1);
sound.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
#Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
for (int i=0 ; i<5; i++){
soundPool.play(sampleId, 1, 1, 1, 0, 1);
try {
Thread.sleep(2000); // Waits 2 secs before next beep
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
return null;
}
#Override
protected void onPostExecute(Void result) {
playing = false ;
}
}
}

How to show seekbar along with the custom mediaplayer

i have build a custom media player and i want to show the seekbar also.
The seekbar is showing for now but is not functional i.e. it is not progressing when the song is played. Let me know where am i wrong . Following is the code
public class myPlayer extends Activity implements Runnable,SeekBar.OnSeekBarChangeListener {
MediaPlayer mPlayer;
Button play,stop;
SeekBar seekbar;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
seekbar = (SeekBar)findViewById(R.id.seekbar);
mPlayer = MediaPlayer.create(this,R.raw.sajnave);
play=(Button)findViewById(R.id.play);
stop=(Button)findViewById(R.id.stop);
Toast.makeText(myPlayer.this, ""+mPlayer.getDuration(), Toast.LENGTH_SHORT).show();
play.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mPlayer.start();
}
});
stop.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(myPlayer.this, ""+mPlayer.getCurrentPosition(), Toast.LENGTH_SHORT).show();
mPlayer.stop();
}
});
}
#Override
public void run() {
// TODO Auto-generated method stub
int currentPosition = 0;
int total = mPlayer.getDuration();
seekbar.setMax(total);
while (mPlayer != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = mPlayer.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seekbar.setProgress(currentPosition);
}
}
#Override
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
// TODO Auto-generated method stub
mPlayer.seekTo(arg1);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}
Call updatePosition() method after mediplayer starts..It works for me.
private final Handler handler = new Handler();
private final Runnable updatePositionRunnable = new Runnable() {
public void run() {
updatePosition();
}
};
private void updatePosition() {
handler.removeCallbacks(updatePositionRunnable);
if (player != null) seekbar.setProgress(player.getCurrentPosition());
handler.postDelaye(updatePositionRunnable, 500);
}
#Override
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
// TODO Auto-generated method stub
player.seekTo(arg1);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
SurfaceView mPreview=(SurfaceView)findViewById(R.id.surface);
mPreview.postDelayed(runnable,200);
Runnable runnable = new Runnable() {
#Override
public void run() {
if (mMediaPlayer != null) {
if (isPlaying) {
// converting current position into seconds so dividing by
// 1000
try {
currentPosition = mMediaPlayer.getCurrentPosition();
mVideoProgress
.setProgress((int) ((currentPosition / (float) mMediaPlayer
.getDuration()) * 100f));
} catch (Exception e) {
e.printStackTrace();
}
mPreview.postDelayed(runnable, 150);
}
}
}
};

Categories

Resources