Java Code Examples for android.content.BroadcastReceiver

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project android-client_1, under directory /src/com/googlecode/asmack/connection/.

Source file: XmppTransportService.java

  18 
vote

/** 
 * Initialize the xmpp service, binding all required receivers.
 */
@Override public void onCreate(){
  super.onCreate();
  accountManager=AccountManager.get(this);
  ContentProviderClient provider=getContentResolver().acquireContentProviderClient(ContactsContract.AUTHORITY_URI);
  ContactDataMapper mapper=new ContactDataMapper(provider);
  listeners.add(new PresenceBroadcastReceiver(mapper));
  listeners.add(new DiscoReceiver(getApplicationContext(),this));
  BroadcastReceiver receiver=new KeepaliveActionIntentReceiver(this);
  ;
  registerReceiver(receiver,new IntentFilter(Intent.ACTION_TIME_TICK));
  receiver=new ConnectivityReceiver(this);
  registerReceiver(receiver,new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
  accountManager.addOnAccountsUpdatedListener(this,null,true);
}
 

Example 2

From project android_packages_apps_Nfc, under directory /src/com/android/nfc/.

Source file: RegisteredComponentCache.java

  18 
vote

/** 
 * Stops the monitoring of package additions, removals and changes.
 */
public void close(){
  final BroadcastReceiver receiver=mReceiver.getAndSet(null);
  if (receiver != null) {
    mContext.unregisterReceiver(receiver);
  }
}
 

Example 3

From project google-voice-tasker-plugin, under directory /tests/src/com/yourcompany/yoursetting/receiver/.

Source file: ReceiverTest.java

  18 
vote

/** 
 * Tests sending an Intent with null message
 */
public void testNullMessage(){
  BroadcastReceiver fireReceiver=new FireReceiver();
  Bundle bundle=new Bundle();
  bundle.putString(PluginBundleManager.BUNDLE_EXTRA_STRING_MESSAGE,null);
  fireReceiver.onReceive(getContext(),new Intent(com.twofortyfouram.locale.Intent.ACTION_FIRE_SETTING).putExtra(com.twofortyfouram.locale.Intent.EXTRA_BUNDLE,bundle));
}
 

Example 4

From project Locale-MWM, under directory /tests/src/com/yourcompany/yoursetting/receiver/.

Source file: ReceiverTest.java

  18 
vote

/** 
 * Tests sending an Intent with null message
 */
public void testNullMessage(){
  BroadcastReceiver fireReceiver=new FireReceiver();
  Bundle bundle=new Bundle();
  bundle.putString(PluginBundleManager.BUNDLE_EXTRA_STRING_MESSAGE,null);
  fireReceiver.onReceive(getContext(),new Intent(com.twofortyfouram.locale.Intent.ACTION_FIRE_SETTING).putExtra(com.twofortyfouram.locale.Intent.EXTRA_BUNDLE,bundle));
}
 

Example 5

From project Airports, under directory /src/com/nadmm/airports/notams/.

Source file: NotamFragmentBase.java

  17 
vote

@Override public void onCreate(Bundle savedInstanceState){
  super.onCreate(savedInstanceState);
  mFilter=new IntentFilter();
  mFilter.addAction(NotamService.ACTION_GET_NOTAM);
  mReceiver=new BroadcastReceiver(){
    @Override public void onReceive(    Context context,    Intent intent){
      handleNotamBroadcast(intent);
    }
  }
;
}
 

Example 6

From project android-vpn-server, under directory /src/android/net/vpn/.

Source file: VpnTest.java

  17 
vote

@SmallTest public void testReceiver(){
  final String profileName="whatever";
  final VpnState state=VpnState.DISCONNECTING;
  final ConditionVariable cv=new ConditionVariable();
  cv.close();
  BroadcastReceiver r=new BroadcastReceiver(){
    public void onReceive(    Context c,    Intent i){
      assertEquals(profileName,i.getStringExtra(VpnManager.BROADCAST_PROFILE_NAME));
      assertEquals(state,i.getSerializableExtra(VpnManager.BROADCAST_CONNECTION_STATE));
      cv.open();
    }
  }
;
  VpnManager m=new VpnManager(getContext());
  m.registerConnectivityReceiver(r);
  m.broadcastConnectivity(profileName,state);
  assertTrue(cv.block(5000));
}
 

Example 7

From project android-vpn-settings, under directory /src/android/net/vpn/.

Source file: VpnTest.java

  17 
vote

@SmallTest public void testReceiver(){
  final String profileName="whatever";
  final VpnState state=VpnState.DISCONNECTING;
  final ConditionVariable cv=new ConditionVariable();
  cv.close();
  BroadcastReceiver r=new BroadcastReceiver(){
    public void onReceive(    Context c,    Intent i){
      assertEquals(profileName,i.getStringExtra(VpnManager.BROADCAST_PROFILE_NAME));
      assertEquals(state,i.getSerializableExtra(VpnManager.BROADCAST_CONNECTION_STATE));
      cv.open();
    }
  }
;
  VpnManager m=new VpnManager(getContext());
  m.registerConnectivityReceiver(r);
  m.broadcastConnectivity(profileName,state);
  assertTrue(cv.block(5000));
}
 

Example 8

From project AsmackService, under directory /src/com/googlecode/asmack/connection/.

Source file: XmppTransportService.java

  17 
vote

/** 
 * Initialize the xmpp service, binding all required receivers.
 */
@Override public void onCreate(){
  super.onCreate();
  accountManager=AccountManager.get(this);
  ContentProviderClient provider=getContentResolver().acquireContentProviderClient(ContactsContract.AUTHORITY_URI);
  ContactDataMapper mapper=new ContactDataMapper(provider);
  BroadcastReceiver receiver=new PresenceBroadcastReceiver(mapper);
  registerReceiver(receiver,new IntentFilter(XmppTransportService.XMPP_STANZA_INTENT));
  receiver=new DiscoReceiver();
  registerReceiver(receiver,new IntentFilter(XmppTransportService.XMPP_STANZA_INTENT));
  receiver=new KeepaliveActionIntentReceiver(this);
  ;
  registerReceiver(receiver,new IntentFilter(Intent.ACTION_TIME_TICK));
  receiver=new SendStanzaReceiver(this);
  registerReceiver(receiver,new IntentFilter(XMPP_STANZA_SEND_INTENT));
  receiver=new ConnectivityReceiver(this);
  registerReceiver(receiver,new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
  accountManager.addOnAccountsUpdatedListener(this,null,true);
}
 

Example 9

From project bitfluids, under directory /src/main/java/at/bitcoin_austria/bitfluids/trafficSignal/.

Source file: TrafficSignal.java

  17 
vote

/** 
 * @param trafficSignReciever where you will be notified
 * @return the BroadcastReceiver to unregister by the UI
 */
public BroadcastReceiver addNotifier(final TrafficSignalReciever trafficSignReciever){
  checkInternet(trafficSignReciever);
  IntentFilter intentFilter=new IntentFilter();
  intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
  BroadcastReceiver receiver=new BroadcastReceiver(){
    @Override public void onReceive(    Context context,    Intent intent){
      checkInternet(trafficSignReciever);
    }
  }
;
  context.registerReceiver(receiver,intentFilter);
  bitcoinNet.addPeerCountListener(new Consumer<Integer>(){
    @Override public void consume(    Integer count){
      if (count < 1) {
        trafficSignReciever.onStatusChanged(SignalType.PEERS,Status.RED);
      }
 else       if (count < BitcoinTransactionListener.MAX_CONNECTIONS) {
        trafficSignReciever.onStatusChanged(SignalType.PEERS,Status.YELLOW);
      }
 else {
        trafficSignReciever.onStatusChanged(SignalType.PEERS,Status.GREEN);
      }
    }
  }
);
  priceService.addLastQuoteListener(new Consumer<Status>(){
    @Override public void consume(    Status status){
      trafficSignReciever.onStatusChanged(SignalType.EXCHANGERATE,status);
    }
  }
);
  return receiver;
}
 

Example 10

From project DeskSMS, under directory /DeskSMS/src/com/koushikdutta/desktopsms/.

Source file: TickleServiceHelper.java

  17 
vote

static void registerForPush(final Context context,final Callback<Void> callback){
  Intent registrationIntent=new Intent("com.google.android.c2dm.intent.REGISTER");
  registrationIntent.putExtra("app",PendingIntent.getBroadcast(context,0,new Intent(),0));
  registrationIntent.putExtra("sender","[email protected]");
  if (callback != null) {
    BroadcastReceiver receiver=new BroadcastReceiver(){
      @Override public void onReceive(      Context context,      Intent intent){
        context.unregisterReceiver(this);
        callback.onCallback(null);
      }
    }
;
    IntentFilter filter=new IntentFilter(C2DMReceiver.ACTION_REGISTRATION_RECEIVED);
    context.registerReceiver(receiver,filter);
  }
  context.startService(registrationIntent);
}
 

Example 11

From project DownloadProvider, under directory /src/com/mozillaonline/downloadprovider/.

Source file: DownloadProviderActivity.java

  17 
vote

/** 
 * Called when the activity is first created. 
 */
@Override public void onCreate(Bundle savedInstanceState){
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  mDownloadManager=new DownloadManager(getContentResolver(),getPackageName());
  buildComponents();
  startDownloadService();
  mReceiver=new BroadcastReceiver(){
    @Override public void onReceive(    Context context,    Intent intent){
      showDownloadList();
    }
  }
;
  registerReceiver(mReceiver,new IntentFilter(DownloadManager.ACTION_NOTIFICATION_CLICKED));
}
 

Example 12

From project lastfm-android, under directory /app/src/fm/last/android/.

Source file: LastFMApplication.java

  17 
vote

public void playRadioStation(Context ctx,String url,boolean showPlayer){
  mCtx=ctx;
  if (session != null && session.getKey().length() > 0) {
    final Intent out=new Intent(this,RadioPlayerService.class);
    out.setAction("fm.last.android.PLAY");
    out.putExtra("station",url);
    out.putExtra("session",(Parcelable)session);
    startService(out);
    if (showPlayer) {
      IntentFilter intentFilter=new IntentFilter();
      intentFilter.addAction(RadioPlayerService.STATION_CHANGED);
      intentFilter.addAction("fm.last.android.ERROR");
      BroadcastReceiver statusListener=new BroadcastReceiver(){
        @Override public void onReceive(        Context context,        Intent intent){
          String action=intent.getAction();
          if (action.equals(RadioPlayerService.STATION_CHANGED)) {
            Intent i=new Intent(LastFMApplication.this,Player.class);
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(i);
          }
 else           if (action.equals("fm.last.android.ERROR")) {
            WSError e=intent.getParcelableExtra("error");
            Log.e("Last.fm","Tuning error: " + e.getMessage());
            presentError(mCtx,e);
          }
          unregisterReceiver(this);
        }
      }
;
      registerReceiver(statusListener,intentFilter);
    }
  }
}
 

Example 13

From project maven-android-plugin-samples, under directory /apidemos-android-10/application/src/main/java/com/example/android/apis/content/.

Source file: ExternalStorage.java

  17 
vote

void startWatchingExternalStorage(){
  mExternalStorageReceiver=new BroadcastReceiver(){
    @Override public void onReceive(    Context context,    Intent intent){
      Log.i("test","Storage: " + intent.getData());
      updateExternalStorageState();
    }
  }
;
  IntentFilter filter=new IntentFilter();
  filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
  filter.addAction(Intent.ACTION_MEDIA_REMOVED);
  registerReceiver(mExternalStorageReceiver,filter);
  updateExternalStorageState();
}
 

Example 14

From project ohmagePhone, under directory /src/org/ohmage/triggers/types/location/.

Source file: LocTrigMapsActivity.java

  17 
vote

private void getGPSSamples(){
  Log.i(TAG,"Maps: getGPSSamples");
  BroadcastReceiver bRecr=new BroadcastReceiver(){
    @Override public void onReceive(    Context context,    Intent intent){
      if (intent.getAction().equals(ACTION_ALRM_GPS_TIMEOUT)) {
        stopGPS();
      }
    }
  }
;
  IntentFilter intFilter=new IntentFilter(ACTION_ALRM_GPS_TIMEOUT);
  registerReceiver(bRecr,intFilter);
  if (mGpsTimeoutPI != null) {
    mAlarmMan.cancel(mGpsTimeoutPI);
    mGpsTimeoutPI.cancel();
  }
  mLatestLoc=null;
  mLocMan.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,this);
  mLocMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,this);
  Intent intent=new Intent(ACTION_ALRM_GPS_TIMEOUT);
  mGpsTimeoutPI=PendingIntent.getBroadcast(this,0,intent,PendingIntent.FLAG_CANCEL_CURRENT);
  mAlarmMan.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,SystemClock.elapsedRealtime() + MY_LOC_SAMPLE_TIMEOUT,mGpsTimeoutPI);
}
 

