Example usage for android.content IntentFilter IntentFilter

List of usage examples for android.content IntentFilter IntentFilter

Introduction

In this page you can find the example usage for android.content IntentFilter IntentFilter.

Prototype

public IntentFilter() 

Source Link

Document

New empty IntentFilter.

Usage

From source file:com.mobilyzer.MeasurementScheduler.java

@Override
public void onCreate() {
    Logger.d("MeasurementScheduler -> onCreate called");
    PhoneUtils.setGlobalContext(this.getApplicationContext());

    phoneUtils = PhoneUtils.getPhoneUtils();
    phoneUtils.registerSignalStrengthListener();

    this.measurementExecutor = Executors.newSingleThreadExecutor();
    this.mainQueue = new PriorityBlockingQueue<MeasurementTask>(Config.MAX_TASK_QUEUE_SIZE,
            new TaskComparator());
    this.waitingTasksQueue = new PriorityBlockingQueue<MeasurementTask>(Config.MAX_TASK_QUEUE_SIZE,
            new WaitingTasksComparator());
    this.pendingTasks = new ConcurrentHashMap<MeasurementTask, Future<MeasurementResult[]>>();
    this.tasksStatus = new ConcurrentHashMap<String, MeasurementScheduler.TaskStatus>();
    this.alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    this.resourceCapManager = new ResourceCapManager(Config.DEFAULT_BATTERY_THRESH_PRECENT, this);

    this.serverTasks = new HashMap<String, Date>();
    // this.currentSchedule = new HashMap<String, MeasurementTask>();

    this.idToClientKey = new ConcurrentHashMap<String, String>();

    messenger = new Messenger(new APIRequestHandler(this));

    gcmManager = new GCMManager(this.getApplicationContext());

    this.setCurrentTask(null);
    this.setCurrentTaskStartTime(null);

    this.checkin = new Checkin(this);
    this.checkinRetryIntervalSec = Config.MIN_CHECKIN_RETRY_INTERVAL_SEC;
    this.checkinRetryCnt = 0;
    this.checkinTask = new CheckinTask();

    this.batteryThreshold = -1;
    this.checkinIntervalSec = -1;
    this.dataUsageProfile = DataUsageProfile.NOTASSIGNED;

    //    loadSchedulerState();//TODO(ASHKAN)

    // Register activity specific BroadcastReceiver here
    IntentFilter filter = new IntentFilter();
    filter.addAction(UpdateIntent.CHECKIN_ACTION);
    filter.addAction(UpdateIntent.CHECKIN_RETRY_ACTION);
    filter.addAction(UpdateIntent.MEASUREMENT_ACTION);
    filter.addAction(UpdateIntent.MEASUREMENT_PROGRESS_UPDATE_ACTION);
    filter.addAction(UpdateIntent.GCM_MEASUREMENT_ACTION);
    filter.addAction(UpdateIntent.PLT_MEASUREMENT_ACTION);

    broadcastReceiver = new BroadcastReceiver() {

        @Override/* w  w w . ja  v  a  2s.c o m*/
        public void onReceive(Context context, Intent intent) {
            Logger.d(intent.getAction() + " RECEIVED");
            if (intent.getAction().equals(UpdateIntent.MEASUREMENT_ACTION)) {
                handleMeasurement();

            } else if (intent.getAction().equals(UpdateIntent.GCM_MEASUREMENT_ACTION)) {
                try {
                    JSONObject json = new JSONObject(
                            intent.getExtras().getString(UpdateIntent.MEASUREMENT_TASK_PAYLOAD));
                    Logger.d("MeasurementScheduler -> GCMManager: json task Value is " + json);
                    if (json != null && MeasurementTask.getMeasurementTypes().contains(json.get("type"))) {

                        try {
                            MeasurementTask task = MeasurementJsonConvertor.makeMeasurementTaskFromJson(json);
                            task.getDescription().priority = MeasurementTask.GCM_PRIORITY;
                            task.getDescription().startTime = new Date(System.currentTimeMillis() - 1000);
                            task.getDescription().endTime = new Date(System.currentTimeMillis() + (600 * 1000));
                            task.generateTaskID();
                            task.getDescription().key = Config.SERVER_TASK_CLIENT_KEY;
                            submitTask(task);
                        } catch (IllegalArgumentException e) {
                            Logger.w("MeasurementScheduler -> GCM : Could not create task from JSON: " + e);
                        }
                    }

                } catch (JSONException e) {
                    Logger.e(
                            "MeasurementSchedule -> GCMManager : Got exception during converting GCM json to MeasurementTask",
                            e);
                }

            } else if (intent.getAction().equals(UpdateIntent.MEASUREMENT_PROGRESS_UPDATE_ACTION)) {
                String taskid = intent.getStringExtra(UpdateIntent.TASKID_PAYLOAD);
                String taskKey = intent.getStringExtra(UpdateIntent.CLIENTKEY_PAYLOAD);
                int priority = intent.getIntExtra(UpdateIntent.TASK_PRIORITY_PAYLOAD,
                        MeasurementTask.INVALID_PRIORITY);

                Logger.e(
                        intent.getStringExtra(UpdateIntent.TASK_STATUS_PAYLOAD) + " " + taskid + " " + taskKey);
                if (intent.getStringExtra(UpdateIntent.TASK_STATUS_PAYLOAD).equals(Config.TASK_FINISHED)) {
                    tasksStatus.put(taskid, TaskStatus.FINISHED);
                    Parcelable[] results = intent.getParcelableArrayExtra(UpdateIntent.RESULT_PAYLOAD);
                    if (results != null) {
                        sendResultToClient(results, priority, taskKey, taskid);

                        for (Object obj : results) {
                            try {
                                MeasurementResult result = (MeasurementResult) obj;
                                /**
                                 * Nullify the additional parameters in MeasurmentDesc, or the results won't be
                                 * accepted by GAE server
                                 */
                                result.getMeasurementDesc().parameters = null;
                                String jsonResult = MeasurementJsonConvertor.encodeToJson(result).toString();
                                saveResultToFile(jsonResult);
                            } catch (JSONException e) {
                                Logger.e("Error converting results to json format", e);
                            }
                        }
                    }
                    handleMeasurement();
                } else if (intent.getStringExtra(UpdateIntent.TASK_STATUS_PAYLOAD).equals(Config.TASK_PAUSED)) {
                    tasksStatus.put(taskid, TaskStatus.PAUSED);
                } else if (intent.getStringExtra(UpdateIntent.TASK_STATUS_PAYLOAD)
                        .equals(Config.TASK_STOPPED)) {
                    tasksStatus.put(taskid, TaskStatus.SCHEDULED);
                } else if (intent.getStringExtra(UpdateIntent.TASK_STATUS_PAYLOAD)
                        .equals(Config.TASK_CANCELED)) {
                    tasksStatus.put(taskid, TaskStatus.CANCELLED);
                    Parcelable[] results = intent.getParcelableArrayExtra(UpdateIntent.RESULT_PAYLOAD);
                    if (results != null) {
                        sendResultToClient(results, priority, taskKey, taskid);
                    }
                } else if (intent.getStringExtra(UpdateIntent.TASK_STATUS_PAYLOAD)
                        .equals(Config.TASK_STARTED)) {
                    tasksStatus.put(taskid, TaskStatus.RUNNING);
                } else if (intent.getStringExtra(UpdateIntent.TASK_STATUS_PAYLOAD)
                        .equals(Config.TASK_RESUMED)) {
                    tasksStatus.put(taskid, TaskStatus.RUNNING);
                }
            } else if (intent.getAction().equals(UpdateIntent.CHECKIN_ACTION)
                    || intent.getAction().equals(UpdateIntent.CHECKIN_RETRY_ACTION)) {
                Logger.d("Checkin intent received");
                handleCheckin();
            }
        }
    };
    this.registerReceiver(broadcastReceiver, filter);
}

