Example usage for android.content BroadcastReceiver BroadcastReceiver

List of usage examples for android.content BroadcastReceiver BroadcastReceiver

Introduction

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

Prototype

public BroadcastReceiver() 

Source Link

Usage

From source file:com.keysolutions.meteorparties.LoginActivity.java

/**
 * Called on resume of activity and initial startup
 *//*from   ww w .  j a va 2s  . co  m*/
protected void onResume() {
    super.onResume();
    // get ready to handle DDP events
    mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // display errors to the user
            Bundle bundle = intent.getExtras();
            showProgress(false);
            if (intent.getAction().equals(MyDDPState.MESSAGE_ERROR)) {
                String message = bundle.getString(MyDDPState.MESSAGE_EXTRA_MSG);
                showError("Login Error", message);
            } else if (intent.getAction().equals(MyDDPState.MESSAGE_CONNECTION)) {
                int state = bundle.getInt(MyDDPState.MESSAGE_EXTRA_STATE);
                if (state == MyDDPState.DDPSTATE.LoggedIn.ordinal()) {
                    // login complete, so we can close this login activity and go back
                    finish();
                }
            }
        }

    };
    // we want error messages
    LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver,
            new IntentFilter(MyDDPState.MESSAGE_ERROR));
    // we want connection state change messages so we know we're logged in
    LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver,
            new IntentFilter(MyDDPState.MESSAGE_CONNECTION));

    // show connection error if it happened
    if (MyDDPState.getInstance().getState() == MyDDPState.DDPSTATE.Closed) {
        showError("Connection Issue", "Error connecting to server...please try again");
        MyDDPState.getInstance().connectIfNeeded(); // try reconnecting
    }
}

From source file:com.supremainc.biostar2.main.MainFragment.java

protected void registerBroadcast() {
    if (mReceiverTick == null) {
        mReceiverTick = new BroadcastReceiver() {
            @Override//from w  ww. j  a v  a  2 s . com
            public void onReceive(Context context, Intent intent) {
                if (mIsDestroy) {
                    return;
                }
                final String action = intent.getAction();

                if (action.equals(Intent.ACTION_TIME_TICK)) {
                    setTime();
                }
            }
        };
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_TIME_TICK);
        getActivity().registerReceiver(mReceiverTick, intentFilter);
    }
    if (mReceiver == null) {
        mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (isInValidCheck(null)) {
                    return;
                }
                String action = intent.getAction();
                if (action.equals(Setting.BROADCAST_REROGIN)) {
                    applyPermission();
                } else if (action.equals(Setting.BROADCAST_ALARM_UPDATE)) {
                    if (mLayout != null) {
                        mLayout.setAlarmCount();
                    }
                }
            }
        };
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Setting.BROADCAST_REROGIN);
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mReceiver, intentFilter);
    }
}

From source file:com.cellbots.remoteEyes.RemoteEyesActivity.java

/** Called when the activity is first created. */
@Override/*  ww  w .  j  a  va2 s . com*/
public void onCreate(Bundle savedInstanceState) {
    Log.e("remote eyes", "started");
    super.onCreate(savedInstanceState);

    mTorchMode = false;

    out = new ByteArrayOutputStream();

    if ((getIntent() != null) && (getIntent().getData() != null)) {
        putUrl = getIntent().getData().toString();
        server = putUrl.replace("http://", "");
        server = server.substring(0, server.indexOf("/"));
        Bundle extras = getIntent().getExtras();
        if ((extras != null) && (extras.getBoolean("TORCH", false))) {
            mTorchMode = true;
        }
    } else {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        putUrl = prefs.getString("REMOTE_EYES_PUT_URL", "");
        Log.e("prefs", putUrl);
        if (putUrl.length() < 1) {
            Intent i = new Intent();
            i.setClass(this, PrefsActivity.class);
            startActivity(i);
            finish();
            return;
        } else {
            server = putUrl.replace("http://", "");
            server = server.substring(0, server.indexOf("/"));
        }
    }

    resetConnection();
    mHttpState = new HttpState();

    setContentView(R.layout.main);
    mPreview = (SurfaceView) findViewById(R.id.preview);
    mHolder = mPreview.getHolder();
    mHolder.addCallback(this);
    mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

    mPreview.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            setTorchMode(!mTorchMode);
        }
    });

    this.registerReceiver(new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            boolean useTorch = intent.getBooleanExtra("TORCH", false);
            setTorchMode(useTorch);
        }
    }, new IntentFilter("android.intent.action.REMOTE_EYES_COMMAND"));
}