Example 15

From project Ohmage_Phone, under directory /src/org/ohmage/triggers/types/location/.

Source file: LocTrigMapsActivity.java

  17 
vote

private void getGPSSamples(){
  Log.i(DEBUG_TAG,"Maps: getGPSSamples");
  BroadcastReceiver bRecr=new BroadcastReceiver(){
    public void onReceive(    Context context,    Intent intent){
      if (intent.getAction().equals(ACTION_ALRM_GPS_TIMEOUT)) {
        stopGPS();
      }
    }
  }
;
  IntentFilter intFilter=new IntentFilter(ACTION_ALRM_GPS_TIMEOUT);
  registerReceiver(bRecr,intFilter);
  if (mGpsTimeoutPI != null) {
    mAlarmMan.cancel(mGpsTimeoutPI);
    mGpsTimeoutPI.cancel();
  }
  mLatestLoc=null;
  mLocMan.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,this);
  mLocMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,this);
  Intent intent=new Intent(ACTION_ALRM_GPS_TIMEOUT);
  mGpsTimeoutPI=PendingIntent.getBroadcast(this,0,intent,PendingIntent.FLAG_CANCEL_CURRENT);
  mAlarmMan.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,SystemClock.elapsedRealtime() + MY_LOC_SAMPLE_TIMEOUT,mGpsTimeoutPI);
}
 

Example 16

From project Racenet-for-Android, under directory /src/org/racenet/.

Source file: NewsListActivity.java

  17 
vote

@Override public void onCreate(Bundle savedInstanceState){
  super.onCreate(savedInstanceState);
  setContentView(R.layout.newslist);
  mAdapter=new NewsListAdapter(this);
  setListAdapter(mAdapter);
  registerForContextMenu(getExpandableListView());
  broadcastReceiver=new BroadcastReceiver(){
    @Override public void onReceive(    Context context,    Intent intent){
      mAdapter.notifyDataSetChanged();
    }
  }
;
  db=new Database(getApplicationContext());
}
 

Example 17

From project SchoolPlanner4Untis, under directory /src/edu/htl3r/schoolplanner/.

Source file: SchoolPlannerApp.java

  17 
vote

@Override public void onCreate(){
  super.onCreate();
  initBackend();
  IntentFilter filter=new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
  registerReceiver(new BroadcastReceiver(){
    @Override public void onReceive(    Context context,    Intent intent){
      NetworkInfo info=intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
      setNetworkAvailable(info.isConnectedOrConnecting());
    }
  }
,filter);
}
 

Example 18

From project SMSSync, under directory /smssync/src/org/addhen/smssync/widget/.

Source file: SmsSyncAppWidgetProvider.java

  17 
vote