From source file:com.aware.ESM.java

@Override
public void onCreate() {
    super.onCreate();

    TAG = Aware.getSetting(getApplicationContext(), Aware_Preferences.DEBUG_TAG).length() > 0
            ? Aware.getSetting(getApplicationContext(), Aware_Preferences.DEBUG_TAG)
            : TAG;//from   w w  w . ja  v  a 2s . co m

    DATABASE_TABLES = ESM_Provider.DATABASE_TABLES;
    TABLES_FIELDS = ESM_Provider.TABLES_FIELDS;
    CONTEXT_URIS = new Uri[] { ESM_Data.CONTENT_URI };

    IntentFilter filter = new IntentFilter();
    filter.addAction(ESM.ACTION_AWARE_QUEUE_ESM);
    registerReceiver(esmMonitor, filter);

    intent_ESM = new Intent(this, ESM_Queue.class);
    intent_ESM.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    pending_ESM = PendingIntent.getActivity(this, 0, intent_ESM, PendingIntent.FLAG_UPDATE_CURRENT);

    if (Aware.DEBUG)
        Log.d(TAG, "ESM service created!");
}

From source file:org.span.manager.MainActivity.java

@Override
public void onResume() {
    super.onResume();
    Log.d(TAG, "onResume()"); // DEBUG

    // check if the battery temperature should be displayed
    if (app.prefs.getString("batterytemppref", "fahrenheit").equals("disabled") == false) {
        // create the IntentFilter that will be used to listen
        // to battery status broadcasts
        intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        registerReceiver(intentReceiver, intentFilter);
        batteryTemperatureLayout.setVisibility(View.VISIBLE);
    } else {/*from  www  .  j  ava2s  .  co m*/
        try {
            unregisterReceiver(this.intentReceiver);
        } catch (Exception e) {
            ;
        }
        batteryTemperatureLayout.setVisibility(View.INVISIBLE);
    }

    // Register to receive updates about the device network state
    registerReceiver(intentReceiver, new IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION));
    registerReceiver(intentReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

    /*
      Window window = getWindow();
      // window.addFlags(LayoutParams.FLAG_DISMISS_KEYGUARD);
      // window.addFlags(LayoutParams.FLAG_SHOW_WHEN_LOCKED);
      window.addFlags(LayoutParams.FLAG_TURN_SCREEN_ON);
      window.addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON);
      */
}