From source file:com.mgalgs.trackthatthing.LocationReceiver.java

public void updateResultsInUi() {
    SharedPreferences settings = mContext.getSharedPreferences(TrackThatThing.PREFS_NAME,
            android.content.Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = settings.edit();

    SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss a yyyy-MM-dd");
    Calendar cal = Calendar.getInstance();

    editor.putString(TrackThatThing.PREF_LAST_LOC_TIME, sdf.format(cal.getTime()));
    editor.commit();/*from  w ww  . j a va2  s  .c o  m*/

    Intent i = new Intent(TheTracker.IF_LOC_UPDATE);
    // i.putExtra(TimerDB.KEY_ID, id);
    Log.d(TrackThatThing.TAG, "Pinging TheTracker...");
    mContext.sendOrderedBroadcast(i, null, new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int result = getResultCode();
            if (result != Activity.RESULT_CANCELED) {
                Log.d(TrackThatThing.TAG, "TheTracker caught the broadcast, result " + result);
                return; // Activity caught it
            }
            Log.d(TrackThatThing.TAG, "TimerActivity did not catch the broadcast");
        }
    }, null, Activity.RESULT_CANCELED, null, null);
}

From source file:com.joshmoles.byobcontroller.ControlActivity.java

/**
 * Function that does configuration of Pubnub for the controller.
 *//* w  ww. ja va2 s  . com*/