@Override public void onStart(final Intent intent,final int startId){
  final Runnable updateUI=new Runnable(){
    public void run(){
      String action=intent.getAction();
      if (INTENT_PREV.equals(action) || INTENT_NEXT.equals(action)) {
        buildUpdate(intent,startId);
      }
 else {
        if (INTENT_REFRESH.equals(action)) {
          pendingMsgIndex=0;
        }
        pendingMsgs=showMessages();
        buildUpdate(intent,startId);
      }
    }
  }
;
  ConnectivityManager cm=(ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
  if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected()) {
    new Thread(updateUI).start();
  }
 else {
    BroadcastReceiver networkChange=new BroadcastReceiver(){
      @Override public void onReceive(      Context context,      Intent intent){
        try {
          NetworkInfo ni=intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
          if (ni != null && ni.isConnected()) {
            new Thread(updateUI).start();
            SmsSyncAppWidgetService.this.unregisterReceiver(this);
          }
        }
 catch (        Exception e) {
          Log.e(CLASS_TAG,"receiver error",e);
        }
      }
    }
;
    registerReceiver(networkChange,new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
  }
}
 

Example 19

From project TextSecure, under directory /src/org/thoughtcrime/securesms/.

Source file: ConversationListActivity.java

  17 
vote

private void initializeKillReceiver(){
  this.killActivityReceiver=new BroadcastReceiver(){
    @Override public void onReceive(    Context context,    Intent intent){
      finish();
    }
  }
;
  registerReceiver(this.killActivityReceiver,new IntentFilter(KeyCachingService.PASSPHRASE_EXPIRED_EVENT),KeyCachingService.KEY_PERMISSION,null);
}
 

Example 20

From project tinfoil-sms, under directory /branches/prePhase0/src/com/tinfoil/sms/.

Source file: PrePhase0Activity.java

  17 
vote

/** 
 * Called when the activity is first created. 
 */
@Override public void onCreate(Bundle savedInstanceState){
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  final String SMS_RECEIVED="android.provider.Telephony.SMS_RECEIVED";
  BroadcastReceiver SMSbr=new BroadcastReceiver(){
    @Override public void onReceive(    Context context,    Intent intent){
      Bundle bundle=intent.getExtras();
      if (bundle != null) {
        Object[] pdus=(Object[])bundle.get("pdus");
        final SmsMessage[] messages=new SmsMessage[pdus.length];
        for (int i=0; i < pdus.length; i++)         messages[i]=SmsMessage.createFromPdu((byte[])pdus[i]);
        if (messages.length > -1) {
          String smsToast="New SMS received from " + messages[0].getOriginatingAddress() + "\n'Test"+ messages[0].getMessageBody()+ "'";
          Toast.makeText(context,smsToast,Toast.LENGTH_LONG).show();
          sendToSelf(messages[0].getOriginatingAddress(),Cipher.rot13(messages[0].getMessageBody()));
        }
      }
      this.abortBroadcast();
    }
  }
;
  IntentFilter SMSfilter=new IntentFilter(SMS_RECEIVED);
  this.registerReceiver(SMSbr,SMSfilter);
}
 

Example 21

From project WLANAudit-Android, under directory /WLANAudit/src/es/glasspixel/wlanaudit/activities/.

Source file: NetworkListActivity.java

  17 
vote

/** 
 * Sets up the logic to execute when a scan is complete. This is done this way because the SCAN_RESULTS_AVAILABLE_ACTION must be caught by a BroadCastReceiver.
 */
private void setupNetworkScanCallBack(){
  IntentFilter i=new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
  mCallBackReceiver=new BroadcastReceiver(){
    @Override public void onReceive(    Context context,    Intent intent){
      getListView().setAdapter(new WifiNetworkAdapter(NetworkListActivity.this,R.layout.network_list_element_layout,mWifiManager.getScanResults()));
    }
  }
;
  registerReceiver(mCallBackReceiver,i);
}
 

Example 22

From project yammp, under directory /src/org/yammp/.

Source file: MusicPlaybackService.java

  17 
vote

public void registerA2dpServiceListener(){
  mA2dpReceiver=new BroadcastReceiver(){
    @Override public void onReceive(    Context context,    Intent intent){
      String action=intent.getAction();
      if (BROADCAST_PLAYSTATUS_REQUEST.equals(action)) {
        notifyChange(BROADCAST_PLAYSTATUS_RESPONSE);
      }
    }
  }
;
  IntentFilter iFilter=new IntentFilter();
  iFilter.addAction(BROADCAST_PLAYSTATUS_REQUEST);
  registerReceiver(mA2dpReceiver,iFilter);
}
 

Example 23

From project Absolute-Android-RSS, under directory /src/com/AA/Activities/.

Source file: AAMain.java

  16 
vote

/** 
 * Called when the activity is created and put into memory. This is where all GUI elements should be set up and any other member variables that is used throughout the class
 */
@Override public void onCreate(Bundle savedInstanceState){
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  articles=new ArrayList<Article>();
  settings=this.getSharedPreferences("settings",0);
  AlarmReceiver.stopAlarm(this);
  adapter=new ArticleAdapter(this);
  this.setListAdapter(adapter);
  ib_refresh=(ImageButton)findViewById(R.id.ib_refresh);
  TextView tv=(TextView)findViewById(R.id.AATitle);
  Typeface face=Typeface.createFromAsset(getAssets(),"fonts/WREXHAM_.TTF");
  tv.setTypeface(face);
  finishReceiver=new BroadcastReceiver(){
    @Override public void onReceive(    Context context,    Intent intent){
      articles.clear();
      Bundle articleBundle=intent.getBundleExtra("articles");
      ArrayList<String> titles=articleBundle.getStringArrayList("titles");
      for (      String title : titles)       articles.add((Article)articleBundle.getSerializable(title));
      progressDialog.cancel();
      refresh();
    }
  }
;
  this.registerReceiver(finishReceiver,new IntentFilter("RSSFinish"));
  ib_refresh.setOnClickListener(new OnClickListener(){
    /** 
 * Handles when the user clicks the refresh button
 * @param v - view that was clicked
 */
    @Override public void onClick(    View v){
      runService();
    }
  }
);
  runService();
}
 

Example 24

From project android_5, under directory /src/aarddict/android/.

Source file: DictionaryService.java

  16 
vote

@Override public void onCreate(){
  Log.d(TAG,"On create");
  library=new Library();
  loadDictFileList();
  broadcastReceiver=new BroadcastReceiver(){
    @Override public void onReceive(    Context context,    Intent intent){
      String action=intent.getAction();
      Uri path=intent.getData();
      Log.d(TAG,String.format("action: %s, path: %s",action,path));
      stopSelf();
    }
  }
;
  IntentFilter intentFilter=new IntentFilter();
  intentFilter.addDataScheme("file");
  intentFilter.addAction(Intent.ACTION_MEDIA_EJECT);
  intentFilter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);
  intentFilter.addAction(Intent.ACTION_MEDIA_REMOVED);
  registerReceiver(broadcastReceiver,intentFilter);
}
 

Example 25

From project android_aosp_packages_apps_Settings, under directory /src/com/android/settings/wifi/.

Source file: WifiSettings.java

  16 
vote

public WifiSettings(){
  mFilter=new IntentFilter();
  mFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
  mFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
  mFilter.addAction(WifiManager.NETWORK_IDS_CHANGED_ACTION);
  mFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
  mFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
  mFilter.addAction(WifiManager.RSSI_CHANGED_ACTION);
  mReceiver=new BroadcastReceiver(){
    @Override public void onReceive(    Context context,    Intent intent){
      handleEvent(intent);
    }
  }
;
  mScanner=new Scanner();
}
 

Example 26

From project android_packages_apps_Gallery, under directory /src/com/android/camera/.

Source file: GalleryPicker.java

  16 
vote

@Override public void onCreate(Bundle icicle){
  super.onCreate(icicle);
  setContentView(R.layout.gallerypicker);
  mGridView=(GridView)findViewById(R.id.albums);
  mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
    public void onItemClick(    AdapterView<?> parent,    View view,    int position,    long id){
      launchFolderGallery(position);
    }
  }
);
  mGridView.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener(){
    public void onCreateContextMenu(    ContextMenu menu,    View v,    final ContextMenuInfo menuInfo){
      onCreateGalleryPickerContextMenu(menu,menuInfo);
    }
  }
);
  mReceiver=new BroadcastReceiver(){
    @Override public void onReceive(    Context context,    Intent intent){
      onReceiveMediaBroadcast(intent);
    }
  }
;
  mDbObserver=new ContentObserver(mHandler){
    @Override public void onChange(    boolean selfChange){
      rebake(false,ImageManager.isMediaScannerScanning(getContentResolver()));
    }
  }
;
  ImageManager.ensureOSXCompatibleFolder();
}
 

Example 27