From source file:com.mobiperf.MeasurementScheduler.java

@Override
public void onCreate() {
    Logger.d("Service onCreate called");
    PhoneUtils.setGlobalContext(this.getApplicationContext());
    phoneUtils = PhoneUtils.getPhoneUtils();
    phoneUtils.registerSignalStrengthListener();
    this.checkin = new Checkin(this);
    this.checkinRetryIntervalSec = Config.MIN_CHECKIN_RETRY_INTERVAL_SEC;
    this.checkinRetryCnt = 0;
    this.checkinTask = new CheckinTask();

    this.pauseRequested = true;
    this.stopRequested = false;
    this.measurementExecutor = Executors.newSingleThreadExecutor();
    this.taskQueue = new PriorityBlockingQueue<MeasurementTask>(Config.MAX_TASK_QUEUE_SIZE,
            new TaskComparator());
    this.pendingTasks = new ConcurrentHashMap<MeasurementTask, Future<MeasurementResult>>();

    // expect it to be the same size as the queue
    this.currentSchedule = new Hashtable<String, MeasurementTask>(Config.MAX_TASK_QUEUE_SIZE);

    this.notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    this.alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    this.resourceCapManager = new ResourceCapManager(Config.DEFAULT_BATTERY_THRESH_PRECENT, this);

    restoreState();//www .j av  a2 s  .  c  o  m

    // Register activity specific BroadcastReceiver here
    IntentFilter filter = new IntentFilter();
    filter.addAction(UpdateIntent.PREFERENCE_ACTION);
    filter.addAction(UpdateIntent.MSG_ACTION);
    filter.addAction(UpdateIntent.CHECKIN_ACTION);
    filter.addAction(UpdateIntent.CHECKIN_RETRY_ACTION);
    filter.addAction(UpdateIntent.MEASUREMENT_ACTION);
    filter.addAction(UpdateIntent.MEASUREMENT_PROGRESS_UPDATE_ACTION);

    broadcastReceiver = new BroadcastReceiver() {
        // Handles various broadcast intents.

        // If traffic is paused by RRCTrafficControl (because a RRC test is
        // running), we do not perform the checkin, since sending interfering
        // traffic makes the RRC inference task abort and restart the current
        // test as the traffic may have altered the phone's RRC state.
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(UpdateIntent.PREFERENCE_ACTION)) {
                updateFromPreference();
            } else if (intent.getAction().equals(UpdateIntent.CHECKIN_ACTION)
                    || intent.getAction().equals(UpdateIntent.CHECKIN_RETRY_ACTION)
                            && !RRCTrafficControl.checkIfPaused()) {
                Logger.d("Checkin intent received");
                handleCheckin(false);
            } else if (intent.getAction().equals(UpdateIntent.MEASUREMENT_ACTION)
                    && !RRCTrafficControl.checkIfPaused()) {
                Logger.d("MeasurementIntent intent received");
                handleMeasurement();
            } else if (intent.getAction().equals(UpdateIntent.MEASUREMENT_PROGRESS_UPDATE_ACTION)) {
                Logger.d("MeasurementIntent update intent received");
                if (intent.getIntExtra(UpdateIntent.PROGRESS_PAYLOAD,
                        Config.INVALID_PROGRESS) == Config.MEASUREMENT_END_PROGRESS) {
                    if (intent.getStringExtra(UpdateIntent.ERROR_STRING_PAYLOAD) != null) {
                        failedMeasurementCnt++;
                    } else {
                        // Process result
                        completedMeasurementCnt++;
                    }
                    if (intent.getStringExtra(UpdateIntent.RESULT_PAYLOAD) != null) {
                        Logger.d("Measurement result intent received");
                        saveResultToFile(intent.getStringExtra(UpdateIntent.RESULT_PAYLOAD));

                    }
                    updateResultsConsole(intent);
                }
            } else if (intent.getAction().equals(UpdateIntent.MSG_ACTION)) {
                String msg = intent.getExtras().getString(UpdateIntent.STRING_PAYLOAD);
                Date now = Calendar.getInstance().getTime();
                insertStringToConsole(systemConsole, now + "\n\n" + msg);
            }
        }
    };
    this.registerReceiver(broadcastReceiver, filter);
    // TODO(mdw): Make this a user-selectable option
    addIconToStatusBar();
}

