Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class OtgService extends Service
- {
- private boolean mOtgConnected = false;
- private Handler mHandler;
- Timer taskTimer = new Timer();
- TimerTask task = new TimerTask()
- {
- private int last_Length = -1;
- @Override
- public void run()
- {
- Context context = OtgService.this.getBaseContext();
- File directory = new File("/sys/bus/usb/devices");
- File[] contents = directory.listFiles();
- int conn_length = contents.length;
- if(conn_length ==last_Length)
- {
- return;
- }
- else
- {
- last_Length = conn_length;
- }
- if(conn_length == 0)
- {
- mOtgConnected = false;
- mHandler.post(flagChangedTask);
- }
- else if (conn_length > 0) //Might get a -1
- {
- mOtgConnected = true;
- mHandler.post(flagChangedTask);
- }
- if(conn_length == 0)
- {
- displayDialog(false);
- }
- else if (conn_length > 0) //Might get a -1
- {
- displayDialog(true);
- }
- }
- };
- //Will post this to the main thread
- Runnable flagChangedTask = new Runnable()
- {
- @Override
- public void run()
- {
- if (mOtgConnected)
- Toast.makeText(OtgService.this,"otg connected",Toast.LENGTH_SHORT).show();
- else
- Toast.makeText(OtgService.this,"otg not connected",Toast.LENGTH_SHORT).show();
- }
- };
- public OtgService()
- {
- }
- public void displayDialog(boolean isConnected)
- {
- Intent intent = new Intent(this, MainActivity.class);
- intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
- intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- intent.putExtra(MainActivity.IS_CONNECTED_KEY, isConnected);
- startActivity(intent);
- }
- private void onStartCompat(Intent intent)
- {
- Log.e("###", "Starting service!");
- if (mHandler == null)
- mHandler = new Handler(getMainLooper());
- taskTimer.scheduleAtFixedRate(task, 0, 1000);
- }
- // This is the old onStart method that will be called on the pre-2.0
- // platform. On 2.0 or later we override onStartCommand() so this
- // method will not be called.
- @Override
- public void onStart(Intent intent, int startId)
- {
- onStartCompat(intent);
- }
- @Override
- public int onStartCommand(Intent intent, int flags, int startId)
- {
- onStartCompat(intent);
- // We want this service to continue running until it is explicitly
- // stopped, so return sticky.
- return START_STICKY;
- }
- @Override
- public void onDestroy()
- {
- //task.cancel();
- }
- @Override
- public IBinder onBind(Intent intent)
- {
- return null;
- }
- }
Add Comment
Please, Sign In to add comment