From project android_packages_apps_phone, under directory /src/com/android/phone/.

Source file: DataUsageListener.java

  16 
vote

private void initialize(){
  mThrottleManager=(ThrottleManager)mContext.getSystemService(Context.THROTTLE_SERVICE);
  mStart=GregorianCalendar.getInstance();
  mEnd=GregorianCalendar.getInstance();
  mFilter=new IntentFilter();
  mFilter.addAction(ThrottleManager.THROTTLE_POLL_ACTION);
  mFilter.addAction(ThrottleManager.THROTTLE_ACTION);
  mFilter.addAction(ThrottleManager.POLICY_CHANGED_ACTION);
  mReceiver=new BroadcastReceiver(){
    @Override public void onReceive(    Context context,    Intent intent){
      String action=intent.getAction();
      if (ThrottleManager.THROTTLE_POLL_ACTION.equals(action)) {
        updateUsageStats(intent.getLongExtra(ThrottleManager.EXTRA_CYCLE_READ,0),intent.getLongExtra(ThrottleManager.EXTRA_CYCLE_WRITE,0),intent.getLongExtra(ThrottleManager.EXTRA_CYCLE_START,0),intent.getLongExtra(ThrottleManager.EXTRA_CYCLE_END,0));
      }
 else       if (ThrottleManager.POLICY_CHANGED_ACTION.equals(action)) {
        updatePolicy();
      }
 else       if (ThrottleManager.THROTTLE_ACTION.equals(action)) {
        updateThrottleRate(intent.getIntExtra(ThrottleManager.EXTRA_THROTTLE_LEVEL,-1));
      }
    }
  }
;
}
 

Example 28

From project Anki-Android, under directory /src/com/ichi2/anki/.

Source file: CardEditor.java

  16 
vote

/** 
 * Registers an intent to listen for ACTION_MEDIA_EJECT notifications.
 */
public void registerExternalStorageListener(){
  if (mUnmountReceiver == null) {
    mUnmountReceiver=new BroadcastReceiver(){
      @Override public void onReceive(      Context context,      Intent intent){
        String action=intent.getAction();
        if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
          finishNoStorageAvailable();
        }
      }
    }
;
    IntentFilter iFilter=new IntentFilter();
    iFilter.addAction(Intent.ACTION_MEDIA_EJECT);
    iFilter.addDataScheme("file");
    registerReceiver(mUnmountReceiver,iFilter);
  }
}
 

Example 29

From project BBC-News-Reader, under directory /src/com/digitallizard/bbcnewsreader/.

Source file: ResourceService.java

  16 
vote

@Override public void onCreate(){
  loadInProgress=false;
  if (settings == null) {
    settings=getSharedPreferences(ReaderActivity.PREFS_FILE_NAME,MODE_PRIVATE);
  }
  if (database == null) {
    setDatabase(new DatabaseHandler(this));
    if (!getDatabase().isCreated()) {
      getDatabase().addCategoriesFromXml();
    }
  }
  if (getWebManager() == null) {
    setWebManager(new WebManager(this));
  }
  if (rssManager == null) {
    rssManager=new RSSManager(this);
  }
  broadcastReceiver=new BroadcastReceiver(){
    @Override public void onReceive(    Context context,    Intent intent){
      if (intent.getAction().equals("com.digitallizard.bbcnewsreader.action.LOAD_NEWS")) {
        loadData();
      }
    }
  }
;
  this.registerReceiver(broadcastReceiver,new IntentFilter(ACTION_LOAD));
  updateSettings();
  settingsChangedListener=new OnSharedPreferenceChangeListener(){
    public void onSharedPreferenceChanged(    SharedPreferences preferences,    String key){
      updateSettings();
    }
  }
;
  settings.registerOnSharedPreferenceChangeListener(settingsChangedListener);
}
 

Example 30

From project Cafe, under directory /webapp/src/org/openqa/selenium/android/.

Source file: NetworkStateHandler.java

  16 
vote

public NetworkStateHandler(Activity activity,final WebView view){
  this.activity=activity;
  this.view=view;
  ConnectivityManager cm=(ConnectivityManager)activity.getSystemService(Context.CONNECTIVITY_SERVICE);
  NetworkInfo info=cm.getActiveNetworkInfo();
  if (info != null) {
    isConnected=info.isConnected();
    isNetworkUp=info.isAvailable();
  }
  filter=new IntentFilter();
  filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
  receiver=new BroadcastReceiver(){
    public void onReceive(    Context context,    Intent intent){
      if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
        NetworkInfo info=intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
        String typeName=info.getTypeName();
        String subType=info.getSubtypeName();
        isConnected=info.isConnected();
        if (view != null) {
          try {
            Method setNetworkType=view.getClass().getMethod("setNetworkType",String.class,String.class);
            setNetworkType.invoke(view,typeName,(subType == null ? "" : subType));
            boolean noConnection=intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,false);
            onNetworkChange(!noConnection);
          }
 catch (          Exception e) {
            throw new RuntimeException(e);
          }
        }
      }
    }
  }
;
}
 

Example 31

From project cicada, under directory /cicada/src/org/cicadasong/cicada/.

Source file: AppList.java

  16 
vote

@Override protected void onResume(){
  paint=new Paint();
  paint.setTypeface(Typeface.DEFAULT);
  if (apps == null) {
    loadApps();
  }
  IntentFilter filter=new IntentFilter();
  filter.addAction(PackageMonitor.INTENT_APPS_CHANGED);
  receiver=new BroadcastReceiver(){
    @Override public void onReceive(    Context context,    Intent intent){
      loadApps();
      changeSelection(selectedIndex);
    }
  }
;
  registerReceiver(receiver,filter);
}
 

Example 32

From project cornerstone, under directory /frameworks/base/services/java/com/android/server/am/.

Source file: ActivityManagerService.java

  16 
vote

final void finishBooting(){
  IntentFilter pkgFilter=new IntentFilter();
  pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
  pkgFilter.addDataScheme("package");
  mContext.registerReceiver(new BroadcastReceiver(){
    @Override public void onReceive(    Context context,    Intent intent){
      String[] pkgs=intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
      if (pkgs != null) {
        for (        String pkg : pkgs) {
synchronized (ActivityManagerService.this) {
            if (forceStopPackageLocked(pkg,-1,false,false,false,false)) {
              setResultCode(Activity.RESULT_OK);
              return;
            }
          }
        }
      }
    }
  }
,pkgFilter);
synchronized (this) {
    final int NP=mProcessesOnHold.size();
    if (NP > 0) {
      ArrayList<ProcessRecord> procs=new ArrayList<ProcessRecord>(mProcessesOnHold);
      for (int ip=0; ip < NP; ip++) {
        if (DEBUG_PROCESSES)         Slog.v(TAG,"Starting process on hold: " + procs.get(ip));
        startProcessLocked(procs.get(ip),"on-hold",null);
      }
    }
    if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
      Message nmsg=mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
      mHandler.sendMessageDelayed(nmsg,POWER_CHECK_DELAY);
      SystemProperties.set("sys.boot_completed","1");
      broadcastIntentLocked(null,null,new Intent(Intent.ACTION_BOOT_COMPLETED,null),null,null,0,null,null,android.Manifest.permission.RECEIVE_BOOT_COMPLETED,false,false,MY_PID,Process.SYSTEM_UID);
    }
  }
}
 

Example 33

From project creamed_glacier_app_settings, under directory /src/com/android/settings/wifi/.

Source file: WifiSettings.java

  16 
vote