From source file:com.ieeton.agency.activity.ContactlistFragment.java

private void initView() {
    IntentFilter filter = new IntentFilter();
    filter.addAction(Constants.ACTION_FOLLOW);
    filter.addAction(Constants.ACTION_UNFOLLOW);
    mReceiver = new OperationReceiver();
    getActivity().registerReceiver(mReceiver, filter);

    mPullDownView = (PullDownView) mView.findViewById(R.id.pulldown_view);
    mPullDownView.setUpdateHandle(this);

    mListView = (SwipeListView) mView.findViewById(R.id.list);
    mAdapter = new HomeListAdapter();
    mListView.setAdapter(mAdapter);//from  w w w.  j  a  va 2 s.  c o m
    mListView.setOnScrollListener(this);
    mListView.setSwipeListViewListener(new BaseSwipeListViewListener() {

        @Override
        public void onClickFrontView(int position) {
            if (mList != null && position < mList.size()) {
                UserInfo user = mList.get(position);
                if (user == null) {
                    return;
                }
                if (user.getUserType() == UserInfo.ACCOUNT_DOCTOR) {
                    Doctor doctor = user.getDoctor();
                    if (doctor == null) {
                        return;
                    }
                    Intent intent = new Intent(getActivity(), UserProfileActivity.class);
                    intent.putExtra(UserProfileActivity.EXTRA_USERINFO, new ChatUser(doctor));
                    startActivity(intent);
                } else {
                    Patient patient = user.getPatient();
                    if (patient == null) {
                        return;
                    }
                    Intent intent = new Intent(getActivity(), PatientProfileActivity.class);
                    intent.putExtra(PatientProfileActivity.EXTRA_USERID, patient.getID());
                    startActivity(intent);
                }
            }
        }

    });

    if (mList == null || mList.isEmpty()) {
        refreshData(LOAD_REFRESH);
    }
}

From source file:com.dimasdanz.kendalipintu.NFCOpenDoorActivity.java

