jjzjj

android - 我的 onNewIntent 没有调用

coder 2023-12-11 原文

创建一个集成 Twitter 的应用程序。我使用本教程:

http://blog.blundell-apps.com/sending-a-tweet/

package com.blundell.tut.ttt;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.Toast;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;

public class TweetToTwitterActivity extends Activity {

    private static final String TAG = "Blundell.TweetToTwitterActivity";

    /** Name to store the users access token */
    private static final String PREF_ACCESS_TOKEN = "accessToken";
    /** Name to store the users access token secret */
    private static final String PREF_ACCESS_TOKEN_SECRET = "accessTokenSecret";
    /** Consumer Key generated when you registered your app at https://dev.twitter.com/apps/ */
    private static final String CONSUMER_KEY = "yourConsumerKey";
    /** Consumer Secret generated when you registered your app at https://dev.twitter.com/apps/  */
    private static final String CONSUMER_SECRET = "yourConsumerSecret"; // XXX Encode in your app
    /** The url that Twitter will redirect to after a user log's in - this will be picked up by your app manifest and redirected into this activity */
    private static final String CALLBACK_URL = "tweet-to-twitter-blundell-01-android:///";
    /** Preferences to store a logged in users credentials */
    private SharedPreferences mPrefs;
    /** Twitter4j object */
    private Twitter mTwitter;
    /** The request token signifies the unique ID of the request you are sending to twitter  */
    private RequestToken mReqToken;