public WifiSettings(){
  mFilter=new IntentFilter();
  mFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
  mFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
  mFilter.addAction(WifiManager.NETWORK_IDS_CHANGED_ACTION);
  mFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
  mFilter.addAction(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
  mFilter.addAction(WifiManager.LINK_CONFIGURATION_CHANGED_ACTION);
  mFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
  mFilter.addAction(WifiManager.RSSI_CHANGED_ACTION);
  mFilter.addAction(WifiManager.ERROR_ACTION);
  mReceiver=new BroadcastReceiver(){
    @Override public void onReceive(    Context context,    Intent intent){
      handleEvent(context,intent);
    }
  }
;
  mScanner=new Scanner();
}
 

Example 34

From project Cura, under directory /src/com/cura/.

Source file: AccountsListActivity.java

  16 
vote

@Override protected void onCreate(Bundle savedInstanceState){
  super.onCreate(savedInstanceState);
  this.setTitle(R.string.LoginScreenName);
  prefs=PreferenceManager.getDefaultSharedPreferences(this);
  rv=new regexValidator();
  user=getUser();
  array=new CustomArrayAdapter(this,user);
  setListAdapter(array);
  registerForContextMenu(getListView());
  databaseBR=new BroadcastReceiver(){
    @Override public void onReceive(    Context context,    Intent intent){
      user=getUser();
      array=new CustomArrayAdapter(AccountsListActivity.this,user);
      setListAdapter(array);
      Log.d("onResume","onResume");
    }
  }
;
  IntentFilter databaseIntentFilter=new IntentFilter();
  databaseIntentFilter.addAction(deleteDB);
  registerReceiver(databaseBR,databaseIntentFilter);
  vibrator=(Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
}
 

Example 35

From project filemanager, under directory /FileManager/src/org/openintents/filemanager/search/.

Source file: SearchableActivity.java

  16 
vote

private void handleIntent(){
  Intent intent=getIntent();
  if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
    String query=intent.getStringExtra(SearchManager.QUERY);
    setTitle(query);
    String path=null;
    if (intent.getBundleExtra(SearchManager.APP_DATA) != null)     path=intent.getBundleExtra(SearchManager.APP_DATA).getString(FileManagerIntents.EXTRA_SEARCH_INIT_PATH);
    SearchRecentSuggestions suggestions=new SearchRecentSuggestions(this,RecentsSuggestionsProvider.AUTHORITY,RecentsSuggestionsProvider.MODE);
    suggestions.saveRecentQuery(query,null);
    lbm.registerReceiver(new BroadcastReceiver(){
      @Override public void onReceive(      Context context,      Intent intent){
        setProgressBarIndeterminateVisibility(false);
      }
    }
,new IntentFilter(FileManagerIntents.ACTION_SEARCH_FINISHED));
    lbm.registerReceiver(new BroadcastReceiver(){
      @Override public void onReceive(      Context context,      Intent intent){
        setProgressBarIndeterminateVisibility(true);
      }
    }
,new IntentFilter(FileManagerIntents.ACTION_SEARCH_STARTED));
    searchResults=getSearchResults();
    setListAdapter(new SearchListAdapter(this,searchResults));
    Intent in=new Intent(this,SearchService.class);
    in.putExtra(FileManagerIntents.EXTRA_SEARCH_INIT_PATH,path);
    in.putExtra(FileManagerIntents.EXTRA_SEARCH_QUERY,query);
    startService(in);
  }
 else   if (Intent.ACTION_VIEW.equals(intent.getAction())) {
    browse(intent.getData());
  }
 else   setTitle(R.string.query_error);
}
 

Example 36

From project incubator-cordova-android, under directory /framework/src/org/apache/cordova/.

Source file: BatteryListener.java

  16 
vote

/** 
 * Executes the request.
 * @param action        	The action to execute.
 * @param args          	JSONArry of arguments for the plugin.
 * @param callbackContext 	The callback context used when calling back into JavaScript.
 * @return              	True if the action was valid, false if not.
 */
public boolean execute(String action,JSONArray args,CallbackContext callbackContext){
  if (action.equals("start")) {
    if (this.batteryCallbackContext != null) {
      callbackContext.error("Battery listener already running.");
      return true;
    }
    this.batteryCallbackContext=callbackContext;
    IntentFilter intentFilter=new IntentFilter();
    intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
    if (this.receiver == null) {
      this.receiver=new BroadcastReceiver(){
        @Override public void onReceive(        Context context,        Intent intent){
          updateBatteryInfo(intent);
        }
      }
;
      cordova.getActivity().registerReceiver(this.receiver,intentFilter);
    }
    PluginResult pluginResult=new PluginResult(PluginResult.Status.NO_RESULT);
    pluginResult.setKeepCallback(true);
    callbackContext.sendPluginResult(pluginResult);
    return true;
  }
 else   if (action.equals("stop")) {
    removeBatteryListener();
    this.sendUpdate(new JSONObject(),false);
    this.batteryCallbackContext=null;
    callbackContext.success();
    return true;
  }
  return false;
}
 

Example 37

From project keepassdroid, under directory /src/com/keepassdroid/services/.

Source file: TimeoutService.java

  16 
vote

@Override public void onCreate(){
  super.onCreate();
  mIntentReceiver=new BroadcastReceiver(){
    @Override public void onReceive(    Context context,    Intent intent){
      String action=intent.getAction();
      if (action.equals(Intents.TIMEOUT)) {
        timeout(context);
      }
    }
  }
;
  IntentFilter filter=new IntentFilter();
  filter.addAction(Intents.TIMEOUT);
  registerReceiver(mIntentReceiver,filter);
}
 

Example 38

From project MobiPerf, under directory /android/src/com/mobiperf/speedometer/.

Source file: MeasurementScheduleConsoleActivity.java

  16 
vote

@Override protected void onCreate(Bundle savedInstanceState){
  super.onCreate(savedInstanceState);
  this.setContentView(R.layout.measurement_schedule);
  taskMap=new HashMap<String,String>();
  parent=(SpeedometerApp)this.getParent();
  consoleContent=new ArrayAdapter<String>(this,R.layout.list_item);
  this.consoleView=(ListView)this.findViewById(R.id.measurementScheduleConsole);
  this.consoleView.setAdapter(consoleContent);
  lastCheckinTimeText=(TextView)this.findViewById(R.id.lastCheckinTime);
  Button checkinButton=(Button)this.findViewById(R.id.checkinButton);
  checkinButton.setOnClickListener(new OnClickListener(){
    @Override public void onClick(    View v){
      doCheckin();
    }
  }
);
  registerForContextMenu(consoleView);
  consoleView.setOnItemLongClickListener(new OnItemLongClickListener(){
    /** 
 * Records which item in the list is selected
 */
    @Override public boolean onItemLongClick(    AdapterView<?> parent,    View view,    int position,    long id){
      longClickedItemPosition=position;
      return false;
    }
  }
);
  IntentFilter filter=new IntentFilter();
  filter.addAction(UpdateIntent.SCHEDULER_CONNECTED_ACTION);
  filter.addAction(UpdateIntent.SYSTEM_STATUS_UPDATE_ACTION);
  this.receiver=new BroadcastReceiver(){
    @Override public void onReceive(    Context context,    Intent intent){
      Logger.d("MeasurementConsole got intent");
      updateConsole();
    }
  }
;
  registerReceiver(receiver,filter);
}
 

Example 39

From project packages_apps_Phone_1, under directory /src/com/android/phone/.

Source file: DataUsageListener.java

  16 
vote

private void initialize(){
  mThrottleManager=(ThrottleManager)mContext.getSystemService(Context.THROTTLE_SERVICE);
  mStart=GregorianCalendar.getInstance();
  mEnd=GregorianCalendar.getInstance();
  mFilter=new IntentFilter();
  mFilter.addAction(ThrottleManager.THROTTLE_POLL_ACTION);
  mFilter.addAction(ThrottleManager.THROTTLE_ACTION);
  mFilter.addAction(ThrottleManager.POLICY_CHANGED_ACTION);
  mReceiver=new BroadcastReceiver(){
    @Override public void onReceive(    Context context,    Intent intent){
      String action=intent.getAction();
      if (ThrottleManager.THROTTLE_POLL_ACTION.equals(action)) {
        updateUsageStats(intent.getLongExtra(ThrottleManager.EXTRA_CYCLE_READ,0),intent.getLongExtra(ThrottleManager.EXTRA_CYCLE_WRITE,0),intent.getLongExtra(ThrottleManager.EXTRA_CYCLE_START,0),intent.getLongExtra(ThrottleManager.EXTRA_CYCLE_END,0));
      }
 else       if (ThrottleManager.POLICY_CHANGED_ACTION.equals(action)) {
        updatePolicy();
      }
 else       if (ThrottleManager.THROTTLE_ACTION.equals(action)) {
        updateThrottleRate(intent.getIntExtra(ThrottleManager.EXTRA_THROTTLE_LEVEL,-1));
      }
    }
  }
;
}
 

Example 40

From project PartyWare, under directory /android/src/edu/stanford/junction/sample/partyware/.

Source file: PicturesActivity.java

  16 
vote

protected void startUpload(Uri localUri){
  mUriReceiver=new BroadcastReceiver(){
    @Override public void onReceive(    Context context,    Intent intent){
      unregisterReceiver(this);
      mUploadProgressDialog.dismiss();
      uploadFinishedHandler(intent);
    }
  }
;
  IntentFilter intentFilter=new IntentFilter(ImgurUploadService.BROADCAST_FINISHED);
  registerReceiver(mUriReceiver,intentFilter);
  mErrorReceiver=new BroadcastReceiver(){
    @Override public void onReceive(    Context context,    Intent intent){
      unregisterReceiver(this);
      mUploadProgressDialog.dismiss();
      String error=intent.getStringExtra("error");
      showDialog(error);
    }
  }
;
  intentFilter=new IntentFilter(ImgurUploadService.BROADCAST_FAILED);
  registerReceiver(mErrorReceiver,intentFilter);
  Intent i=new Intent(this,ImgurUploadService.class);
  i.setAction(Intent.ACTION_SEND);
  i.putExtra(Intent.EXTRA_STREAM,localUri);
  startService(i);
  mUploadProgressDialog=ProgressDialog.show(this,"","Uploading. Please wait...",true);
}
 

Example 41

From project platform_packages_apps_browser, under directory /src/com/android/browser/.

Source file: NetworkStateHandler.java

  16 
vote

public NetworkStateHandler(Activity activity,Controller controller){
  mActivity=activity;
  mController=controller;
  ConnectivityManager cm=(ConnectivityManager)mActivity.getSystemService(Context.CONNECTIVITY_SERVICE);
  NetworkInfo info=cm.getActiveNetworkInfo();
  if (info != null) {
    mIsNetworkUp=info.isAvailable();
  }
  mNetworkStateChangedFilter=new IntentFilter();
  mNetworkStateChangedFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
  mNetworkStateIntentReceiver=new BroadcastReceiver(){
    @Override public void onReceive(    Context context,    Intent intent){
      if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
        NetworkInfo info=intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
        String typeName=info.getTypeName();
        String subtypeName=info.getSubtypeName();
        sendNetworkType(typeName.toLowerCase(),(subtypeName != null ? subtypeName.toLowerCase() : ""));
        BrowserSettings.getInstance().updateConnectionType();
        boolean noConnection=intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,false);
        onNetworkToggle(!noConnection);
      }
    }
  }