private void configurePubnub() {
    // Configure PubNub object
    pubnub = new Pubnub(myConfig.pubnubPublish, // PUBLISH_KEY   (Optional, supply "" to disable)
            myConfig.pubnubSubscribe, // SUBSCRIBE_KEY (Required)
            myConfig.pubnubSecret, // SECRET_KEY    (Optional, supply "" to disable)
            "", // CIPHER_KEY    (Optional, supply "" to disable)
            false // SSL_ON?
    );

    // In case of disconnect, register the receiver.
    this.registerReceiver(new BroadcastReceiver() {
        @Override
        public void onReceive(Context arg0, Intent intent) {
            pubnub.disconnectAndResubscribe();
        }

    }, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

    // Need to subscribe to the private user channel and the game channel.
    // First, the private user channel.
    Hashtable<String, String> args = new Hashtable<String, String>(2);
    args.put("channel", privGameCh);
    try {
        pubnub.subscribe(args, new Callback() {
            public void successCallback(String channel, Object message) {
                // Callback for if a message is received in the game channel.
                // TODO: Update score, etc. here.
                Log.v(Consts.LOAD_FETCH, "Received Message " + message.toString());
                if (message.toString().equals(Consts.PUBNUB_RESP_GAMEOVER)) {
                    // Game Over
                    Log.v(Consts.LOAD_FETCH, "Attempting to play game over audio.");
                    playAudio(R.raw.game_over);
                    mMessage = "Game over!";
                    mHandler.post(mGoBackToMain);
                } else if (message.toString().equals(Consts.PUBNUB_RESP_WINNER)) {
                    // Winner
                    Log.v(Consts.LOAD_FETCH, "Attempting to play winner audio.");
                    playAudio(R.raw.you_win);
                } else if (message.toString().equals(Consts.PUBNUB_RESP_LOSER)) {
                    // Loser
                    Log.v(Consts.LOAD_FETCH, "Attempting to play loser audio.");
                    playAudio(R.raw.you_lose);
                }

            }

            public void errorCallback(String channel, Object message) {
                Log.w(Consts.LOAD_FETCH, channel + " " + message.toString());
            }
        });
    } catch (PubnubException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:eu.liveGov.libraries.livegovtoolkit.activities_fragments.MapFragment.java

/**
 *    RESUME//from  ww w.  j a  v  a 2 s . c o  m
 */
@Override
public void onResume() {
    Functions.startLocationService(getActivity());

    //--------------- Receiver for Location Changed -------
    intentFilter = new IntentFilter("locarsens");
    mReceiverLocChanged = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            if (intent.getStringExtra("LocChanged").equals("ok")) {
                onLocationChanged(null);
            }
        }
    };

    if (!isReg_mReceiverLocChanged) {
        getActivity().registerReceiver(mReceiverLocChanged, intentFilter);
        isReg_mReceiverLocChanged = true;
    }

    super.onResume();
}

From source file:com.kasungunathilaka.sarigama.fragment.PlayerFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_player, container, false);
    activity = (HomeActivity) getActivity();
    totalTime = (TextView) view.findViewById(R.id.totalTime);
    currentTime = (TextView) view.findViewById(R.id.currentTime);
    seekBar = (SeekBar) view.findViewById(R.id.seekBar);
    ibPlay = (CircleImageView) view.findViewById(R.id.ibPlay);
    imCoverImage = (ImageView) view.findViewById(R.id.coverImage);
    ibMinimize = (ImageButton) view.findViewById(R.id.ibMinimize);
    ivNext = (ImageButton) view.findViewById(R.id.ivNext);
    ivPrevious = (ImageButton) view.findViewById(R.id.ivPrevious);
    ivLoop = (ImageButton) view.findViewById(R.id.ivLoop);
    ivShuffle = (ImageButton) view.findViewById(R.id.ivShuffle);
    ivNext.setOnClickListener(new View.OnClickListener() {
        @Override/*from w w w . j  ava  2 s.  c  om*/
        public void onClick(View v) {
            playerService.next();
        }
    });

    ivPrevious.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            playerService.previous();
        }
    });

    ivLoop.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (playerService.isQueueOnLoop()) {
                playerService.setQueueOnLoop(false);
                playerService.setSongOnLoop(true);
                ivLoop.setImageResource(R.drawable.ic_repeat_one_black);
                ivLoop.setColorFilter(getResources().getColor(R.color.colorPrimaryDark));
            } else if (playerService.isSongOnLoop()) {
                playerService.setQueueOnLoop(false);
                playerService.setSongOnLoop(false);
                ivLoop.setImageResource(R.drawable.ic_repeat_white);
                ivLoop.clearColorFilter();
            } else {
                ivLoop.setColorFilter(getResources().getColor(R.color.colorPrimaryDark));
                playerService.setQueueOnLoop(true);
                playerService.setSongOnLoop(false);
            }
        }
    });

    ibPlay.setOnClickListener(playOnClick);
    ibMinimize.setOnClickListener(minimizeOnclick);
    localBroadcastManager = LocalBroadcastManager.getInstance(getActivity());
    broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
            case HomeActivity.ON_PREPARED:
                int position = playerQueue.getCurrentPosition();
                Song currentSong = playerQueue.getSongByPosition(position);
                if (currentSong.getSongImage().contentEquals("http://sarigama.lk/img/songs/default.jpg")) {
                    imCoverImage.setImageResource(R.drawable.default_song_art);
                } else {
                    Picasso.with(getActivity()).load(currentSong.getSongImage()).into(imCoverImage);
                }
                ibPlay.setImageResource(R.drawable.ic_pause_white);
                ((TextView) getActivity().findViewById(R.id.tvTitle)).setText(currentSong.getSongTitle());
                ((TextView) getActivity().findViewById(R.id.tvArtist)).setText(currentSong.getSongArtist());
                activity.setupMiniPlayer(currentSong.getSongTitle(), currentSong.getSongArtist());
                mRunnable.run();
                showProgressDialog(false);
                break;
            case HomeActivity.ON_PREPARING:
                showProgressDialog(true);
                break;
            case HomeActivity.ON_COMPLETED:
                ibPlay.setImageResource(R.drawable.ic_play_white);
                seekBar.setProgress(0);
                break;
            case HomeActivity.ON_PAUSE:
                ibPlay.setImageResource(R.drawable.ic_play_white);
                break;
            case HomeActivity.ON_PLAY:
                ibPlay.setImageResource(R.drawable.ic_pause_white);
                break;
            case HomeActivity.ON_PREPARE_ERROR:
                showProgressDialog(false);
                Toast.makeText(getActivity(), "Song cannot be played, Trying to play next song",
                        Toast.LENGTH_SHORT).show();
                break;
            case HomeActivity.ON_QUEUE_COMPLETED:
                playerService.setQueueOnLoop(false);
                playerService.setSongOnLoop(false);
                ivLoop.setImageResource(R.drawable.ic_repeat_white);
                ivLoop.clearColorFilter();
                break;
            }
        }
    };
    localBroadcastManager.sendBroadcast(new Intent(HomeActivity.ON_PLAYER_ENTER));

    LocalBroadcastManager.getInstance(getActivity()).registerReceiver((broadcastReceiver),
            new IntentFilter(HomeActivity.ON_PAUSE));
    LocalBroadcastManager.getInstance(getActivity()).registerReceiver((broadcastReceiver),
            new IntentFilter(HomeActivity.ON_PLAY));
    LocalBroadcastManager.getInstance(getActivity()).registerReceiver((broadcastReceiver),
            new IntentFilter(HomeActivity.ON_PREPARED));
    LocalBroadcastManager.getInstance(getActivity()).registerReceiver((broadcastReceiver),
            new IntentFilter(HomeActivity.ON_PREPARING));
    LocalBroadcastManager.getInstance(getActivity()).registerReceiver((broadcastReceiver),
            new IntentFilter(HomeActivity.ON_COMPLETED));
    LocalBroadcastManager.getInstance(getActivity()).registerReceiver((broadcastReceiver),
            new IntentFilter(HomeActivity.ON_PREPARE_ERROR));
    LocalBroadcastManager.getInstance(getActivity()).registerReceiver((broadcastReceiver),
            new IntentFilter(HomeActivity.ON_QUEUE_COMPLETED));
    return view;
}

