Example usage for android.content ServiceConnection ServiceConnection

List of usage examples for android.content ServiceConnection ServiceConnection

Introduction

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

Prototype

ServiceConnection

Source Link

Usage

From source file:io.teak.sdk.GooglePlay.java

public void init(Context context) {
    mContext = context;// w w  w. j  a va  2 s .  c o  m

    mServiceConn = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            if (Teak.isDebug) {
                Log.d(LOG_TAG, "Google Play Billing service disconnected.");
            }
            mService = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            if (mDisposed)
                return;
            if (Teak.isDebug) {
                Log.d(LOG_TAG, "Google Play Billing service connected.");
            }

            try {
                Class<?> cls = Class.forName("com.android.vending.billing.IInAppBillingService$Stub");
                Method m = cls.getMethod("asInterface", IBinder.class);
                mService = m.invoke(null, (Object) service);
            } catch (Exception e) {
                Log.e(LOG_TAG,
                        "Unable to use 'IInAppBillingService' via reflection. " + Log.getStackTraceString(e));
                Teak.sdkRaven.reportException(e);
                return;
            }

            String packageName = mContext.getPackageName();
            try {
                if (Teak.isDebug) {
                    Log.d(LOG_TAG, "Checking for Google Play in-app billing 3 support.");
                }

                // check for in-app billing v3 support
                Class<?> cls = Class.forName("com.android.vending.billing.IInAppBillingService");
                Method m = cls.getMethod("isBillingSupported", int.class, String.class, String.class);
                int response = (Integer) m.invoke(mService, 3, packageName, ITEM_TYPE_INAPP);
                if (response != BILLING_RESPONSE_RESULT_OK) {
                    Log.e(LOG_TAG, "Error checking for Google Play billing v3 support.");
                } else {
                    if (Teak.isDebug) {
                        Log.d(LOG_TAG, "Google Play In-app billing version 3 supported for " + packageName);
                    }
                }

                // Check for v5 subscriptions support. This is needed for
                // getBuyIntentToReplaceSku which allows for subscription update
                response = (Integer) m.invoke(mService, 5, packageName, ITEM_TYPE_SUBS);
                if (response == BILLING_RESPONSE_RESULT_OK) {
                    if (Teak.isDebug) {
                        Log.d(LOG_TAG, "Google Play Subscription re-signup available.");
                        Log.d(LOG_TAG, "Google Play Subscriptions available.");
                    }
                } else {
                    if (Teak.isDebug) {
                        Log.d(LOG_TAG, "Google Play Subscription re-signup not available.");
                    }
                    // check for v3 subscriptions support
                    response = (Integer) m.invoke(mService, 3, packageName, ITEM_TYPE_SUBS);
                    if (response == BILLING_RESPONSE_RESULT_OK) {
                        if (Teak.isDebug) {
                            Log.d(LOG_TAG, "Google Play Subscriptions available.");
                        }
                    } else {
                        if (Teak.isDebug) {
                            Log.d(LOG_TAG, "Google Play Subscriptions NOT available. Response: " + response);
                        }
                    }
                }
            } catch (Exception e) {
                Log.e(LOG_TAG, "Error working with InAppBillingService: " + Log.getStackTraceString(e));
                Teak.sdkRaven.reportException(e);
            }
        }
    };

    Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
    serviceIntent.setPackage("com.android.vending");
    List<ResolveInfo> intentServices = mContext.getPackageManager().queryIntentServices(serviceIntent, 0);
    if (intentServices != null && !intentServices.isEmpty()) {
        mContext.bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);
    } else {
        Log.e(LOG_TAG, "Google Play Billing service unavailable on device.");
    }
}

From source file:org.scratch.microwebserver.MicrowebserverActivity.java