;
}
 

Example 42

From project platform_packages_apps_CytownPhone, under directory /src/com/android/phone/.

Source file: DataUsageListener.java

  16 
vote

private void initialize(){
  mThrottleManager=(ThrottleManager)mContext.getSystemService(Context.THROTTLE_SERVICE);
  mStart=GregorianCalendar.getInstance();
  mEnd=GregorianCalendar.getInstance();
  mFilter=new IntentFilter();
  mFilter.addAction(ThrottleManager.THROTTLE_POLL_ACTION);
  mFilter.addAction(ThrottleManager.THROTTLE_ACTION);
  mFilter.addAction(ThrottleManager.POLICY_CHANGED_ACTION);
  mReceiver=new BroadcastReceiver(){
    @Override public void onReceive(    Context context,    Intent intent){
      String action=intent.getAction();
      if (ThrottleManager.THROTTLE_POLL_ACTION.equals(action)) {
        updateUsageStats(intent.getLongExtra(ThrottleManager.EXTRA_CYCLE_READ,0),intent.getLongExtra(ThrottleManager.EXTRA_CYCLE_WRITE,0),intent.getLongExtra(ThrottleManager.EXTRA_CYCLE_START,0),intent.getLongExtra(ThrottleManager.EXTRA_CYCLE_END,0));
      }
 else       if (ThrottleManager.POLICY_CHANGED_ACTION.equals(action)) {
        updatePolicy();
      }
 else       if (ThrottleManager.THROTTLE_ACTION.equals(action)) {
        updateThrottleRate(intent.getIntExtra(ThrottleManager.EXTRA_THROTTLE_LEVEL,-1));
      }
    }
  }
;
}
 

Example 43

From project platform_packages_apps_Gallery, under directory /src/com/android/camera/.

Source file: GalleryPicker.java

  16 
vote

@Override public void onCreate(Bundle icicle){
  super.onCreate(icicle);
  setContentView(R.layout.gallerypicker);
  mGridView=(GridView)findViewById(R.id.albums);
  mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
    public void onItemClick(    AdapterView<?> parent,    View view,    int position,    long id){
      launchFolderGallery(position);
    }
  }
);
  mGridView.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener(){
    public void onCreateContextMenu(    ContextMenu menu,    View v,    final ContextMenuInfo menuInfo){
      onCreateGalleryPickerContextMenu(menu,menuInfo);
    }
  }
);
  mReceiver=new BroadcastReceiver(){
    @Override public void onReceive(    Context context,    Intent intent){
      onReceiveMediaBroadcast(intent);
    }
  }
;
  mDbObserver=new ContentObserver(mHandler){
    @Override public void onChange(    boolean selfChange){
      rebake(false,ImageManager.isMediaScannerScanning(getContentResolver()));
    }
  }
;
  ImageManager.ensureOSXCompatibleFolder();
}
 

Example 44

From project platform_packages_apps_music, under directory /src/com/android/music/.

Source file: MediaPlaybackService.java

  16 
vote

/** 
 * Registers an intent to listen for ACTION_MEDIA_EJECT notifications. The intent will call closeExternalStorageFiles() if the external media is going to be ejected, so applications can clean up any files they have open.
 */
public void registerExternalStorageListener(){
  if (mUnmountReceiver == null) {
    mUnmountReceiver=new BroadcastReceiver(){
      @Override public void onReceive(      Context context,      Intent intent){
        String action=intent.getAction();
        if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
          saveQueue(true);
          mQueueIsSaveable=false;
          closeExternalStorageFiles(intent.getData().getPath());
        }
 else         if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
          mMediaMountedCount++;
          mCardId=MusicUtils.getCardId(MediaPlaybackService.this);
          reloadQueue();
          mQueueIsSaveable=true;
          notifyChange(QUEUE_CHANGED);
          notifyChange(META_CHANGED);
        }
      }
    }
;
    IntentFilter iFilter=new IntentFilter();
    iFilter.addAction(Intent.ACTION_MEDIA_EJECT);
    iFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
    iFilter.addDataScheme("file");
    registerReceiver(mUnmountReceiver,iFilter);
  }
}
 

Example 45

From project platform_packages_apps_phone, under directory /src/com/android/phone/.

Source file: DataUsageListener.java

  16 
vote

private void initialize(){
  mThrottleManager=(ThrottleManager)mContext.getSystemService(Context.THROTTLE_SERVICE);
  mStart=GregorianCalendar.getInstance();
  mEnd=GregorianCalendar.getInstance();
  mFilter=new IntentFilter();
  mFilter.addAction(ThrottleManager.THROTTLE_POLL_ACTION);
  mFilter.addAction(ThrottleManager.THROTTLE_ACTION);
  mFilter.addAction(ThrottleManager.POLICY_CHANGED_ACTION);
  mReceiver=new BroadcastReceiver(){
    @Override public void onReceive(    Context context,    Intent intent){
      String action=intent.getAction();
      if (ThrottleManager.THROTTLE_POLL_ACTION.equals(action)) {
        updateUsageStats(intent.getLongExtra(ThrottleManager.EXTRA_CYCLE_READ,0),intent.getLongExtra(ThrottleManager.EXTRA_CYCLE_WRITE,0),intent.getLongExtra(ThrottleManager.EXTRA_CYCLE_START,0),intent.getLongExtra(ThrottleManager.EXTRA_CYCLE_END,0));
      }
 else       if (ThrottleManager.POLICY_CHANGED_ACTION.equals(action)) {
        updatePolicy();
      }
 else       if (ThrottleManager.THROTTLE_ACTION.equals(action)) {
        updateThrottleRate(intent.getIntExtra(ThrottleManager.EXTRA_THROTTLE_LEVEL,-1));
      }
    }
  }
;
}
 

