Call SensorManager from AsyncTask? - android

How do I call the SensorManager from inside -
protected String doInBackground(String... params) {
.....
}
I have to log the acclerometer data on to a file. This application runs in the background. Hence I am using AsyncTask to implement it. I need to start and stop the logging by pressing the button (onClick). Any pointers would be helpful!!
This is the update... The file written is empty...How do I start the logging?
public class AsyncTaskActivity extends Activity implements SensorEventListener{
Button btn;
File root = Environment.getExternalStorageDirectory();
StringBuilder builder = new StringBuilder();
File gpxfile = new File(root, "TestFile.txt");
String fileText = "Data";
FileWriter gpxwriter;
BufferedWriter out;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
new LongOperation(new AsyncTaskActivity()).execute("");
}
});
}
private class LongOperation extends AsyncTask<String, Void, String> {
private AsyncTaskActivity mActivity;
public LongOperation (AsyncTaskActivity activity) {
mActivity = activity;
}
#Override
protected String doInBackground(String... params) {
try {
gpxwriter = new FileWriter(gpxfile);
out = new BufferedWriter(gpxwriter);
if (root.canWrite()){
SensorManager manager = (SensorManager) mActivity.getSystemService(Context.SENSOR_SERVICE);
Sensor accelerometer = manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
if(!manager.registerListener((SensorEventListener) this, accelerometer, SensorManager.SENSOR_DELAY_GAME)){
System.out.println("Could not start!!!!!!!!!");
}
out.write("Start");
out.newLine();
out.close();
}
} catch (IOException e) {
Log.e("doIn","Could not write file " + e.getMessage());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
TextView txt = (TextView) findViewById(R.id.output);
txt.setText("File written successfully!!!");
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
builder.setLength(0);
builder.append(event.values[0]+","+event.values[1]+","+event.values[2]);
try {
out.append(builder.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Pass the Activity Instance to the constructor of the AsyncTask and then access the Sensor Manager
class MyTask extends AsyncTask<URL, Integer, List> {
private MainActivity mActivity;
public MyTask(MainActivity activity) {
mActivity = activity;
}
protected List doInBackground(URL... url) {
SensorManager mSensorManager = (SensorManager)
mActivity.getSystemService(SENSOR_SERVICE)
....
return ..;
}
}

Related

Can't bind my app to sql server DB

hi this is a fragment but i tried it in an activity and it throw the same error i don't know what to do if the error has thrown because of my sql server or there is something i should do so i hope someone would help me
this is the exception :
04-16 07:53:06.693: E/Error(1144): Network error IOException: failed to connect to /10.0.2.2 (port 1433): connect failed: ETIMEDOUT (Connection timed out)
public class TopStories extends Fragment {
ListView lv = null;
Connection connx = null;
SimpleAdapter sa = null;
String sqlreq = "select * from news";
#SuppressLint("NewApi")
private Connection cnx() //connection to sqlserver
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection conn = null;
String ConnUrl = null;
try
{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
ConnUrl = "jdbc:jtds:sqlserver://10.0.2.2:1433/PFFDB;ssl=required";
conn=DriverManager.getConnection(ConnUrl);
} catch (SQLException e)
{
Log.e("Error", " "+e.getMessage());
}
catch (ClassNotFoundException e)
{
Log.e("Error", " "+e.getMessage());
}
catch (Exception e)
{
Log.e("Error", " "+e.getMessage());
}
return conn;
}
public void SqlQuery(String SqlCmnd)
{
connx = cnx();
ResultSet rs;
try
{
Statement stm = connx.createStatement();
rs = stm.executeQuery(SqlCmnd);
List<Map<String, String>> data = null;
data = new ArrayList<Map<String, String>>();
while (rs.next()) {
Map<String, String> datanum = new HashMap<String, String>();
datanum.put("A", rs.getString("title"));
datanum.put("B", rs.getString("idnews"));
data.add(datanum);
}
String[] from = {"A","B"};
int [] views ={R.id.Titleid,R.id.ArticleID};
sa = new SimpleAdapter(getActivity(), data, R.layout.model, from, views);
lv.setAdapter(sa);
}
catch (Exception e) {
Log.e("Error", " "+e.getMessage());
}
}
#SuppressWarnings("deprecation")
#Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
//newsv = new ArrayList<HashMap<String, String>>();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ListView lv = (ListView)getActivity().findViewById(R.id.listView1);
return inflater.inflate(R.layout.topstories, container,false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
SqlQuery(sqlreq);
}
#Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
#Override
public void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
#Override
public void onDestroyView() {
// TODO Auto-generated method stub
super.onDestroyView();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
#Override
public void onDetach() {
// TODO Auto-generated method stub
super.onDetach();
}
}

Android, will the socket close in service when activity destroy?

service code :
public class AlarmListeningService extends Service{
public static final String sHost = "*.*.*.*";
public static final int sPort = 5566;
Thread thrSocket;
#SuppressWarnings("deprecation")
public void onStartCommand(Intent intent, int startId) {
super.onStartCommand(intent, startId, startId);
thrSocket = new thrSocket();
thrSocket.start();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
class thrSocket extends Thread {
Socket mSocket;
public void run() {
InitSocket();
new Thread(){
public void run() {
try {
String msg = "";
while (true) {
int count = 0;
while (count == 0) {
count=ips.available();
}
byte[] serverdata = new byte[count];
ips.read(serverdata);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
}
private void InitSocket(){
try {
mSocket = new Socket(sHost,sPort);
OutputStream out=mSocket.getOutputStream();
byte[] b_client = "client".getBytes(Charset.forName("UTF-8"));
out.write(b_client);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
}
Activity code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent startAL = new Intent();
startAL.setClass(MainActivity.this, AlarmListeningService.class);
startService(startAL);
}
My question is will the socket in service close when I destroy the activity
(Observation at socket server)?
And the socket will re-connection in seconds to tens of seconds (Observation at socket server too)
How could I let the socket not close when I destroy the activity?

android radio streaming background and progress dialog

I am developing a Radio application in android that will stream from url and in background will show progress dialog loading streams but shows ANR. I am using service for mediaplayer to start and stop. Need help.I have used asynctask but can't get a solution.
MainActivity.class
button_Play.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
new DownloadTask().execute();
}
});
class DownloadTask extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute()
{
progressDialog = ProgressDialog.show(MainActivity.this , "Android Streaming
Player" , "Connecting to Stream..." , true , false);
Log.d("onPreExecute()----->" , "MainActivity.class");
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params)
{
Log.d("doInBackground()----->" , "MainActivity.class");
startService(new Intent(MainActivity.this , RadioService.class));
return null;
}
#Override
protected void onPostExecute(Void result)
{
Log.d("onPostExecute()----->" , "MainActivity.class");
progressDialog.dismiss();
super.onPostExecute(result);
}
}
Here is service class:
RadioService.class
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.d("onStartCommand------->", "RadioService.class");
try
{
Log.d("MediaPlayer--->TRY BLOCK", "MediaPlayer");
URL url2 = new URL("http://141.139.35.23:8000");
URLConnection urlConnection = url2.openConnection();
player.setDataSource(urlConnection.getURL().toString());
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.prepare();
Log.d("MediaPlayer--->TRY BLOCK AFTER ASYNC", "MediaPlayer");
player.setOnPreparedListener(new OnPreparedListener()
{
#Override
public void onPrepared(MediaPlayer mp)
{
Log.d("MediaPlayer--->ON PREPARED BEGINS", "MediaPlayer");
//mp.setOnErrorListener(MainActivity.this);
mp.start();
//mp.setOnErrorListener(this);
mp.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
Toast.makeText(getApplicationContext() , "Streaming started " , Toast.LENGTH_SHORT).show();
Log.d("MediaPlayer--->ON PREPARED ENDS", "MediaPlayer");
}
});
} catch (Exception e)
{
Log.i("Exception", "Exception in streaming mediaplayer e = " + e);
}
return START_STICKY;
//return super.onStartCommand(intent, flags, startId);
}
class Loading extends AsyncTask<Object, Object, Object>{
protected void onPreExecute(){
loadDialog.show();
}
#Override
protected Object doInBackground(Object... arg0) {
if(rFlag==false){
mediaPlayer = new MediaPlayer();
try{
url = "rtsp://ra.dio";
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(url);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (Exception e) {
loadDialog.dismiss();
errmsg = "error";
// TODO: handle exception
}
while(rFlag==false){
mediaPlayer.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer arg0, int arg1) {
// TODO Auto-generated method stub
if(arg1 >= 98){
loadDialog.dismiss();
rFlag=true;
}
}
});
}
}
else if(rFlag==true){
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer=null;
rFlag=false;
}
return null;
}
#Override
protected void onPostExecute(Object result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// loaded
}
}

Android: AsyncTask timeout

Is it possible to do splash screen that will execute HTTP request and if this request is executing too long, i.e. 7-10 seconds, then abort the request and jump to the main activity?
The below code is what I did, but it doesn't work - the timeout isn't working, the HTTP request and jumping are working. As I understand, it's possible to use the AsyncTask's get() method or handler with delay. Get() method should be in separate thread but it doesn't work. How to do this task?
EDIT:
public class SplashActivity extends Activity {
private static final String TAG = "SplashActivity";
private Handler handler = new Handler();
private Runnable r;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_layout);
if (Helpers.isNetworkConnected(getApplicationContext())) {
Log.d(TAG, "Has Internet");
final DownloadFAQ downloadFAQ = new DownloadFAQ();
new Thread(new Runnable() {
public void run() {
try {
Log.d(TAG, "Timing...");
downloadFAQ.execute().get(1000, TimeUnit.MILLISECONDS);
SplashActivity.this.runOnUiThread(new Runnable() {
public void run() {
Log.d(TAG, "redirect");
redirect();
}
});
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
downloadFAQ.cancel(true);
Log.d(TAG, "Task has benn canceled");
if (downloadFAQ.isCancelled())
redirect();
}
}
}).start();
} else {
r = new Runnable() {
public void run() {
redirect();
}
};
handler.postDelayed(r, 2500);
}
}
private class DownloadFAQ extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
Log.d(TAG, "Execute task");
ServerAPI server = new ServerAPI(getApplicationContext());
server.serverRequest(ServerAPI.GET_FAQ, null);
return null;
}
}
private void redirect() {
Intent i = new Intent(SplashActivity.this, TabsActivity.class);
startActivity(i);
finish();
}
#Override
protected void onDestroy() {
super.onDestroy();
handler.removeCallbacks(r);
}
}
because you are trying to start AsyncTask again inside doInBackground when it's still running . change your code as to get it work :
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_layout);
downloadFAQ = new DownloadFAQ();
new Thread(new Runnable() {
public void run() {
try {
downloadFAQ.execute().get(2000, TimeUnit.MILLISECONDS);
SplashActivity.thisrunOnUiThread(new Runnable() {
public void run() {
// start Activity here
Intent i = new Intent(SplashActivity.this,
TabsActivity.class);
SplashActivity.this.startActivity(i);
SplashActivity.this.finish();
}
});
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TimeoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
and you will need to remove downloadFAQ.get(2000, TimeUnit.MILLISECONDS); from doInBackground method change your AsyncTask as
private class DownloadFAQ extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
ServerAPI server = new ServerAPI(getApplicationContext());
server.serverRequest(ServerAPI.GET_FAQ, null);
return null;
}
protected void onPostExecute(Void result) {
}
}
consider using asyncTask status:
AsyncTask.Status

Using wait in AsyncTask

When using a wait in an AsyncTask, I get ERROR/AndroidRuntime(24230): Caused by: java.lang.IllegalMonitorStateException: object not locked by thread before wait()
Is it possible to use an Asynctask just for waiting? How?
Thanks
class WaitSplash extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
try {
wait(MIN_SPLASH_DURATION);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute() {
waitSplashFinished = true;
finished();
}
}
Use Thread.sleep() instead of wait().
You can use Thread.sleep method
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
Thread.currentThread();
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
If you're looking to just postpone execution of a method for a set amount of time, a good option is Handler.postDelayed()
define the handler and runnable...
private Handler handler = new Handler();
private Runnable runnable = new Runnable() {
finished();
};
and execute with delay...
handler.postDelayed(runnable, MIN_SPLASH_DURATION);
Use threads for this
public class SplashActivity extends Activity{
int splashTime = 5000;
private Thread splashThread;
private Context mContext;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.mContext = this;
setContentView(R.layout.splash_layout);
splashThread = new Thread(){
public void run() {
try{
synchronized (this) {
wait(splashTime);
}
}catch(InterruptedException ex){
ex.printStackTrace();
}finally{
Intent i = new Intent(mContext,LocationDemo.class);
startActivity(i);
stop();
}
}
};
splashThread.start();
}
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
synchronized (splashThread) {
splashThread.notifyAll();
}
}
return true;
}
on touch event, thread get notified.. can change according to your need.
You have this way to work with asyntask and wait();
public class yourAsynctask extends AsyncTask<Void, Void, Void> {
public boolean inWait;
public boolean stopWork;
#Override
protected void onPreExecute() {
inWait = false;
stopWork = false;
}
#Override
protected Void doInBackground(Void... params) {
synchronized (this) {
while(true) {
if(stopWork) return null;
if(youHaveWork) {
//make some
} else {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
return null;
}
public void mynotify() {
synchronized (this) {
if(inWait) {
notify();
inWait = false;
}
}
}
public void setStopWork() {
synchronized (this) {
stopWork = false;
if(inWait) {
notify();
inWait = false;
}
}
}
}

Categories

Resources