protected void connectService() {
    Intent serviceIntent = new Intent(this.getApplicationContext(), MicrowebserverService.class);

    sconn = new ServiceConnection() {

        @Override//from w ww .j  a  v a  2  s. c o m
        public void onServiceConnected(ComponentName name, IBinder service) {
            if (name.getClassName().equals("org.scratch.microwebserver.MicrowebserverService")) {
                binder = ((MicrowebserverServiceBinder) service);

                //global adapter ;)
                lea = binder.getLogEntryAdapter();

                binder.registerServiceListener(MicrowebserverActivity.this);

                setContentView(R.layout.main);

                statusImage = (ImageView) findViewById(R.id.StatusImage);
                statusImage.setOnClickListener(MicrowebserverActivity.this);
                statusText = (TextView) findViewById(R.id.statusText);
                socketInfo = (TextView) findViewById(R.id.socketInfo);
                //logList=(ListView)findViewById(R.id.logList);
                logList.setAdapter(lea);

                runOnUiThread(new Runnable() {
                    public void run() {
                        logList.setSelection(lea.getCount());
                    }
                });

                Vector<WebService> wss = new Vector<WebService>();
                //add remote AND local (TODO !)
                wss.addAll(binder.getRegisteredRemoteWebServices());

                sea = new ServiceAdapter(getPackageManager(), wss);
                serviceList.setAdapter(sea);

                //pager
                pager = (ViewPager) findViewById(R.id.pager);
                pager.setAdapter(new APagerAdapter());

                //Bind the title indicator to the adapter
                TitlePageIndicator indicator = (TitlePageIndicator) findViewById(R.id.pagertitles);

                final float density = getResources().getDisplayMetrics().density;

                TypedValue tv = new TypedValue();

                try {
                    //fgcol (line/footer)
                    getApplicationContext().getTheme().resolveAttribute(android.R.attr.colorActivatedHighlight,
                            tv, true);
                    indicator.setFooterColor(getResources().getColor(tv.resourceId));
                    //logList.getDivider().setColorFilter(getResources().getColor(tv.resourceId),Mode.MULTIPLY);
                } catch (Resources.NotFoundException rnfe) {
                }

                indicator.setFooterLineHeight(1 * density); //1dp
                indicator.setFooterIndicatorHeight(2 * density); //2dp
                indicator.setFooterIndicatorStyle(IndicatorStyle.Underline);

                //textcol
                TypedValue tv2 = new TypedValue();

                try {
                    getApplicationContext().getTheme().resolveAttribute(android.R.attr.colorActivatedHighlight,
                            tv2, true);
                    indicator.setTextColor(getResources().getColor(tv2.resourceId));
                } catch (Resources.NotFoundException rnfe) {
                }

                //selectedtextcol
                TypedValue tv3 = new TypedValue();
                getApplicationContext().getTheme().resolveAttribute(android.R.attr.colorForeground, tv3, true);
                indicator.setSelectedColor(getResources().getColor(tv3.resourceId));

                indicator.setSelectedBold(true);

                indicator.setViewPager(pager);

                if (binder.isServerUp()) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            statusText.setText("Started");
                            socketInfo.setText(Arrays.toString(binder.getListeningAdresses().toArray()));
                            statusImage.setImageResource(R.drawable.indicator_started);
                        }
                    });
                } else {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            statusText.setText("Stopped");
                            socketInfo.setText("");
                            statusImage.setImageResource(R.drawable.indicator_stopped);
                        }
                    });
                }
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            if (name.getClassName().equals("comtec.tool.wifilogger.WifiLoggerService")) {
                // TODO: implement, do stuff here ?
            }
        }

    };

    startService(serviceIntent);

    if (!bindService(serviceIntent, sconn, BIND_AUTO_CREATE)) {
        Log.e(PropertyNames.LOGGERNAME.toString(), "ARGH !!!!");
        // TOOOOOOOAST ! or a dialog ... whatever this SHOULD not happen at
        // all ...
    } else {

    }
}

From source file:org.envirocar.app.application.service.DeviceInRangeService.java

private void bindToBackgroundService() {
    if (!bindService(new Intent(this, BackgroundServiceImpl.class), new ServiceConnection() {

        @Override//www .  ja v  a2s .c  o m
        public void onServiceDisconnected(ComponentName name) {
            logger.info(String.format("BackgroundService %S disconnected!", name.flattenToString()));
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            backgroundService = (BackgroundServiceInteractor) service;
        }
    }, 0)) {
        logger.warn("Could not connect to BackgroundService.");
    }
}