Example 46

From project platform_packages_apps_settings, under directory /src/com/android/settings/wifi/.

Source file: WifiSettings.java

  16 
vote

public WifiSettings(){
  mFilter=new IntentFilter();
  mFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
  mFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
  mFilter.addAction(WifiManager.NETWORK_IDS_CHANGED_ACTION);
  mFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
  mFilter.addAction(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
  mFilter.addAction(WifiManager.LINK_CONFIGURATION_CHANGED_ACTION);
  mFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
  mFilter.addAction(WifiManager.RSSI_CHANGED_ACTION);
  mReceiver=new BroadcastReceiver(){
    @Override public void onReceive(    Context context,    Intent intent){
      handleEvent(context,intent);
    }
  }
;
  mScanner=new Scanner();
}
 

Example 47

From project Playlist, under directory /src/edu/stanford/junction/sample/partyware/playlist/.

Source file: PicturesActivity.java

  16 
vote

protected void startUpload(Uri localUri){
  mUriReceiver=new BroadcastReceiver(){
    @Override public void onReceive(    Context context,    Intent intent){
      unregisterReceiver(this);
      mUploadProgressDialog.dismiss();
      uploadFinishedHandler(intent);
    }
  }
;
  IntentFilter intentFilter=new IntentFilter(ImgurUploadService.BROADCAST_FINISHED);
  registerReceiver(mUriReceiver,intentFilter);
  mErrorReceiver=new BroadcastReceiver(){
    @Override public void onReceive(    Context context,    Intent intent){
      unregisterReceiver(this);
      mUploadProgressDialog.dismiss();
      String error=intent.getStringExtra("error");
      showDialog(error);
    }
  }
;
  intentFilter=new IntentFilter(ImgurUploadService.BROADCAST_FAILED);
  registerReceiver(mErrorReceiver,intentFilter);
  Intent i=new Intent(this,ImgurUploadService.class);
  i.setAction(Intent.ACTION_SEND);
  i.putExtra(Intent.EXTRA_STREAM,localUri);
  startService(i);
  mUploadProgressDialog=ProgressDialog.show(this,"","Uploading. Please wait...",true);
}
 

Example 48

From project PowerTutor, under directory /src/edu/umich/PowerTutor/components/.

Source file: LCD.java

  16 
vote

public LCD(Context context){
  this.context=context;
  screenOn=true;
  if (context == null) {
    return;
  }
  foregroundDetector=new ForegroundDetector((ActivityManager)context.getSystemService(context.ACTIVITY_SERVICE));
  broadcastReceiver=new BroadcastReceiver(){
    public void onReceive(    Context context,    Intent intent){
synchronized (this) {
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
          screenOn=false;
        }
 else         if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
          screenOn=true;
        }
      }
    }
  }
;
  IntentFilter intentFilter=new IntentFilter();
  intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
  intentFilter.addAction(Intent.ACTION_SCREEN_ON);
  context.registerReceiver(broadcastReceiver,intentFilter);
  for (int i=0; i < BACKLIGHT_BRIGHTNESS_FILES.length; i++) {
    if (new File(BACKLIGHT_BRIGHTNESS_FILES[i]).exists()) {
      brightnessFile=BACKLIGHT_BRIGHTNESS_FILES[i];
    }
  }
}
 

Example 49

From project roman10-android-tutorial, under directory /dash/src/roman10/media/dash/.

Source file: VideoBrowser.java

  16 
vote

@Override public void onCreate(Bundle icicle){
  super.onCreate(icicle);
  mContext=this.getApplicationContext();
  self=this;
  FileUtilsStatic.initDirs();
  upladInterruptedReceiver=new BroadcastReceiver(){
    @Override public void onReceive(    Context arg0,    Intent arg1){
      Bundle b=arg1.getExtras();
      if (b != null) {
        if (b.getString("action").compareTo(upladInterruptedReceiver_ACTION) == 0) {
          Log.e("receiver","upload interrupted");
          checkIfWeCanUpload();
        }
      }
    }
  }
;
  IntentFilter filter=new IntentFilter();
  filter.addAction(Intent.ACTION_ATTACH_DATA);
  mContext.registerReceiver(upladInterruptedReceiver,filter);
  initUI();
}
 

Example 50

From project safe, under directory /Safe/src/org/openintents/safe/service/.

Source file: ServiceDispatchImpl.java

  16 
vote

@Override public void onCreate(){
  super.onCreate();
  mIntentReceiver=new BroadcastReceiver(){
    public void onReceive(    Context context,    Intent intent){
      if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
        if (debug)         Log.d(TAG,"caught ACTION_SCREEN_OFF");
        if (lockOnScreenLock) {
          stopSelf();
        }
      }
 else       if (intent.getAction().equals(CryptoIntents.ACTION_RESTART_TIMER)) {
        restartTimer();
      }
    }
  }
;
  IntentFilter filter=new IntentFilter();
  filter.addAction(CryptoIntents.ACTION_RESTART_TIMER);
  filter.addAction(Intent.ACTION_SCREEN_OFF);
  registerReceiver(mIntentReceiver,filter);
  if (debug)   Log.d(TAG,"onCreate");
}
 

Example 51

From project Speedometer, under directory /android/src/com/google/wireless/speed/speedometer/.

Source file: MeasurementScheduleConsoleActivity.java

  16 
vote

@Override protected void onCreate(Bundle savedInstanceState){
  super.onCreate(savedInstanceState);
  this.setContentView(R.layout.measurement_schedule);
  taskMap=new HashMap<String,String>();
  parent=(SpeedometerApp)this.getParent();
  consoleContent=new ArrayAdapter<String>(this,R.layout.list_item);
  this.consoleView=(ListView)this.findViewById(R.id.measurementScheduleConsole);
  this.consoleView.setAdapter(consoleContent);
  lastCheckinTimeText=(TextView)this.findViewById(R.id.lastCheckinTime);
  Button checkinButton=(Button)this.findViewById(R.id.checkinButton);
  checkinButton.setOnClickListener(new OnClickListener(){
    @Override public void onClick(    View v){
      doCheckin();
    }
  }
);
  registerForContextMenu(consoleView);
  consoleView.setOnItemLongClickListener(new OnItemLongClickListener(){
    /** 
 * Records which item in the list is selected
 */
    @Override public boolean onItemLongClick(    AdapterView<?> parent,    View view,    int position,    long id){
      longClickedItemPosition=position;
      return false;
    }
  }
);
  IntentFilter filter=new IntentFilter();
  filter.addAction(UpdateIntent.SCHEDULER_CONNECTED_ACTION);
  filter.addAction(UpdateIntent.SYSTEM_STATUS_UPDATE_ACTION);
  this.receiver=new BroadcastReceiver(){
    @Override public void onReceive(    Context context,    Intent intent){
      Logger.d("MeasurementConsole got intent");
      updateConsole();
    }
  }
;
  registerReceiver(receiver,filter);
}
 

Example 52

From project SyncMyPix, under directory /src/com/nloko/android/.

Source file: PhotoCache.java

  16 
vote

private void startWatchingExternalStorage(){
  Context context=mContext.get();
  if (context == null) {
    return;
  }
  Log.v(TAG,"Registering BroadcastReceiver");
  mExternalStorageReceiver=new BroadcastReceiver(){
    @Override public void onReceive(    Context context,    Intent intent){
      Log.d(TAG,"Storage: " + intent.getData());
      updateExternalStorageState();
    }
  }
;
  IntentFilter filter=new IntentFilter();
  filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
  filter.addAction(Intent.ACTION_MEDIA_REMOVED);
  filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
  filter.addDataScheme("file");
  context.registerReceiver(mExternalStorageReceiver,filter);
  updateExternalStorageState();
}
 

Example 53

From project todo.txt-touch, under directory /src/com/todotxt/todotxttouch/.

Source file: LoginScreen.java

  16 
vote