From source file:com.callba.phone.ui.GroupSimpleDetailActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    tv_name = (TextView) findViewById(R.id.name);
    tv_admin = (TextView) findViewById(R.id.tv_admin);
    btn_add_group = (Button) findViewById(R.id.btn_add_to_group);
    tv_introduction = (TextView) findViewById(R.id.tv_introduction);
    tv_id = (TextView) findViewById(R.id.tv_id);
    tv_need_apply = (TextView) findViewById(R.id.tv_need_apply);
    introduction = (LinearLayout) findViewById(R.id.introduction);

    introduction.setOnClickListener(new View.OnClickListener() {
        @Override/*  www . j av a  2s .  c  om*/
        public void onClick(View v) {
            if (!group.getDescription().equals("")) {
                android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(
                        GroupSimpleDetailActivity.this);
                builder.setMessage(group.getDescription());
                android.app.AlertDialog alertDialog = builder.create();
                alertDialog.setCanceledOnTouchOutside(true);
                alertDialog.setCancelable(true);
                alertDialog.show();
            }
        }
    });
    final EMGroupInfo groupInfo = (EMGroupInfo) getIntent().getSerializableExtra("groupinfo");
    String groupname = groupInfo.getGroupName();
    groupid = groupInfo.getGroupId();
    tv_name.setText(groupname);
    tv_id.setText(groupid);
    if (group != null) {
        showGroupDetail();
        return;
    }
    new Thread(new Runnable() {

        public void run() {
            //??
            try {
                group = EMClient.getInstance().groupManager().getGroupFromServer(groupid);

                runOnUiThread(new Runnable() {
                    public void run() {
                        showGroupDetail();
                        tv_need_apply.setText(group.isMembersOnly() ? "" : "?");
                    }
                });
            } catch (final HyphenateException e) {
                e.printStackTrace();
                final String st1 = getResources().getString(R.string.Failed_to_get_group_chat_information);
                runOnUiThread(new Runnable() {
                    public void run() {
                        //progressBar.setVisibility(View.INVISIBLE);
                        Toast.makeText(GroupSimpleDetailActivity.this, st1 + e.getMessage(), Toast.LENGTH_SHORT)
                                .show();

                    }
                });
            }

        }
    }).start();
    broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getExtras() != null) {
                if (intent.getStringExtra("group_id").equals(groupInfo.getGroupId())) {
                    if (intent.getIntExtra("result", 0) == 1)
                        finish();
                    else
                        btn_add_group.setEnabled(true);

                }
            }
        }
    };
    broadcastManager = LocalBroadcastManager.getInstance(this);
    broadcastManager.registerReceiver(broadcastReceiver, new IntentFilter(Constant.ACTION_GROUP_CHANAGED));
}