From source file:com.turbulenz.turbulenz.googlepayment.java

public googlepayment(Activity activity, int purchaseRequestCode) {
    mActivity = activity;//from www  .  ja  v  a 2 s  . c o m
    mPurchaseRequestCode = purchaseRequestCode;

    // Just listens for connection / disconnection
    mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            _log("service disconnected :(");
            mService = null;
            mReady = false;
            reportReady(false);
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            _log("service connected :)");
            mService = IInAppBillingService.Stub.asInterface(service);

            String packageName = mActivity.getPackageName();
            _log("checking for billing.3 in " + packageName + "...");
            try {
                int response = mService.isBillingSupported(3, packageName, ITEM_TYPE_INAPP);
                if (BILLING_RESPONSE_RESULT_OK == response) {
                    mReady = true;
                } else {
                    _log("billing v3 not supported for this package");
                }
            } catch (RemoteException e) {
                _error("remoteexception:");
                e.printStackTrace();
            }

            reportReady(mReady);
        }
    };

    _log("binding service ...");
    boolean bound = activity.bindService(new Intent("com.android.vending.billing.InAppBillingService.BIND"),
            mServiceConnection, Context.BIND_AUTO_CREATE);
    _log("back from bindService: bound: " + Boolean.toString(bound));
}

From source file:src.com.nustats.pacelogger.RecordingActivity.java

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

    setContentView(R.layout.recording);/*www .j  a  va 2 s .  c  o  m*/

    txtStat = (TextView) findViewById(R.id.TextRecordStats);
    txtDistance = (TextView) findViewById(R.id.TextDistance);
    txtDuration = (TextView) findViewById(R.id.TextDuration);
    txtCurSpeed = (TextView) findViewById(R.id.TextSpeed);
    txtMaxSpeed = (TextView) findViewById(R.id.TextMaxSpeed);
    txtAvgSpeed = (TextView) findViewById(R.id.TextAvgSpeed);

    pauseButton = (Button) findViewById(R.id.ButtonPause);
    finishButton = (Button) findViewById(R.id.ButtonFinished);

    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

    // Query the RecordingService to figure out what to do.
    Intent rService = new Intent(this, RecordingService.class);
    startService(rService);
    ServiceConnection sc = new ServiceConnection() {
        public void onServiceDisconnected(ComponentName name) {
        }

        public void onServiceConnected(ComponentName name, IBinder service) {
            IRecordService rs = (IRecordService) service;

            switch (rs.getState()) {
            // If recording service is idle, start recording
            case RecordingService.STATE_IDLE:
                trip = TripData.createTrip(RecordingActivity.this);
                rs.startRecording(trip);
                isRecording = true;
                RecordingActivity.this.pauseButton.setEnabled(true);
                RecordingActivity.this.setTitle("PaceLogger - Recording...");
                break;
            // If recording service is recording, fetch data
            case RecordingService.STATE_RECORDING:
                long id = rs.getCurrentTrip();
                trip = TripData.fetchTrip(RecordingActivity.this, id);
                isRecording = true;
                RecordingActivity.this.pauseButton.setEnabled(true);
                RecordingActivity.this.setTitle("PaceLogger - Recording...");
                break;
            // If recording service is paused, fetch data, display resume option
            case RecordingService.STATE_PAUSED:
                long tid = rs.getCurrentTrip();
                isRecording = false;
                trip = TripData.fetchTrip(RecordingActivity.this, tid);
                RecordingActivity.this.pauseButton.setEnabled(true);
                RecordingActivity.this.pauseButton.setText("Resume");
                RecordingActivity.this.setTitle("PaceLogger - Paused...");
                break;
            case RecordingService.STATE_FULL:
                // Should never get here, right?
                break;
            }
            rs.setListener(RecordingActivity.this);
            unbindService(this);
        }
    };
    bindService(rService, sc, Context.BIND_AUTO_CREATE);

    // Pause button
    pauseButton.setEnabled(false);
    pauseButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            isRecording = !isRecording;
            if (isRecording) {
                pauseButton.setText("Pause");
                RecordingActivity.this.setTitle("PaceLogger - Recording...");
                // Don't include pause time in trip duration
                if (trip.pauseStartedAt > 0) {
                    trip.totalPauseTime += (System.currentTimeMillis() - trip.pauseStartedAt);
                    trip.pauseStartedAt = 0;
                }
                Toast.makeText(getBaseContext(), "GPS restarted. It may take a moment to resync.",
                        Toast.LENGTH_LONG).show();
            } else {
                pauseButton.setText("Resume");
                RecordingActivity.this.setTitle("PaceLogger - Paused...");
                trip.pauseStartedAt = System.currentTimeMillis();
                Toast.makeText(getBaseContext(), "Recording paused; GPS now offline", Toast.LENGTH_LONG).show();
            }
            RecordingActivity.this.setListener();
        }
    });

    // Finish button
    finishButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // If we have points, go to the save-trip activity
            if (trip.numpoints > 0) {
                // Handle pause time gracefully
                if (trip.pauseStartedAt > 0) {
                    trip.totalPauseTime += (System.currentTimeMillis() - trip.pauseStartedAt);
                }
                if (trip.totalPauseTime > 0) {
                    trip.endTime = System.currentTimeMillis() - trip.totalPauseTime;
                }
                // Save trip so far (points and extent, but no purpose or notes)
                fi = new Intent(RecordingActivity.this, SaveTrip.class);
                trip.updateTrip("", "", "", "");
            }
            // Otherwise, cancel and go back to main screen
            else {

                Toast.makeText(getBaseContext(), "No GPS data acquired; nothing to submit.", Toast.LENGTH_SHORT)
                        .show();

                cancelRecording();

                // Go back to main screen
                fi = new Intent(RecordingActivity.this, MainInput.class);
                fi.putExtra("keep", true);
            }

            // Either way, activate next task, and then kill this task
            startActivity(fi);
            RecordingActivity.this.finish();
        }
    });
}