public static void setupForegroundDispatch(final Activity activity, NfcAdapter adapter) {
    final Intent intent = new Intent(activity.getApplicationContext(), activity.getClass());
    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

    final PendingIntent pendingIntent = PendingIntent.getActivity(activity.getApplicationContext(), 0, intent,
            0);//  w w w. j ava2  s.  co m

    IntentFilter[] filters = new IntentFilter[1];
    String[][] techList = new String[][] {};
    filters[0] = new IntentFilter();
    filters[0].addAction(NfcAdapter.ACTION_NDEF_DISCOVERED);
    filters[0].addCategory(Intent.CATEGORY_DEFAULT);
    try {
        filters[0].addDataType(MIME_TEXT_PLAIN);
    } catch (MalformedMimeTypeException e) {
        throw new RuntimeException("Check your mime type.");
    }
    adapter.enableForegroundDispatch(activity, pendingIntent, filters, techList);
}

From source file:system.info.reader.java

@Override
protected void onResume() {
    super.onResume();
    //register to receive battery intent
    Properties.BatteryString = (String) propertyItems[0];
    Properties.batteryHealth = getResources().getTextArray(R.array.batteryHealthState);
    Properties.batteryStatus = getResources().getTextArray(R.array.batteryStatus);
    IntentFilter filter = new IntentFilter();
    filter.addAction(Intent.ACTION_BATTERY_CHANGED);
    registerReceiver(Properties.BroadcastReceiver, filter);
}

From source file:com.grupohqh.carservices.operator.ManipulateCarActivity.java

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

    if (getIntent().getExtras().containsKey("userId"))
        userId = getIntent().getExtras().getInt("userId");
    if (getIntent().getExtras().containsKey("carOwnerId"))
        carOwnerId = getIntent().getExtras().getInt("carOwnerId");

    CARBRAND_URL = getString(R.string.base_url) + getString(R.string.carbrands_url);
    CARLINE_URL = getString(R.string.base_url) + getString(R.string.carmodels_url);
    SAVECAR_URL = getString(R.string.base_url) + "savecar/";
    SAVEPHOTO_URL = getString(R.string.base_url) + "savephoto/";
    hasCamera = this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);

    etTagNumber = (EditText) findViewById(R.id.etTagNumber);
    etUsernameOwner = (EditText) findViewById(R.id.etUsernameOwner);
    etCarBrand = (EditText) findViewById(R.id.etCarBrand);
    etCarModel = (EditText) findViewById(R.id.etCarModel);
    etCarYear = (EditText) findViewById(R.id.etCarYear);
    etColor = (EditText) findViewById(R.id.etCarColor);
    etSerialNumber = (EditText) findViewById(R.id.etSerialNumber);
    etLicensePlate = (EditText) findViewById(R.id.etLicensePlate);
    etKM = (EditText) findViewById(R.id.etKm);
    imgCar = (ImageView) findViewById(R.id.imgCar);
    spCarBrand = (Spinner) findViewById(R.id.spCarBrand);
    spCarModel = (Spinner) findViewById(R.id.spCarModel);
    btnSaveCar = (Button) findViewById(R.id.btnSaveCar);
    btnTakePicture = (Button) findViewById(R.id.btnTakePicture);
    bar = (ProgressBar) findViewById(R.id.progressBar);
    viewUsername = findViewById(R.id.viewUsername);

    if (savedInstanceState != null) {
        bm = savedInstanceState.getParcelable("bm");
        if (bm != null)
            imgCar.setImageBitmap(bm);/*ww  w.j a  v a 2  s . c o m*/
    }

    bar.setVisibility(View.GONE);
    etCarBrand.setVisibility(View.GONE);
    etCarModel.setVisibility(View.GONE);
    viewUsername.setVisibility(carOwnerId == 0 ? View.VISIBLE : View.GONE);

    btnTakePicture.setEnabled(hasCamera);
    btnTakePicture.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(ManipulateCarActivity.this)));
            startActivityForResult(intent, CAPTURE_IMAGE);
        }
    });

    btnSaveCar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (validate())
                new SaveCarAsyncTask().execute(SAVECAR_URL);
        }
    });

    spCarBrand.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            if (position == 0)
                ((TextView) parent.getChildAt(position)).setTextColor(Color.GRAY);
            if (mapBrands.get(brands.get(position)) == otherId) {
                etCarBrand.setVisibility(View.VISIBLE);
                etCarModel.setVisibility(View.VISIBLE);
                spCarModel.setVisibility(View.GONE);
                etCarBrand.requestFocus();
            } else {
                etCarBrand.setVisibility(View.GONE);
                etCarModel.setVisibility(View.GONE);
                spCarModel.setVisibility(View.VISIBLE);
                new LoadCarModelsAsyncTask().execute(CARLINE_URL + mapBrands.get(brands.get(position)) + "/");
                reload = true;
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

    spCarModel.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            if (position == 0)
                ((TextView) parent.getChildAt(position)).setTextColor(Color.GRAY);
            if (mapModels.get(models.get(position)) == otherId) {
                etCarModel.setVisibility(View.VISIBLE);
                etCarModel.requestFocus();
            } else {
                etCarModel.setVisibility(View.GONE);
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

    if (useMiniMe) {
        manager = (UsbManager) getSystemService(Context.USB_SERVICE);
        usbCommunication = UsbCommunication.newInstance();

        IntentFilter filter = new IntentFilter();
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED); // will intercept by system
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        filter.addAction(ACTION_USB_PERMISSION);
        registerReceiver(usbReceiver, filter);

        etEPC = (EditText) findViewById(R.id.etEPC);
        btnReadTAG = (Button) findViewById(R.id.btnReadTAG);
        txtStatus = (TextView) findViewById(R.id.txtStatus);
        btnReadTAG.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etEPC.setText("");
                if (txtStatus.getText().toString().equals("conectado")) {
                    readTag();
                } else {
                    Toast.makeText(getBaseContext(), "dispositivo " + txtStatus.getText(), Toast.LENGTH_LONG)
                            .show();
                }
            }
        });
    }

    etKM.addTextChangedListener(new NumberTextWatcher(etKM));
}