From source file:com.numenta.htmit.mobile.notification.NotificationListActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    gestureDetector = new GestureDetector(getApplicationContext(), this);
    setContentView(R.layout.activity_notification_list);
    setVisible(false);/*from  ww  w  . ja va 2s. c om*/

    listView = (ListView) findViewById(R.id.notification_list_view);
    dismissButton = (Button) findViewById(R.id.action_dismiss_all_notifications);
    closeButton = (Button) findViewById(R.id.action_close_notifications);
    noNotificationsText = (TextView) findViewById(R.id.no_notifications_text);

    // For the cursor adapter, specify which columns go into which views
    String[] fromColumns = { "timestamp", "description", "metric_id", "read" };
    int[] toViews = { R.id.notification_time, R.id.notification_description, R.id.notification_delete,
            R.id.notification_unread }; // The TextView in simple_list_item_1
    _database = HTMITApplication.getDatabase();
    adapter = new SimpleCursorAdapter(this, R.layout.fragment_notification_list_item, null, fromColumns,
            toViews, 0);

    new AsyncTask<Void, Void, Cursor>() {
        @Override
        protected Cursor doInBackground(Void... params) {
            unreadNotificationSize = _database.getUnreadNotificationCount();
            return _database.getNotificationCursor();
        }

        @Override
        protected void onPostExecute(Cursor cursor) {
            setVisible(true);
            adapter.changeCursor(cursor);
            notificationSize = cursor.getCount();
            updateButtons();
        }
    }.execute();

    _notificationsReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (adapter != null) {
                new AsyncTask<Void, Void, Cursor>() {
                    @Override
                    protected Cursor doInBackground(Void... params) {
                        if (isCancelled())
                            return null;
                        return _database.getNotificationCursor();
                    }

                    @Override
                    protected void onPostExecute(Cursor cursor) {
                        adapter.changeCursor(cursor);
                        updateButtons();
                    }
                }.execute();
            }
        }
    };

    adapter.setViewBinder(new ViewBinder() {

        @Override
        public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
            final int viewId = view.getId();

            switch (viewId) {
            case R.id.notification_time:
                // Converts the timestamp to a readable time.
                final int timeIndex = cursor.getColumnIndex("timestamp");
                Date date = new Date(cursor.getLong(timeIndex));
                ((TextView) view).setText(sdf.format(date));
                break;
            case R.id.notification_unread:
                // Hides notification icon if already read.
                if (cursor.getInt(cursor.getColumnIndex("read")) < 1) {
                    view.setVisibility(View.VISIBLE);
                } else {
                    view.setVisibility(View.INVISIBLE);
                }
                break;
            case R.id.notification_delete:
                // Adds click handler for notification deletions
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Log.i(TAG, "{TAG:ANDROID.ACTION.NOTIFICATION.DELETE} Delete notification clicked");
                        View layout = (View) v.getParent();
                        int position = listView.getPositionForView(layout);
                        NotificationListActivity.this.removeNotificationAt(position);
                    }
                });
                break;
            default:
                return false;
            }
            return true;
        }
    });

    listView.setAdapter(adapter);

    // Clicks on the notifications themselves navigates to the detail view.
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
            Log.i(TAG,
                    "{TAG:ANDROID.ACTION.NOTIFICATION.SELECT} Notification navigation should occur here to notification "
                            + position);
            Cursor cursor = (Cursor) adapter.getItem(position);
            int localIdx = cursor.getColumnIndex("_id");
            final int localId = cursor.getInt(localIdx);

            new AsyncTask<Void, Void, Intent>() {
                @Override
                protected Intent doInBackground(Void... v) {
                    // Get the metric necessary for the new intent to view
                    // the metric detail
                    // page.
                    Notification notification = _database.getNotificationByLocalId(localId);
                    if (notification == null) {
                        // The notification or metric was deleted as the
                        // user view the list
                        return null;
                    }
                    Metric metric = _database.getMetric(notification.getMetricId());
                    if (metric == null) {
                        // the metric was deleted, so nowhere to go
                        _database.deleteNotification(localId);
                        return null;
                    }
                    Intent metricDetail = NotificationUtils
                            .createMetricDetailIntent(NotificationListActivity.this, notification);
                    // Mark the notification as read

                    if (!notification.isRead()) {
                        _database.markNotificationRead(localId);
                    }
                    ((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).cancelAll();

                    return metricDetail;
                }

                @Override
                protected void onPostExecute(Intent metricDetail) {
                    if (metricDetail == null) {
                        Toast.makeText(NotificationListActivity.this, R.string.notification_expired,
                                Toast.LENGTH_LONG).show();
                        NotificationListActivity.this.finish();
                        return;
                    }
                    // Show detail page
                    startActivity(metricDetail);
                    // Hide the 'unread' indication.
                    view.findViewById(R.id.notification_unread).setVisibility(View.INVISIBLE);
                }
            }.execute();

        }
    });

    // This catches "fling" events on items to delete notifications within
    // the list.
    // Defers touch events to a GestureDetector, which isolates fling events
    // from touch events.
    listView.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return gestureDetector.onTouchEvent(event);
        }
    });

    dismissButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Log.i(TAG, "{TAG:ANDROID.ACTION.NOTIFICATION.DELETE_ALL}");
            deleteAllNotifications();
        }
    });

    closeButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            cancelNotifications();
        }
    });
}