From source file:com.volosyukivan.WiFiInputMethod.java

@Override
public void onCreate() {
    super.onCreate();
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE,
            "wifikeyboard");
    //    Debug.d("WiFiInputMethod started");
    serviceConnection = new ServiceConnection() {
        //@Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //        Debug.d("WiFiInputMethod connected to HttpService.");
            try {
                remoteKeyboard = RemoteKeyboard.Stub.asInterface(service);
                keyboardListener = new RemoteKeyListener.Stub() {
                    @Override//from   w  w  w .j a v  a 2  s  .com
                    public void keyEvent(int code, boolean pressed) throws RemoteException {
                        // Debug.d("got key in WiFiInputMethod");
                        receivedKey(code, pressed);
                    }

                    @Override
                    public void charEvent(int code) throws RemoteException {
                        // Debug.d("got key in WiFiInputMethod");
                        receivedChar(code);
                    }

                    @Override
                    public boolean setText(String text) throws RemoteException {
                        return WiFiInputMethod.this.setText(text);
                    }

                    @Override
                    public String getText() throws RemoteException {
                        return WiFiInputMethod.this.getText();
                    }
                };
                RemoteKeyboard.Stub.asInterface(service).registerKeyListener(keyboardListener);
            } catch (RemoteException e) {
                throw new RuntimeException("WiFiInputMethod failed to connected to HttpService.", e);
            }
        }

        //@Override
        public void onServiceDisconnected(ComponentName name) {
            //        Debug.d("WiFiInputMethod disconnected from HttpService.");
        }
    };
    if (this.bindService(new Intent(this, HttpService.class), serviceConnection, BIND_AUTO_CREATE) == false) {
        throw new RuntimeException("failed to connect to HttpService");
    }
}

From source file:com.jetheis.android.grades.billing.googleplay.GooglePlayBillingWrapper.java