@Override protected void onCreate(Bundle savedInstanceState){
  super.onCreate(savedInstanceState);
  setContentView(R.layout.login);
  m_app=(TodoApplication)getApplication();
  findViewById(R.id.loginbackground).getBackground().setDither(true);
  IntentFilter intentFilter=new IntentFilter();
  intentFilter.addAction("com.todotxt.todotxttouch.ACTION_LOGIN");
  m_broadcastReceiver=new BroadcastReceiver(){
    @Override public void onReceive(    Context context,    Intent intent){
      Intent i=new Intent(context,TodoTxtTouch.class);
      startActivity(i);
      finish();
    }
  }
;
  registerReceiver(m_broadcastReceiver,intentFilter);
  m_LoginButton=(Button)findViewById(R.id.login);
  m_LoginButton.setOnClickListener(new OnClickListener(){
    public void onClick(    View v){
      startLogin();
    }
  }
);
  RemoteClient remoteClient=m_app.getRemoteClientManager().getRemoteClient();
  if (remoteClient.isAuthenticated()) {
    switchToTodolist();
  }
}
 

Example 54

From project xinkvpn, under directory /main/src/activity/xink/vpn/.

Source file: VpnSettings.java

  16 
vote

private void registerReceivers(){
  IntentFilter filter=new IntentFilter();
  filter.addAction(ACTION_VPN_CONNECTIVITY);
  stateBroadcastReceiver=new BroadcastReceiver(){
    @Override public void onReceive(    final Context context,    final Intent intent){
      String action=intent.getAction();
      if (ACTION_VPN_CONNECTIVITY.equals(action)) {
        onStateChanged(intent);
      }
 else {
        Log.d(TAG,"VPNSettings receiver ignores intent:" + intent);
      }
    }
  }
;
  registerReceiver(stateBroadcastReceiver,filter);
}
 

Example 55

From project cw-omnibus, under directory /CPU-Java/GoAsync/src/com/commonsware/android/tuning/goasync/.

Source file: AsyncReceiver.java

  15 
vote

@Override public void onReceive(Context context,Intent intent){
  final BroadcastReceiver.PendingResult result=goAsync();
  (new Thread(){
    public void run(){
      SystemClock.sleep(7000);
      result.finish();
    }
  }
).start();
}
 

Example 56

From project droidkit, under directory /src/org/droidkit/.

Source file: DroidKit.java

  15 
vote

public static boolean tryUnregisterReceiver(BroadcastReceiver receiver){
  try {
    sApplicationContext.unregisterReceiver(receiver);
    return true;
  }
 catch (  Throwable t) {
    return false;
  }
}
 

Example 57

From project Gaggle, under directory /src/com/geeksville/maps/.

Source file: PrefetchMapActivity.java

  15 
vote

public DownloadTilesTask(){
  final IRegisterReceiver registerReceiver=new IRegisterReceiver(){
    @Override public Intent registerReceiver(    final BroadcastReceiver aReceiver,    final IntentFilter aFilter){
      return PrefetchMapActivity.this.registerReceiver(aReceiver,aFilter);
    }
    @Override public void unregisterReceiver(    BroadcastReceiver receiver){
      PrefetchMapActivity.this.unregisterReceiver(receiver);
    }
  }
;
  tilesource=new OpenStreetMapTileFilesystemProvider(this,registerReceiver);
}
 

Example 58

From project HeLauncher, under directory /src/mobi/intuitit/android/widget/.

Source file: WidgetSpace.java

  15 
vote

/** 
 * So en exception in unregistering last receiver will not bypass the second one
 * @param context
 * @param receiver
 */
void unregisterReceiver(Context context,BroadcastReceiver receiver){
  try {
    context.unregisterReceiver(receiver);
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
}
 

Example 59

From project mp3tunes-android, under directory /src/com/mp3tunes/android/activity/.

Source file: QueueBrowser.java

  15 
vote

/** 
 * Unregister a receiver, but eat the exception that is thrown if the receiver was never registered to begin with. This is a little easier than keeping track of whether the receivers have actually been registered by the time onDestroy() is called.
 */
private void unregisterReceiverSafe(BroadcastReceiver receiver){
  try {
    unregisterReceiver(receiver);
  }
 catch (  IllegalArgumentException e) {
  }
}
 

Example 60

From project platform_frameworks_support, under directory /v4/java/android/support/v4/content/.

Source file: LocalBroadcastManager.java

  15 
vote

/** 
 * Register a receive for any local broadcasts that match the given IntentFilter.
 * @param receiver The BroadcastReceiver to handle the broadcast.
 * @param filter Selects the Intent broadcasts to be received.
 * @see #unregisterReceiver
 */
public void registerReceiver(BroadcastReceiver receiver,IntentFilter filter){
synchronized (mReceivers) {
    ReceiverRecord entry=new ReceiverRecord(filter,receiver);
    ArrayList<IntentFilter> filters=mReceivers.get(receiver);
    if (filters == null) {
      filters=new ArrayList<IntentFilter>(1);
      mReceivers.put(receiver,filters);
    }
    filters.add(filter);
    for (int i=0; i < filter.countActions(); i++) {
      String action=filter.getAction(i);
      ArrayList<ReceiverRecord> entries=mActions.get(action);
      if (entries == null) {
        entries=new ArrayList<ReceiverRecord>(1);
        mActions.put(action,entries);
      }
      entries.add(entry);
    }
  }
}
 

Example 61

From project platform_packages_apps_calendar, under directory /src/com/android/calendar/.

Source file: Utils.java

  15 
vote

public static BroadcastReceiver setTimeChangesReceiver(Context c,Runnable callback){
  IntentFilter filter=new IntentFilter();
  filter.addAction(Intent.ACTION_TIME_CHANGED);
  filter.addAction(Intent.ACTION_DATE_CHANGED);
  filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
  filter.addAction(Intent.ACTION_LOCALE_CHANGED);
  CalendarBroadcastReceiver r=new CalendarBroadcastReceiver(callback);
  c.registerReceiver(r,filter);
  return r;
}
 

Example 62

From project RA_Launcher, under directory /src/mobi/intuitit/android/widget/.

Source file: WidgetSpace.java

  15 
vote

/** 
 * So en exception in unregistering last receiver will not bypass the second one
 * @param context
 * @param receiver
 */
void unregisterReceiver(Context context,BroadcastReceiver receiver){
  try {
    context.unregisterReceiver(receiver);
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
}
 

Example 63

From project RebeLauncher, under directory /src/mobi/intuitit/android/widget/.

Source file: WidgetSpace.java

  15 
vote

/** 
 * So en exception in unregistering last receiver will not bypass the second one
 * @param context
 * @param receiver
 */
void unregisterReceiver(Context context,BroadcastReceiver receiver){
  try {
    context.unregisterReceiver(receiver);
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
}
 

Example 64

From project sonet, under directory /core/src/mobi/intuitit/android/widget/.

Source file: WidgetSpace.java

  15 
vote

/** 
 * So en exception in unregistering last receiver will not bypass the second one
 * @param context
 * @param receiver
 */
void unregisterReceiver(Context context,BroadcastReceiver receiver){
  try {
    context.unregisterReceiver(receiver);
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
}
 

Example 65

From project Ushahidi_Android, under directory /Libraries/abs/src/android/support/v4/content/.

Source file: LocalBroadcastManager.java

  15 
vote

/** 
 * Register a receive for any local broadcasts that match the given IntentFilter.
 * @param receiver The BroadcastReceiver to handle the broadcast.
 * @param filter Selects the Intent broadcasts to be received.
 * @see #unregisterReceiver
 */
public void registerReceiver(BroadcastReceiver receiver,IntentFilter filter){
synchronized (mReceivers) {
    ReceiverRecord entry=new ReceiverRecord(filter,receiver);
    ArrayList<IntentFilter> filters=mReceivers.get(receiver);
    if (filters == null) {
      filters=new ArrayList<IntentFilter>(1);
      mReceivers.put(receiver,filters);
    }
    filters.add(filter);
    for (int i=0; i < filter.countActions(); i++) {
      String action=filter.getAction(i);
      ArrayList<ReceiverRecord> entries=mActions.get(action);
      if (entries == null) {
        entries=new ArrayList<ReceiverRecord>(1);
        mActions.put(action,entries);
      }
      entries.add(entry);
    }
  }
}