-1

I have created app that detects otg cable,when otg cable is plugged in or out popup message appears that says otg connected or otg disconnected.How to make that popup appears when button on toolbar is clicked,popup message should only appear in action bar when otg cable is not connected,when it's connected it's should be hidden?

public class MainActivity extends AppCompatActivity
{
    private Process suProcess;

    public static final String IS_CONNECTED_KEY = "isConnectedValue";

    public void startOtgService()
    {
        startService(new Intent(MainActivity.this, OtgService.class));

    }

    public void stopOtgService()
    {
        stopService(new Intent(MainActivity.this, OtgService.class));

    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button) findViewById(R.id.button_autootg);
        button.setTag(0);
        button.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                button.setText("");
                final int status = (Integer) view.getTag();
                switch (status)
                {
                    case 0:
                        startOtgService();
                        button.setText("OTG Service Enabled");
                        button.setBackgroundColor(Color.GREEN);
                        view.setTag(1);
                        break;
                    case 1:
                        stopOtgService();
                        button.setText("OTG Service Disabled");
                        button.setBackgroundColor(Color.RED);
                        view.setTag(0);
                        break;
                }
            }
        });

    }

    private void getRoot()
    {
        try
        {
            suProcess = Runtime.getRuntime().exec("su");
        }
        catch (IOException e)
        {

        }
    }

    @Override
    protected void onNewIntent(Intent intent)
    {
        if (intent.getExtras() == null)
        {
            super.onNewIntent(intent);
            Log.e("###", "No extras");
            return;
        }

        if (intent.hasExtra(IS_CONNECTED_KEY))
        {
            Log.e("###", "Displaying dialog");

            boolean isConnected = intent.getExtras().getBoolean(IS_CONNECTED_KEY);

            final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
            alertDialog.setTitle("Otg state changed");

            if (isConnected)
                alertDialog.setMessage("OTG connected");
            else
                alertDialog.setMessage("OTG disconnected");

            alertDialog.show();
        }
        else
        {
            Log.e("###", "Does not contain key");
            super.onNewIntent(intent);
        }
    }
@Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        getMenuInflater().inflate(R.menu.menu_main, menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        int id = item.getItemId();

        if (id == R.id.action_settings)
        {
            return true;
        }
        if(id ==  R.id.action_cable)
        {

        }
        return super.onOptionsItemSelected(item);
    }
}



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;
    }
}
manfcas
  • 1,933
  • 7
  • 28
  • 47

1 Answers1

0

Add the following code in your code. When cable state changed, call cableStateWasChanged(boolean isConnected). This will show the popup button in your toolbar. When the button is clicked, a popup is shown and the button disappears. You can change the popup title and message depending on the cable state as you want it to be.

private boolean isCableConnected = false;
private boolean cableStateChanged = false;
private boolean popupWasShown = false;

@Override
public boolean onPrepareOptionsMenu(Menu menu){
    MenuItem item = menu.findItem(R.id.action_popup);
    if (cableStateChanged && !popupWasShown) {
        item.setVisible(true);
        cableStateChanged = false;
    } else if (popupWasShown) {
        item.setVisible(false); 
    }
    return super.onPrepareOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == ...) {
        ...
    } else if (id == R.id.action_popup) {
        popupWasShown = true;
        invalidateOptionsMenu();
        // You can change the popup title, message and buttons here
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(isCableConnected ? "Cable was connected" : "Cable was disconnected");
        builder.setMessage("foo bar");
        builder.setPositiveButton("OK", null);
        builder.setNegativeButton(null, null);
        builder.create().show();
    }
    return super.onOptionsItemSelected(item);
}

private void cableStateWasChanged(boolean isConnected) {
    isCableConnected = isConnected;
    cableStateChanged = true;
    popupShown = false;
    invalidateOptionsMenu();
}

Also I suggest you to use Handler instead of TimerTask, see this post

Community
  • 1
  • 1
Nicolas
  • 6,611
  • 3
  • 29
  • 73