public GooglePlayBillingWrapper(Context context) {
    mContext = context;/* w ww.  j  a va 2  s .  c o m*/
    mOnReadyListeners = new HashSet<OnBillingReadyListener>();
    mOnPurchaseStateChangedListeners = new HashSet<OnPurchaseStateChangedListener>();

    mContext.startService(new Intent(mContext, GooglePlayBillingService.class));

    mConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mBoundService = ((GooglePlayBillingService.GooglePlayBillingBinder) service).getService();
            mBoundService.checkIsBillingSupported(new OnGooglePlayBillingSupportResultListener() {

                @Override
                public void onGooglePlayBillingSupportResultFound(boolean billingSupported) {
                    if (billingSupported) {
                        Log.i(Constants.TAG, "Google Play billing ready");

                        for (OnBillingReadyListener listener : mOnReadyListeners) {
                            listener.onBillingReady();
                        }

                    } else {
                        Log.i(Constants.TAG, "Google Play billing is not supported");

                        for (OnBillingReadyListener listener : mOnReadyListeners) {
                            listener.onBillingNotSupported();
                        }

                    }
                }

            });

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mBoundService = null;
        }
    };

    mContext.bindService(new Intent(context, GooglePlayBillingService.class), mConnection,
            Context.BIND_AUTO_CREATE);
}

From source file:de.grundid.plusrad.MainActivity.java

private void connectToService() {
    Intent rService = new Intent(this, RecordingService.class);
    ServiceConnection sc = new ServiceConnection() {

        public void onServiceDisconnected(ComponentName name) {
        }//from   w  ww  . j a v  a 2  s .  com

        public void onServiceConnected(ComponentName name, IBinder service) {
            RecordingService.IRecordService rs = (RecordingService.IRecordService) service;
            int state = rs.getState();
            if (state == RecordingService.STATE_RECORDING || state == RecordingService.STATE_PAUSED) {
                startActivity(new Intent(MainActivity.this, RecordingActivity.class));
            } else {
                cleanupData();
            }
            MainActivity.this.unbindService(this); // race?  this says we no longer care
        }
    };
    // This needs to block until the onServiceConnected (above) completes.
    // Thus, we can check the recording status before continuing on.
    bindService(rService, sc, Context.BIND_AUTO_CREATE);
}

