Example usage for android.content Context startService

List of usage examples for android.content Context startService

Introduction

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

Prototype

@Nullable
public abstract ComponentName startService(Intent service);

Source Link

Document

Request that a given application service be started.

Usage

From source file:org.getlantern.firetweet.util.Utils.java

public static void startRefreshServiceIfNeeded(final Context context) {
    final Intent refreshServiceIntent = new Intent(context, RefreshService.class);
    if (isNetworkAvailable(context) && hasAutoRefreshAccounts(context)) {
        if (isDebugBuild()) {
            Log.d(LOGTAG, "Start background refresh service");
        }//from w  w w.j  a  va  2  s.  c  om
        context.startService(refreshServiceIntent);
    } else {
        context.stopService(refreshServiceIntent);
    }
}

From source file:org.kontalk.ui.ComposeMessageFragment.java

private void subscribePresence() {
    // TODO this needs serious refactoring
    if (mPresenceReceiver == null) {
        mPresenceReceiver = new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();

                if (MessageCenterService.ACTION_PRESENCE.equals(action)) {
                    String from = intent.getStringExtra(MessageCenterService.EXTRA_FROM);
                    String bareFrom = from != null ? XmppStringUtils.parseBareJid(from) : null;

                    // we are receiving a presence from our peer
                    if (from != null && bareFrom.equalsIgnoreCase(mUserJID)) {

                        // we handle only (un)available presence stanzas
                        String type = intent.getStringExtra(MessageCenterService.EXTRA_TYPE);

                        if (type == null) {
                            // no roster entry found, request subscription

                            // pre-approve our presence if we don't have contact's key
                            Intent i = new Intent(context, MessageCenterService.class);
                            i.setAction(MessageCenterService.ACTION_PRESENCE);
                            i.putExtra(MessageCenterService.EXTRA_TO, mUserJID);
                            i.putExtra(MessageCenterService.EXTRA_TYPE, Presence.Type.subscribed.name());
                            context.startService(i);

                            // request subscription
                            i = new Intent(context, MessageCenterService.class);
                            i.setAction(MessageCenterService.ACTION_PRESENCE);
                            i.putExtra(MessageCenterService.EXTRA_TO, mUserJID);
                            i.putExtra(MessageCenterService.EXTRA_TYPE, Presence.Type.subscribe.name());
                            context.startService(i);

                            setStatusText(context.getString(R.string.invitation_sent_label));
                        }//w  w  w  .j  a v  a  2s.  c o m

                        // (un)available presence
                        else if (Presence.Type.available.name().equals(type)
                                || Presence.Type.unavailable.name().equals(type)) {

                            CharSequence statusText = null;

                            // really not much sense in requesting the key for a non-existing contact
                            Contact contact = getContact();
                            if (contact != null) {
                                String newFingerprint = intent
                                        .getStringExtra(MessageCenterService.EXTRA_FINGERPRINT);
                                // if this is null, we are accepting the key for the first time
                                PGPPublicKeyRing trustedPublicKey = contact.getTrustedPublicKeyRing();

                                // request the key if we don't have a trusted one and of course if the user has a key
                                boolean unknownKey = (trustedPublicKey == null
                                        && contact.getFingerprint() != null);
                                boolean changedKey = false;
                                // check if fingerprint changed
                                if (trustedPublicKey != null && newFingerprint != null) {
                                    String oldFingerprint = PGP
                                            .getFingerprint(PGP.getMasterKey(trustedPublicKey));
                                    if (!newFingerprint.equalsIgnoreCase(oldFingerprint)) {
                                        // fingerprint has changed since last time
                                        changedKey = true;
                                    }
                                }

                                if (changedKey) {
                                    // warn user that public key is changed
                                    showKeyChangedWarning();
                                } else if (unknownKey) {
                                    // warn user that public key is unknown
                                    showKeyUnknownWarning();
                                }
                            }

                            if (Presence.Type.available.toString().equals(type)) {
                                mAvailableResources.add(from);

                                /*
                                 * FIXME using mode this way has several flaws.
                                 * 1. it doesn't take multiple resources into account
                                 * 2. it doesn't account for away status duration (we don't have this information at all)
                                 */
                                String mode = intent.getStringExtra(MessageCenterService.EXTRA_SHOW);
                                if (mode != null && mode.equals(Presence.Mode.away.toString())) {
                                    statusText = context.getString(R.string.seen_away_label);
                                } else {
                                    statusText = context.getString(R.string.seen_online_label);
                                }

                                // request version information
                                if (contact != null && contact.getVersion() != null) {
                                    setVersionInfo(context, contact.getVersion());
                                } else if (mVersionRequestId == null) {
                                    requestVersion(from);
                                }
                            } else if (Presence.Type.unavailable.toString().equals(type)) {
                                boolean removed = mAvailableResources.remove(from);
                                /*
                                 * All available resources have gone. Mark
                                 * the user as offline immediately and use the
                                 * timestamp provided with the stanza (if any).
                                 */
                                if (mAvailableResources.size() == 0) {
                                    // an offline user can't be typing
                                    mIsTyping = false;

                                    if (removed) {
                                        // resource was removed now, mark as just offline
                                        statusText = context.getText(R.string.seen_moment_ago_label);
                                    } else {
                                        // resource is offline, request last activity
                                        if (contact != null && contact.getLastSeen() > 0) {
                                            setLastSeenTimestamp(context, contact.getLastSeen());
                                        } else if (mLastActivityRequestId == null) {
                                            mLastActivityRequestId = StringUtils.randomString(6);
                                            MessageCenterService.requestLastActivity(context, bareFrom,
                                                    mLastActivityRequestId);
                                        }
                                    }
                                }
                            }

                            if (statusText != null) {
                                mCurrentStatus = statusText;
                                if (!mIsTyping)
                                    setStatusText(statusText);
                            }
                        }

                        // subscription accepted, probe presence
                        else if (Presence.Type.subscribed.name().equals(type)) {
                            presenceSubscribe();
                        }
                    }
                }

                else if (MessageCenterService.ACTION_LAST_ACTIVITY.equals(action)) {
                    String id = intent.getStringExtra(MessageCenterService.EXTRA_PACKET_ID);
                    if (id != null && id.equals(mLastActivityRequestId)) {
                        mLastActivityRequestId = null;
                        // ignore last activity if we had an available presence in the meantime
                        if (mAvailableResources.size() == 0) {
                            String type = intent.getStringExtra(MessageCenterService.EXTRA_TYPE);
                            if (type == null || !type.equalsIgnoreCase(IQ.Type.error.toString())) {
                                long seconds = intent.getLongExtra(MessageCenterService.EXTRA_SECONDS, -1);
                                setLastSeenSeconds(context, seconds);
                            }
                        }
                    }
                }

                else if (MessageCenterService.ACTION_VERSION.equals(action)) {
                    // compare version and show warning if needed
                    String id = intent.getStringExtra(MessageCenterService.EXTRA_PACKET_ID);
                    if (id != null && id.equals(mVersionRequestId)) {
                        mVersionRequestId = null;
                        String name = intent.getStringExtra(MessageCenterService.EXTRA_VERSION_NAME);
                        if (name != null && name.equalsIgnoreCase(context.getString(R.string.app_name))) {
                            String version = intent.getStringExtra(MessageCenterService.EXTRA_VERSION_NUMBER);
                            if (version != null) {
                                Contact contact = getContact();
                                if (contact != null)
                                    // cache the version
                                    contact.setVersion(version);
                                setVersionInfo(context, version);
                            }
                        }
                    }
                }

                else if (MessageCenterService.ACTION_CONNECTED.equals(action)) {
                    // reset compose sent flag
                    mComposer.resetCompose();
                    // reset available resources list
                    mAvailableResources.clear();
                    // reset any pending request
                    mLastActivityRequestId = null;
                    mVersionRequestId = null;
                }

                else if (MessageCenterService.ACTION_ROSTER_LOADED.equals(action)) {
                    // probe presence
                    presenceSubscribe();
                }

                else if (MessageCenterService.ACTION_MESSAGE.equals(action)) {
                    String from = intent.getStringExtra(MessageCenterService.EXTRA_FROM);
                    String chatState = intent.getStringExtra("org.kontalk.message.chatState");

                    // we are receiving a composing notification from our peer
                    if (from != null && XMPPUtils.equalsBareJID(from, mUserJID)) {
                        if (chatState != null && ChatState.composing.toString().equals(chatState)) {
                            mIsTyping = true;
                            setStatusText(context.getString(R.string.seen_typing_label));
                        } else {
                            mIsTyping = false;
                            setStatusText(mCurrentStatus != null ? mCurrentStatus : "");
                        }
                    }
                }

            }
        };

        // listen for user presence, connection and incoming messages
        IntentFilter filter = new IntentFilter();
        filter.addAction(MessageCenterService.ACTION_PRESENCE);
        filter.addAction(MessageCenterService.ACTION_CONNECTED);
        filter.addAction(MessageCenterService.ACTION_ROSTER_LOADED);
        filter.addAction(MessageCenterService.ACTION_LAST_ACTIVITY);
        filter.addAction(MessageCenterService.ACTION_MESSAGE);
        filter.addAction(MessageCenterService.ACTION_VERSION);

        mLocalBroadcastManager.registerReceiver(mPresenceReceiver, filter);

        // request connection and roster load status
        Context ctx = getActivity();
        if (ctx != null) {
            MessageCenterService.requestConnectionStatus(ctx);
            MessageCenterService.requestRosterStatus(ctx);
        }
    }
}