From source file:com.groksolutions.grok.mobile.notification.NotificationListActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    gestureDetector = new GestureDetector(getApplicationContext(), this);
    setContentView(R.layout.activity_notification_list);
    setVisible(false);//from   w w  w.  jav a  2  s  .  c  om

    listView = (ListView) findViewById(R.id.notification_list_view);
    dismissButton = (Button) findViewById(R.id.action_dismiss_all_notifications);
    closeButton = (Button) findViewById(R.id.action_close_notifications);
    noNotificationsText = (TextView) findViewById(R.id.no_notifications_text);

    // For the cursor adapter, specify which columns go into which views
    String[] fromColumns = { "timestamp", "description", "metric_id", "read" };
    int[] toViews = { R.id.notification_time, R.id.notification_description, R.id.notification_delete,
            R.id.notification_unread }; // The TextView in simple_list_item_1
    grokDb = HTMITApplication.getDatabase();
    adapter = new SimpleCursorAdapter(this, R.layout.fragment_notification_list_item, null, fromColumns,
            toViews, 0);

    new AsyncTask<Void, Void, Cursor>() {
        @Override
        protected Cursor doInBackground(Void... params) {
            unreadNotificationSize = grokDb.getUnreadNotificationCount();
            return grokDb.getNotificationCursor();
        }

        @Override
        protected void onPostExecute(Cursor cursor) {
            setVisible(true);
            adapter.changeCursor(cursor);
            notificationSize = cursor.getCount();
            updateButtons();
        }
    }.execute();

    _notificationsReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (adapter != null) {
                new AsyncTask<Void, Void, Cursor>() {
                    @Override
                    protected Cursor doInBackground(Void... params) {
                        if (isCancelled())
                            return null;
                        return grokDb.getNotificationCursor();
                    }

                    @Override
                    protected void onPostExecute(Cursor cursor) {
                        adapter.changeCursor(cursor);
                        updateButtons();
                    }
                }.execute();
            }
        }
    };

    adapter.setViewBinder(new ViewBinder() {

        @Override
        public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
            final int viewId = view.getId();

            switch (viewId) {
            case R.id.notification_time:
                // Converts the timestamp to a readable time.
                final int timeIndex = cursor.getColumnIndex("timestamp");
                Date date = new Date(cursor.getLong(timeIndex));
                ((TextView) view).setText(sdf.format(date));
                break;
            case R.id.notification_unread:
                // Hides notification icon if already read.
                if (cursor.getInt(cursor.getColumnIndex("read")) < 1) {
                    view.setVisibility(View.VISIBLE);
                } else {
                    view.setVisibility(View.INVISIBLE);
                }
                break;
            case R.id.notification_delete:
                // Adds click handler for notification deletions
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Log.i(TAG, "{TAG:ANDROID.ACTION.NOTIFICATION.DELETE} Delete notification clicked");
                        View layout = (View) v.getParent();
                        int position = listView.getPositionForView(layout);
                        NotificationListActivity.this.removeNotificationAt(position);
                    }
                });
                break;
            default:
                return false;
            }
            return true;
        }
    });

    listView.setAdapter(adapter);

    // Clicks on the notifications themselves navigates to the detail view.
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
            Log.i(TAG,
                    "{TAG:ANDROID.ACTION.NOTIFICATION.SELECT} Notification navigation should occur here to notification "
                            + position);
            Cursor cursor = (Cursor) adapter.getItem(position);
            int localIdx = cursor.getColumnIndex("_id");
            final int localId = cursor.getInt(localIdx);

            new AsyncTask<Void, Void, Intent>() {
                @Override
                protected Intent doInBackground(Void... v) {
                    // Get the metric necessary for the new intent to view
                    // the metric detail
                    // page.
                    Notification notification = grokDb.getNotificationByLocalId(localId);
                    if (notification == null) {
                        // The notification or metric was deleted as the
                        // user view the list
                        return null;
                    }
                    Metric metric = grokDb.getMetric(notification.getMetricId());
                    if (metric == null) {
                        // the metric was deleted, so nowhere to go
                        grokDb.deleteNotification(localId);
                        return null;
                    }
                    Intent metricDetail = NotificationUtils
                            .createMetricDetailIntent(NotificationListActivity.this, notification);
                    // Mark the notification as read

                    if (!notification.isRead()) {
                        grokDb.markNotificationRead(localId);
                    }
                    ((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).cancelAll();

                    return metricDetail;
                }

                @Override
                protected void onPostExecute(Intent metricDetail) {
                    if (metricDetail == null) {
                        Toast.makeText(NotificationListActivity.this, R.string.notification_expired,
                                Toast.LENGTH_LONG).show();
                        NotificationListActivity.this.finish();
                        return;
                    }
                    // Show detail page
                    startActivity(metricDetail);
                    // Hide the 'unread' indication.
                    view.findViewById(R.id.notification_unread).setVisibility(View.INVISIBLE);
                }
            }.execute();

        }
    });

    // This catches "fling" events on items to delete notifications within
    // the list.
    // Defers touch events to a GestureDetector, which isolates fling events
    // from touch events.
    listView.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return gestureDetector.onTouchEvent(event);
        }
    });

    dismissButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Log.i(TAG, "{TAG:ANDROID.ACTION.NOTIFICATION.DELETE_ALL}");
            deleteAllNotifications();
        }
    });

    closeButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            cancelNotifications();
        }
    });
}