From source file:com.android.music.PlaylistBrowserFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    View view = inflater.inflate(R.layout.media_picker_activity, null);

    final Intent intent = getActivity().getIntent();
    final String action = intent.getAction();
    if (Intent.ACTION_CREATE_SHORTCUT.equals(action)) {
        mCreateShortcut = true;//w w  w . j  a va  2  s. c om
    }

    getActivity().setVolumeControlStream(AudioManager.STREAM_MUSIC);
    mToken = MusicUtils.bindToService(getActivity(), new ServiceConnection() {
        public void onServiceConnected(ComponentName classname, IBinder obj) {
            if (Intent.ACTION_VIEW.equals(action)) {
                Bundle b = intent.getExtras();
                if (b == null) {
                    Log.w(TAG, "Unexpected:getExtras() returns null.");
                } else {
                    try {
                        long id = Long.parseLong(b.getString("playlist"));
                        if (id == RECENTLY_ADDED_PLAYLIST) {
                            playRecentlyAdded();
                        } else if (id == PODCASTS_PLAYLIST) {
                            playPodcasts();
                        } else if (id == ALL_SONGS_PLAYLIST) {
                            long[] list = MusicUtils.getAllSongs(getActivity());
                            if (list != null) {
                                MusicUtils.playAll(getActivity(), list, 0);
                            }
                        } else {
                            MusicUtils.playPlaylist(getActivity(), id);
                        }
                    } catch (NumberFormatException e) {
                        Log.w(TAG, "Playlist id missing or broken");
                    }
                }
                getActivity().finish();
                return;
            }
            MusicUtils.updateNowPlaying(getActivity());
        }

        public void onServiceDisconnected(ComponentName classname) {
        }

    });

    IntentFilter f = new IntentFilter();
    f.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);
    f.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
    f.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
    f.addDataScheme("file");
    getActivity().registerReceiver(mScanListener, f);

    lv = (ListView) view.findViewById(android.R.id.list);
    lv.setOnCreateContextMenuListener(this);
    lv.setTextFilterEnabled(true);
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // TODO Auto-generated method stub
            if (mCreateShortcut) {
                final Intent shortcut = new Intent();
                shortcut.setAction(Intent.ACTION_VIEW);
                shortcut.setDataAndType(Uri.EMPTY, "vnd.android.cursor.dir/playlist");
                shortcut.putExtra("playlist", String.valueOf(id));

                final Intent intent = new Intent();
                intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcut);
                intent.putExtra(Intent.EXTRA_SHORTCUT_NAME,
                        ((TextView) view.findViewById(R.id.line1)).getText());
                intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource
                        .fromContext(getActivity(), R.drawable.ic_launcher_shortcut_music_playlist));

                getActivity().setResult(getActivity().RESULT_OK, intent);
                getActivity().finish();
                return;
            }
            if (id == RECENTLY_ADDED_PLAYLIST) {
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setDataAndType(Uri.EMPTY, "vnd.android.cursor.dir/track");
                intent.putExtra("playlist", "recentlyadded");
                startActivity(intent);
            } else if (id == PODCASTS_PLAYLIST) {
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setDataAndType(Uri.EMPTY, "vnd.android.cursor.dir/track");
                intent.putExtra("playlist", "podcasts");
                startActivity(intent);
            } else {
                Intent intent = new Intent(Intent.ACTION_EDIT);
                intent.setDataAndType(Uri.EMPTY, "vnd.android.cursor.dir/track");
                intent.putExtra("playlist", Long.valueOf(id).toString());
                startActivity(intent);
            }

        }
    });

    mAdapter = (PlaylistListAdapter) getActivity().getLastNonConfigurationInstance();
    if (mAdapter == null) {
        //Log.i("@@@", "starting query");
        mAdapter = new PlaylistListAdapter(getActivity().getApplication(), this, R.layout.track_list_item,
                mPlaylistCursor, new String[] { MediaStore.Audio.Playlists.NAME },
                new int[] { android.R.id.text1 });
        lv.setAdapter(mAdapter);
        //setTitle(R.string.working_playlists);
        getPlaylistCursor(mAdapter.getQueryHandler(), null);
    } else {
        mAdapter.setActivity(this);
        lv.setAdapter(mAdapter);
        mPlaylistCursor = mAdapter.getCursor();
        // If mPlaylistCursor is null, this can be because it doesn't have
        // a cursor yet (because the initial query that sets its cursor
        // is still in progress), or because the query failed.
        // In order to not flash the error dialog at the user for the
        // first case, simply retry the query when the cursor is null.
        // Worst case, we end up doing the same query twice.
        if (mPlaylistCursor != null) {
            init(mPlaylistCursor);
        } else {
            //setTitle(R.string.working_playlists);
            getPlaylistCursor(mAdapter.getQueryHandler(), null);
        }
    }

    return view;
}