    private Button mLoginButton;
    private Button mTweetButton;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "Loading TweetToTwitterActivity");
        setContentView(R.layout.activity_main);

        // Create a new shared preference object to remember if the user has
        // already given us permission
        mPrefs = getSharedPreferences("twitterPrefs", MODE_PRIVATE);
        Log.i(TAG, "Got Preferences");

        // Load the twitter4j helper
        mTwitter = new TwitterFactory().getInstance();
        Log.i(TAG, "Got Twitter4j");

        // Tell twitter4j that we want to use it with our app
        mTwitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
        Log.i(TAG, "Inflated Twitter4j");

        mLoginButton = (Button) findViewById(R.id.login_button);
        mTweetButton = (Button) findViewById(R.id.tweet_button);
    }

    /**
     * Button clickables are declared in XML as this projects min SDK is 1.6</br> </br> 
     * Checks if the user has given this app permission to use twitter
     * before</br> If so login and enable tweeting</br> 
     * Otherwise redirect to Twitter for permission
     * 
     * @param v the clicked button
     */
    public void buttonLogin(View v) {
        Log.i(TAG, "Login Pressed");
        if (mPrefs.contains(PREF_ACCESS_TOKEN)) {
            Log.i(TAG, "Repeat User");
            loginAuthorisedUser();
        } else {
            Log.i(TAG, "New User");
            loginNewUser();
        }
    }

    /**
     * Button clickables are declared in XML as this projects min SDK is 1.6</br> </br>
     * 
     * @param v the clicked button
     */
    public void buttonTweet(View v) {
        Log.i(TAG, "Tweet Pressed");
        tweetMessage();
    }

    /**
     * Create a request that is sent to Twitter asking 'can our app have permission to use Twitter for this user'</br> 
     * We are given back the {@link mReqToken}
     * that is a unique indetifier to this request</br> 
     * The browser then pops up on the twitter website and the user logins in ( we never see this informaton
     * )</br> Twitter then redirects us to {@link CALLBACK_URL} if the login was a success</br>
     * 
     */
    private void loginNewUser() {
        try {
            Log.i(TAG, "Request App Authentication");
            mReqToken = mTwitter.getOAuthRequestToken(CALLBACK_URL);

            Log.i(TAG, "Starting Webview to login to twitter");
            WebView twitterSite = new WebView(this);
            twitterSite.loadUrl(mReqToken.getAuthenticationURL());
            setContentView(twitterSite);

        } catch (TwitterException e) {
            Toast.makeText(this, "Twitter Login error, try again later", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * The user had previously given our app permission to use Twitter</br> 
     * Therefore we retrieve these credentials and fill out the Twitter4j helper
     */
    private void loginAuthorisedUser() {
        String token = mPrefs.getString(PREF_ACCESS_TOKEN, null);
        String secret = mPrefs.getString(PREF_ACCESS_TOKEN_SECRET, null);

        // Create the twitter access token from the credentials we got previously
        AccessToken at = new AccessToken(token, secret);

        mTwitter.setOAuthAccessToken(at);

        Toast.makeText(this, "Welcome back", Toast.LENGTH_SHORT).show();

        enableTweetButton();
    }

    /**
     * Catch when Twitter redirects back to our {@link CALLBACK_URL}</br> 
     * We use onNewIntent as in our manifest we have singleInstance="true" if we did not the
     * getOAuthAccessToken() call would fail
     */
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.i(TAG, "New Intent Arrived");
        dealWithTwitterResponse(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG, "Arrived at onResume");
    }

    /**
     * Twitter has sent us back into our app</br> 
     * Within the intent it set back we have a 'key' we can use to authenticate the user
     * 
     * @param intent
     */
    private void dealWithTwitterResponse(Intent intent) {
        Uri uri = intent.getData();
        if (uri != null && uri.toString().startsWith(CALLBACK_URL)) { // If the user has just logged in
            String oauthVerifier = uri.getQueryParameter("oauth_verifier");

            authoriseNewUser(oauthVerifier);
        }
    }

    /**
     * Create an access token for this new user</br> 
     * Fill out the Twitter4j helper</br> 
     * And save these credentials so we can log the user straight in next time
     * 
     * @param oauthVerifier
     */
    private void authoriseNewUser(String oauthVerifier) {
        try {
            AccessToken at = mTwitter.getOAuthAccessToken(mReqToken, oauthVerifier);
            mTwitter.setOAuthAccessToken(at);

            saveAccessToken(at);

            // Set the content view back after we changed to a webview
            setContentView(R.layout.activity_main);

            enableTweetButton();
        } catch (TwitterException e) {
            Toast.makeText(this, "Twitter auth error x01, try again later", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * Allow the user to Tweet
     */
    private void enableTweetButton() {
        Log.i(TAG, "User logged in - allowing to tweet");
        mLoginButton.setEnabled(false);
        mTweetButton.setEnabled(true);
    }

    /**
     * Send a tweet on your timeline, with a Toast msg for success or failure
     */
    private void tweetMessage() {
        try {
            mTwitter.updateStatus("Test - Tweeting with @Blundell_apps #AndroidDev Tutorial using #Twitter4j http://blog.blundell-apps.com/sending-a-tweet/");

            Toast.makeText(this, "Tweet Successful!", Toast.LENGTH_SHORT).show();
        } catch (TwitterException e) {
            Toast.makeText(this, "Tweet error, try again later", Toast.LENGTH_SHORT).show();
        }
    }

    private void saveAccessToken(AccessToken at) {
        String token = at.getToken();
        String secret = at.getTokenSecret();
        Editor editor = mPrefs.edit();
        editor.putString(PREF_ACCESS_TOKEN, token);
        editor.putString(PREF_ACCESS_TOKEN_SECRET, secret);
        editor.commit();
    }
}

这里用 onNewIntent() 方法编写的代码不起作用我只设置了 setcontentView 是一个问题吗?

这是 list

<application
        android:icon="@drawable/icon"
        android:label="@string/app_name">
        <activity
            android:name=".TweetToTwitterActivity"
            android:label="@string/app_name"
            android:launchMode="singleInstance">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data android:scheme="tweet-to-twitter-blundell-01-android" />
            </intent-filter>
        </activity>

    </application>

最佳答案

如下所示更改 list 中的 Activity 启动模式,并让我知道结果,

 android:launchMode="singleTop"

关于android - 我的 onNewIntent 没有调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18209528/

有关android - 我的 onNewIntent 没有调用的更多相关文章

  1. ruby - 难道Lua没有和Ruby的method_missing相媲美的东西吗? - 2

    我好像记得Lua有类似Ruby的method_missing的东西。还是我记错了? 最佳答案 表的metatable的__index和__newindex可以用于与Ruby的method_missing相同的效果。 关于ruby-难道Lua没有和Ruby的method_missing相媲美的东西吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/7732154/

  2. ruby-on-rails - rails 目前在重启后没有安装 - 2

    我有一个奇怪的问题:我在rvm上安装了ruby​​onrails。一切正常,我可以创建项目。但是在我输入“railsnew”时重新启动后,我有“程序'rails'当前未安装。”。SystemUbuntu12.04ruby-v"1.9.3p194"gemlistactionmailer(3.2.5)actionpack(3.2.5)activemodel(3.2.5)activerecord(3.2.5)activeresource(3.2.5)activesupport(3.2.5)arel(3.0.2)builder(3.0.0)bundler(1.1.4)coffee-rails(

  3. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  4. ruby-on-rails - 如何在我的 Rails 应用程序 View 中打印 ruby​​ 变量的内容? - 2

    我是一个Rails初学者,但我想从我的RailsView(html.haml文件)中查看Ruby变量的内容。我试图在ruby​​中打印出变量(认为它会在终端中出现),但没有得到任何结果。有什么建议吗?我知道Rails调试器,但更喜欢使用inspect来打印我的变量。 最佳答案 您可以在View中使用puts方法将信息输出到服务器控制台。您应该能够在View中的任何位置使用Haml执行以下操作:-puts@my_variable.inspect 关于ruby-on-rails-如何在我的R

  5. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

  6. c# - 如何在 ruby​​ 中调用 C# dll? - 2

    如何在ruby​​中调用C#dll? 最佳答案 我能想到几种可能性:为您的DLL编写(或找人编写)一个COM包装器,如果它还没有,则使用Ruby的WIN32OLE库来调用它;看看RubyCLR,其中一位作者是JohnLam,他继续在Microsoft从事IronRuby方面的工作。(估计不会再维护了,可能不支持.Net2.0以上的版本);正如其他地方已经提到的,看看使用IronRuby,如果这是您的技术选择。有一个主题是here.请注意,最后一篇文章实际上来自JohnLam(看起来像是2009年3月),他似乎很自在地断言RubyCL

  7. ruby - 我可以将我的 README.textile 以正确的格式放入我的 RDoc 中吗? - 2

    我喜欢使用Textile或Markdown为我的项目编写自述文件,但是当我生成RDoc时,自述文件被解释为RDoc并且看起来非常糟糕。有没有办法让RDoc通过RedCloth或BlueCloth而不是它自己的格式化程序运行文件?它可以配置为自动检测文件后缀的格式吗?(例如README.textile通过RedCloth运行,但README.mdown通过BlueCloth运行) 最佳答案 使用YARD直接代替RDoc将允许您包含Textile或Markdown文件,只要它们的文件后缀是合理的。我经常使用类似于以下Rake任务的东西:

  8. jquery - 我的 jquery AJAX POST 请求无需发送 Authenticity Token (Rails) - 2

    rails中是否有任何规定允许站点的所有AJAXPOST请求在没有authenticity_token的情况下通过?我有一个调用Controller方法的JqueryPOSTajax调用,但我没有在其中放置任何真实性代码,但调用成功。我的ApplicationController确实有'request_forgery_protection'并且我已经改变了config.action_controller.consider_all_requests_local在我的environments/development.rb中为false我还搜索了我的代码以确保我没有重载ajaxSend来发送

  9. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  10. ruby - 调用其他方法的 TDD 方法的正确方法 - 2

    我需要一些关于TDD概念的帮助。假设我有以下代码defexecute(command)casecommandwhen"c"create_new_characterwhen"i"display_inventoryendenddefcreate_new_character#dostufftocreatenewcharacterenddefdisplay_inventory#dostufftodisplayinventoryend现在我不确定要为什么编写单元测试。如果我为execute方法编写单元测试,那不是几乎涵盖了我对create_new_character和display_invent

随机推荐