From source file:jp.ksksue.app.terminal.AndroidUSBSerialMonitorLite.java

/** Called when the activity is first created. */
@Override// w  w  w. ja v  a2  s .  c o m
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    /* FIXME : How to check that there is a title bar menu or not.
            // Should not set a Window.FEATURE_NO_TITLE on Honeycomb because a user cannot see menu button.
            if(isICSorHigher) {
    if(!getWindow().hasFeature(Window.FEATURE_ACTION_BAR)) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
    }
            }
    */
    setContentView(R.layout.main);

    mSvText = (ScrollView) findViewById(R.id.svText);
    mTvSerial = (TextView) findViewById(R.id.tvSerial);
    btWrite = (Button) findViewById(R.id.btWrite);
    btWrite.setEnabled(false);
    etWrite = (EditText) findViewById(R.id.etWrite);
    etWrite.setEnabled(false);
    etWrite.setHint("CR : \\r, LF : \\n, bin : \\u0000");

    if (SHOW_DEBUG) {
        Log.d(TAG, "New FTDriver");
    }

    // get service
    mSerial = new Physicaloid(this);

    if (SHOW_DEBUG) {
        Log.d(TAG, "New instance : " + mSerial);
    }
    // listen for new devices
    IntentFilter filter = new IntentFilter();
    filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
    filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
    registerReceiver(mUsbReceiver, filter);

    if (SHOW_DEBUG) {
        Log.d(TAG, "FTDriver beginning");
    }

    openUsbSerial();

    etWrite.setOnKeyListener(new OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_ENTER) {
                writeDataToSerial();
                return true;
            }
            return false;
        }
    });
    // ---------------------------------------------------------------------------------------
    // Write Button
    // ---------------------------------------------------------------------------------------
    if (!USE_WRITE_BUTTON_FOR_DEBUG) {
        btWrite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                writeDataToSerial();
            }
        });
    } else {
        // Write test button for debug
        btWrite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String strWrite = "";
                for (int i = 0; i < 3000; ++i) {
                    strWrite = strWrite + " " + Integer.toString(i);
                }
                if (SHOW_DEBUG) {
                    Log.d(TAG, "FTDriver Write(" + strWrite.length() + ") : " + strWrite);
                }
                mSerial.write(strWrite.getBytes(), strWrite.length());
            }
        });
    } // end of if(SHOW_WRITE_TEST_BUTTON)

    btnLoad = (Button) findViewById(R.id.btnLoad);
    btnLoad.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            SimpleFileDialog simpleFileDialog = new SimpleFileDialog(AndroidUSBSerialMonitorLite.this,
                    "FileOpen", new SimpleFileDialog.SimpleFileDialogListener() {
                        @Override
                        public void onChosenDir(String chosenDir) {
                            File file = null;
                            FileInputStream fileInputStream = null;
                            byte[] data;

                            try {
                                file = new File(chosenDir);
                                if (file.isDirectory()) {
                                    throw new IOException("not file");
                                }

                                fileInputStream = new FileInputStream(file);
                                data = new byte[(int) file.length()];
                                fileInputStream.read(data);

                                String dataText = new String(data, "UTF-8");
                                parseJSON(dataText);

                            } catch (IOException e) {
                                Toast.makeText(AndroidUSBSerialMonitorLite.this, e.getMessage(),
                                        Toast.LENGTH_SHORT).show();
                            } finally {
                                if (fileInputStream != null) {
                                    try {
                                        fileInputStream.close();
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                    });
            simpleFileDialog.chooseFile_or_Dir();
        }
    });

    btnPlay = (Button) findViewById(R.id.btnPlay);
    btnPlay.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            startIrBeaconPulse();
        }
    });

    btnStop = (Button) findViewById(R.id.btnStop);
    btnStop.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            stopIrBeaconPulse();
        }
    });

    btnPlay.setEnabled(false);
    btnStop.setEnabled(false);
}