From source file:com.otaupdater.OTAUpdaterActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    final Context context = getApplicationContext();
    cfg = Config.getInstance(context);//from  ww w. j  ava2 s  .c  o  m

    if (!cfg.hasProKey()) {
        bindService(new Intent("com.android.vending.billing.InAppBillingService.BIND"),
                billingSrvConn = new ServiceConnection() {
                    @Override
                    public void onServiceDisconnected(ComponentName name) {
                        billingSrvConn = null;
                    }

                    @Override
                    public void onServiceConnected(ComponentName name, IBinder binder) {
                        IInAppBillingService service = IInAppBillingService.Stub.asInterface(binder);

                        try {
                            Bundle owned = service.getPurchases(3, getPackageName(), "inapp", null);
                            ArrayList<String> ownedItems = owned.getStringArrayList("INAPP_PURCHASE_ITEM_LIST");
                            ArrayList<String> ownedItemData = owned
                                    .getStringArrayList("INAPP_PURCHASE_DATA_LIST");

                            if (ownedItems != null && ownedItemData != null) {
                                for (int q = 0; q < ownedItems.size(); q++) {
                                    if (ownedItems.get(q).equals(Config.PROKEY_SKU)) {
                                        JSONObject itemData = new JSONObject(ownedItemData.get(q));
                                        cfg.setKeyPurchaseToken(itemData.getString("purchaseToken"));
                                        break;
                                    }
                                }
                            }
                        } catch (RemoteException ignored) {
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        unbindService(this);
                        billingSrvConn = null;
                    }
                }, Context.BIND_AUTO_CREATE);
    }

    boolean data = Utils.dataAvailable(this);
    boolean wifi = Utils.wifiConnected(this);

    if (!data || !wifi) {
        final boolean nodata = !data && !wifi;

        if ((nodata && !cfg.getIgnoredDataWarn()) || (!nodata && !cfg.getIgnoredWifiWarn())) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(nodata ? R.string.alert_nodata_title : R.string.alert_nowifi_title);
            builder.setMessage(nodata ? R.string.alert_nodata_message : R.string.alert_nowifi_message);
            builder.setCancelable(false);
            builder.setNegativeButton(R.string.exit, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    finish();
                }
            });
            builder.setNeutralButton(R.string.alert_wifi_settings, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    Intent i = new Intent(Settings.ACTION_WIFI_SETTINGS);
                    startActivity(i);
                }
            });
            builder.setPositiveButton(R.string.ignore, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (nodata) {
                        cfg.setIgnoredDataWarn(true);
                    } else {
                        cfg.setIgnoredWifiWarn(true);
                    }
                    dialog.dismiss();
                }
            });

            final AlertDialog dlg = builder.create();

            dlg.setOnShowListener(new DialogInterface.OnShowListener() {
                @Override
                public void onShow(DialogInterface dialog) {
                    onDialogShown(dlg);
                }
            });
            dlg.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    onDialogClosed(dlg);
                }
            });
            dlg.show();
        }
    }

    Utils.updateDeviceRegistration(this);
    CheckinReceiver.setDailyAlarm(this);

    if (!PropUtils.isRomOtaEnabled() && !PropUtils.isKernelOtaEnabled() && !cfg.getIgnoredUnsupportedWarn()) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.alert_unsupported_title);
        builder.setMessage(R.string.alert_unsupported_message);
        builder.setCancelable(false);
        builder.setNegativeButton(R.string.exit, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                finish();
            }
        });
        builder.setPositiveButton(R.string.ignore, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                cfg.setIgnoredUnsupportedWarn(true);
                dialog.dismiss();
            }
        });

        final AlertDialog dlg = builder.create();

        dlg.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                onDialogShown(dlg);
            }
        });
        dlg.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                onDialogClosed(dlg);
            }
        });
        dlg.show();
    }

    setContentView(R.layout.main);

    Fragment adFragment = getFragmentManager().findFragmentById(R.id.ads);
    if (adFragment != null)
        getFragmentManager().beginTransaction().hide(adFragment).commit();

    ViewPager mViewPager = (ViewPager) findViewById(R.id.pager);

    bar = getActionBar();
    assert bar != null;

    bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    bar.setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE, ActionBar.DISPLAY_SHOW_TITLE);
    bar.setTitle(R.string.app_name);

    TabsAdapter mTabsAdapter = new TabsAdapter(this, mViewPager);
    mTabsAdapter.addTab(bar.newTab().setText(R.string.main_about), AboutTab.class);

    ActionBar.Tab romTab = bar.newTab().setText(R.string.main_rom);
    if (cfg.hasStoredRomUpdate())
        romTab.setIcon(R.drawable.ic_action_warning);
    romTabIdx = mTabsAdapter.addTab(romTab, ROMTab.class);

    ActionBar.Tab kernelTab = bar.newTab().setText(R.string.main_kernel);
    if (cfg.hasStoredKernelUpdate())
        kernelTab.setIcon(R.drawable.ic_action_warning);
    kernelTabIdx = mTabsAdapter.addTab(kernelTab, KernelTab.class);

    if (!handleNotifAction(getIntent())) {
        if (cfg.hasStoredRomUpdate() && !cfg.isDownloadingRom()) {
            cfg.getStoredRomUpdate().showUpdateNotif(this);
        }

        if (cfg.hasStoredKernelUpdate() && !cfg.isDownloadingKernel()) {
            cfg.getStoredKernelUpdate().showUpdateNotif(this);
        }

        if (savedInstanceState != null) {
            bar.setSelectedNavigationItem(savedInstanceState.getInt(KEY_TAB, 0));
        }
    }
}