From source file:org.mortbay.ijetty.IJetty.java

License:asdf

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

    this.requestWindowFeature(Window.FEATURE_NO_TITLE);//?
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);//??

    MainApplication.getInstance().setAppHandler(mHandler);

    instance = this;
    mWebView = new HTML5WebView(this);
    mWebView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
    mWebView.setHorizontalScrollBarEnabled(false);//?
    mWebView.setVerticalScrollBarEnabled(false); //?

    mPropertiesUtil = new PropertiesUtils();

    //?/*from w w w.j  a va  2s.c om*/
    Intent autoStarIntent = new Intent("com.mortbay.ijetty.IJetty");
    autoStarIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    autoStarIntent.addFlags(32);
    sendBroadcast(autoStarIntent);

    //??
    //DisplayMetrics dm = new DisplayMetrics();
    //getWindowManager().getDefaultDisplay().getMetrics(dm);
    AppConstants.RESOLUTION = getDisplayScreenSize(); //String.valueOf(dm.widthPixels) + "*" + String.valueOf(getDisplayScreenHeight());    //dm.widthPixels,dm.heightPixels

    //??
    File clientProps = new File(IJetty.__JETTY_DIR + "/" + IJetty.__ETC_DIR + "/properties.xml");
    try {
        if (clientProps.exists() && clientProps.length() != 0) {
            //?assets??
            mPropertiesUtil.readPropertiesFileFromXML(
                    IJetty.getInstance().getBaseContext().getAssets().open("properties.xml"));
            //String propVersion = mPropertiesUtil.getVersion();
            Log.w("smallstar-defaultPropVersion", mPropertiesUtil.getVersion());
            int defaultPropVersion = Integer.parseInt(mPropertiesUtil.getVersion());
            mPropertiesUtil.readPropertiesFileFromXML(clientProps.getAbsolutePath());
            Log.w("smallstar-curPropVersion", mPropertiesUtil.getVersion());
            int curPropVersion = Integer.parseInt(mPropertiesUtil.getVersion());
            if (defaultPropVersion > curPropVersion) {
                //????????
                //TODO???
                mPropertiesUtil.readPropertiesFileFromXML(
                        IJetty.getInstance().getBaseContext().getAssets().open("properties.xml"));
                mPropertiesUtil.writePropertiesFileToXML(clientProps.getAbsolutePath());
                //?console.war
                Log.w(TAG, "copy console.warSD??");
                InputStream is = IJetty.getInstance().getBaseContext().getAssets().open("console.war");
                FileOutputStream fos = new FileOutputStream(AppConstants.getMediaSdFolder() + "/console.war");
                byte[] buffer = new byte[1024];
                int count = 0;
                while ((count = is.read(buffer)) > 0) {
                    fos.write(buffer, 0, count);
                }
                fos.close();
                is.close();
            }
            Log.w(TAG, "===========================================================");
            AppConstants.CLIENT_CUR_PLAYURL = mPropertiesUtil.getPlayUrl();
            Log.w(TAG, AppConstants.CLIENT_CUR_PLAYURL);
            Log.w(TAG, "===========================================================");
            //                Toast.makeText(IJetty.getInstance().getApplicationContext(), AppConstants.CLIENT_CUR_PLAYURL,
            //                        Toast.LENGTH_SHORT).show();

            PlayListUtil.playListVersion = mPropertiesUtil.getPlayListVersion();
            ApkUtils.apkPushVersion = mPropertiesUtil.getApkPushVersion();
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        Log.w("smallstar------>", "!clientProps.exists() error!!!!!!");
        e.printStackTrace();
    }

    //??:(?)
    startService(new Intent(this, DaemonService.class));

    //js?
    ProxyBridge jsBridge = new ProxyBridge(this);
    mWebView.addJavascriptInterface(jsBridge, "ia");

    mWebView.setHorizontalScrollBarEnabled(false);

    setContentView(R.layout.jetty_controller);

    startButton = (Button) findViewById(R.id.start);
    startButton.setVisibility(View.GONE);//??
    stopButton = (Button) findViewById(R.id.stop);
    stopButton.setVisibility(View.GONE);//??
    configButton = (Button) findViewById(R.id.config);
    configButton.setVisibility(View.GONE);//??
    final Button downloadButton = (Button) findViewById(R.id.download);
    downloadButton.setVisibility(View.GONE);//??

    IntentFilter filter = new IntentFilter();
    filter.addAction(__START_ACTION);
    filter.addAction(__STOP_ACTION);
    filter.addAction(__START_MOVIE_ACTION);
    filter.addCategory("default");

    bcastReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            if (__START_ACTION.equalsIgnoreCase(intent.getAction())) {
                startButton.setEnabled(false);
                configButton.setEnabled(false);
                stopButton.setEnabled(true);
                consolePrint("<br/>Started Jetty at %s", new Date());
                String[] connectors = intent.getExtras().getStringArray("connectors");
                if (null != connectors) {
                    for (int i = 0; i < connectors.length; i++)
                        consolePrint(connectors[i]);
                }

                printNetworkInterfaces();

                if (AndroidInfo.isOnEmulator(IJetty.this))
                    consolePrint("Set up port forwarding to see i-jetty outside of the emulator.");

                //warFile = new File("file:///android_asset/console.war");
                File file = new File(IJetty.__JETTY_DIR + "/" + IJetty.__WEBAPP_DIR + "/"
                        + "console/settings/basicsettings.html");
                if (file.exists()) {
                    if (file.length() > 0) {
                        //Not empty, do something here.
                        //i-jetty???web?
                        setContentView(mWebView.getLayout());
                        //TODO?????
                        int onlineTimeout = 0;
                        do {
                            if (onlineTimeout > 10)
                                break;
                            SystemClock.sleep(1000);
                            onlineTimeout++;
                        } while (!AppConstants.ONLINE_STATUS);

                        if (AppConstants.ONLINE_STATUS)//
                        {
                            mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
                            //mWebView.getSettings().setCacheMode( WebSettings.LOAD_NO_CACHE);
                            mWebView.clearHistory();
                            mWebView.clearFormData();
                            mWebView.clearCache(true);
                            mWebView.loadUrl(AppConstants.CLIENT_CUR_PLAYURL);
                        } else
                            mWebView.loadUrl("http://localhost:8080/console/settings/basicsettings.html");
                    }
                }
            } else if (__STOP_ACTION.equalsIgnoreCase(intent.getAction())) {
                startButton.setEnabled(true);
                configButton.setEnabled(true);
                stopButton.setEnabled(false);
                consolePrint("<br/> Jetty stopped at %s", new Date());
            } else if (__START_MOVIE_ACTION.equalsIgnoreCase(intent.getAction())) {
                //service?onCreate()?onStartCommand().
                Log.i(TAG, "onReceive() get Broadcast org.mortbay.ijetty.movie.start");
                Intent mIntent = new Intent("createUI");
                mIntent.setClass(context, MediaPlaybackService.class);
                context.startService(mIntent);
            }
        }

    };

    registerReceiver(bcastReceiver, filter);

    // Watch for button clicks.
    startButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            if (isUpdateNeeded())
                IJettyToast.showQuickToast(IJetty.this, R.string.loading);
            else {
                //TODO get these values from editable UI elements
                Intent intent = new Intent(IJetty.this, IJettyService.class);
                intent.putExtra(__PORT, __PORT_DEFAULT);
                intent.putExtra(__NIO, __NIO_DEFAULT);
                intent.putExtra(__SSL, __SSL_DEFAULT);
                intent.putExtra(__CONSOLE_PWD, __CONSOLE_PWD_DEFAULT);
                startService(intent);
            }
        }
    });

    stopButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            stopService(new Intent(IJetty.this, IJettyService.class));
        }
    });

    configButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            IJettyEditor.show(IJetty.this);
        }
    });

    downloadButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            IJettyDownloader.show(IJetty.this);
        }
    });

    info = (TextView) findViewById(R.id.info);
    info.setVisibility(View.GONE);
    footer = (TextView) findViewById(R.id.footer);
    footer.setVisibility(View.GONE);
    console = (TextView) findViewById(R.id.console);
    console.setVisibility(View.GONE);
    consoleScroller = (ScrollView) findViewById(R.id.consoleScroller);
    consoleScroller.setVisibility(View.GONE);

    StringBuilder infoBuffer = new StringBuilder();
    try {
        PackageInfo pi = getPackageManager().getPackageInfo(getPackageName(), 0);
        infoBuffer.append(formatJettyInfoLine("i-jetty version %s (%s)", pi.versionName, pi.versionCode));
    } catch (NameNotFoundException e) {
        infoBuffer.append(formatJettyInfoLine("i-jetty version unknown"));
    }
    infoBuffer.append(formatJettyInfoLine("On %s using Android version %s", AndroidInfo.getDeviceModel(),
            AndroidInfo.getOSVersion()));
    info.setText(Html.fromHtml(infoBuffer.toString()));

    StringBuilder footerBuffer = new StringBuilder();
    footerBuffer.append(
            "<b>Project:</b> <a href=\"http://code.google.com/p/i-jetty\">http://code.google.com/p/i-jetty</a> <br/>");
    footerBuffer.append("<b>Server:</b> http://www.eclipse.org/jetty <br/>");
    footerBuffer.append("<b>Support:</b> http://www.intalio.com/jetty/services <br/>");
    footer.setText(Html.fromHtml(footerBuffer.toString()));

    //??WEB?
    Intent intent = new Intent(IJetty.this, IJettyService.class);
    intent.putExtra(__PORT, __PORT_DEFAULT);
    intent.putExtra(__NIO, __NIO_DEFAULT);
    intent.putExtra(__SSL, __SSL_DEFAULT);
    intent.putExtra(__CONSOLE_PWD, __CONSOLE_PWD_DEFAULT);
    startService(intent);
}