From source file:com.t2.androidspineexample.AndroidSpineExampleActivity.java

/** Called when the activity is first created. */
@Override//from w  w  w . j a  v a  2s .c o  m
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Log.d(TAG, this.getClass().getSimpleName() + ".onCreate()");
    mInstance = this;
    setContentView(R.layout.main);

    // Set up member variables to UI Elements
    mTextViewDataMindset = (TextView) findViewById(R.id.textViewData);
    mTextViewDataShimmerEcg = (TextView) findViewById(R.id.textViewDataShimmerEcg);
    mTextViewDataShimmerGsr = (TextView) findViewById(R.id.textViewDataShimmerGsr);
    mTextViewDataShimmerEmg = (TextView) findViewById(R.id.textViewDataShimmerEmg);

    // ----------------------------------------------------
    // Initialize SPINE by passing the fileName with the configuration properties
    // ----------------------------------------------------
    Resources resources = this.getResources();
    AssetManager assetManager = resources.getAssets();
    try {
        mSpineManager = SPINEFactory.createSPINEManager("SPINETestApp.properties", resources);
    } catch (InstantiationException e) {
        Log.e(TAG, "Exception creating SPINE manager: " + e.toString());
        Log.e(TAG,
                "Check to see that valid defaults.properties, and SpineTestApp.properties files exist in the Assets folder!");
        e.printStackTrace();
    }

    // ... then we need to register a SPINEListener implementation to the SPINE manager instance
    // to receive sensor node data from the Spine server
    // (I register myself since I'm a SPINEListener implementation!)
    mSpineManager.addListener(this);

    // Create a broadcast receiver. Note that this is used ONLY for command messages from the service
    // All data from the service goes through the mail SPINE mechanism (received(Data data)).
    // See public void received(Data data)
    this.mCommandReceiver = new SpineReceiver(this);

    // Set up filter intents so we can receive broadcasts
    IntentFilter filter = new IntentFilter();
    filter.addAction("com.t2.biofeedback.service.status.BROADCAST");
    this.registerReceiver(this.mCommandReceiver, filter);

    try {
        mCurrentMindsetData = new MindsetData(this);
    } catch (Exception e1) {
        Log.e(TAG, "Exception creating MindsetData: " + e1.toString());
    }

    // Since Mindset is a static node we have to manually put it in the active node list
    // Note that the sensor id 0xfff1 (-15) is a reserved id for this particular sensor
    Node MindsetNode = null;
    MindsetNode = new Node(new Address("" + Constants.RESERVED_ADDRESS_MINDSET));
    mSpineManager.getActiveNodes().add(MindsetNode);

    // Since Shimmer is a static node we have to manually put it in the active node list
    mShimmerNode = new Node(new Address("" + Constants.RESERVED_ADDRESS_SHIMMER));
    mSpineManager.getActiveNodes().add(mShimmerNode);

    // Set up graph(s)
    mSeries = new XYSeries("parameter");
    generateChart();

}