在主要活动中调用另一个活动

时间:2016-01-30 10:24:42

标签: java android

抱歉,对于你们所有人来说,我的问题可能非常简单。但我是新手,需要解决方案。如果你能帮助我解决它。

我有一个报价应用程序,它具有在主活动中检查来自服务器的新报价的功能,它在加载主活动时检查服务器是否有可用的新报价,如果可用,它的开放一个弹出窗口用于下载设置活动新的报价,如果用户按下设置按钮,而不是用户设置活动。我需要做一些改变。我想从主要活动中自动下载新的报价而不进行设置活动。这两项活动都在下面

由于

public class MainActivity extends Activity {

    SharedPreferences mSharedPreferences;
    //String qotdId;
    private AdView mAdView;
    private InterstitialAd mInterstitial;
    public static boolean active;

    DAO db;

    String siteUrl, updatesUrl;
    int lastAuthor, lastQuote;

    private ConnectionDetector cd;

    @Override
    protected void onStart() {

        mInterstitial = new InterstitialAd(this);
        mInterstitial.setAdUnitId(getResources().getString(R.string.admob_publisher_interstitial_id));
        mInterstitial.loadAd(new AdRequest.Builder().build());

        super.onStart();
        active = true;

    }

    @Override
    protected void onStop() {
        super.onStop();
        active = false;

    }

    // ==============================================================================

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);    
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,           
        WindowManager.LayoutParams.FLAG_FULLSCREEN);        
        setContentView(R.layout.activity_main);
        mAdView = (AdView) findViewById(R.id.adView);
        mAdView.loadAd(new AdRequest.Builder().build());

    /*  Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
                .getBoolean("isFirstRun", true);

        if (isFirstRun) {
            //show start activity

            startActivity(new Intent(MainActivity.this, SettingsActivity.class));
            Toast.makeText(MainActivity.this, "Please Push Download Button And Save Status in Your Mobile For Just One Time", Toast.LENGTH_LONG)
                    .show();
        }


           getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
                    .putBoolean("isFirstRun", false).commit();
                    */


    //  Parse push notification
        Parse.initialize(this, getString(R.string.parse_application_id), getString(R.string.parse_client_key));
        ParseAnalytics.trackAppOpened(getIntent());
        PushService.setDefaultPushCallback(this, MainActivity.class);
        ParseInstallation.getCurrentInstallation().saveInBackground();

        db = new DAO(this);
        db.open();

        cd = new ConnectionDetector(MainActivity.this);
        siteUrl = getResources().getString(R.string.siteUrl);
        updatesUrl = siteUrl + "site/get_updates/" + String.valueOf(lastAuthor) + "/" + String.valueOf(lastQuote);

        if (cd.isConnectingToInternet()) {
            // Internet Connection is not present

            Intent checkUpdates = new Intent(MainActivity.this, CheckUpdatesService.class);

            startService(checkUpdates);
        }

    //  generateKeyHash();

        final ImageButton quotes = (ImageButton) findViewById(R.id.quotes);
        quotes.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,
                        QuotesActivity.class);
                intent.putExtra("quotesType", 1);
                intent.putExtra("itemSelected", 0);
                startActivity(intent);

            }
        });

        final ImageButton authors = (ImageButton) findViewById(R.id.authors);
        authors.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,
                        AuthorsActivity.class);
                startActivity(intent);

            }
        });

        final ImageButton favorites = (ImageButton) findViewById(R.id.favorites);
        favorites.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,
                        QuotesActivity.class);
                intent.putExtra("quotesType", 2);
                startActivity(intent);

            }
        });

        final ImageButton settings = (ImageButton) findViewById(R.id.settings);
        settings.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,
                        SettingsActivity.class);
                startActivity(intent);

            }
        });

    }

}

我的其他活动

public class SettingsActivity extends PreferenceActivity {

    static final int TIME_DIALOG_ID = 999;
    private AdView mAdView;
    private InterstitialAd mInterstitial;
    private static final String MY_PREFERENCES = "my_preferences";  


    @Override
    protected void onStart() {

        mInterstitial = new InterstitialAd(this);
        mInterstitial.setAdUnitId(getResources().getString(R.string.admob_publisher_interstitial_id));
        mInterstitial.loadAd(new AdRequest.Builder().build());

        super.onStart();
    }

    @Override
    protected void onStop() {
        //unregisterReceiver(receiver);
        super.onStop();

    }


    // ==========================================================================================================//

    DAO db;
    // Progress dialog
    ProgressDialog pDialog;

    PreferenceScreen preferenceScreen;

    private static SharedPreferences mSharedPreferences;
    UpdateClass update;

    // Internet Connection detector
    private ConnectionDetector cd;

    // Alert Dialog Manager
    AlertDialogManager alert = new AlertDialogManager();

    Preference more, rate, about, check, share,status,background, progress = null;
    PreferenceCategory socialsCategory;

    private MyDownloadReceiver receiver;
    // ==============================================================================

    ////////////////////     First Load   /////////////////

    public static boolean isFirst(Context context){
        final SharedPreferences reader = context.getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE); 
        final boolean first = reader.getBoolean("is_first", true);
        if(first){
            final SharedPreferences.Editor editor = reader.edit();
            editor.putBoolean("is_first", false);
            editor.commit();
        }
        return first;
    }       

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.config);
        mAdView = (AdView) findViewById(R.id.adView);
        mAdView.loadAd(new AdRequest.Builder().build());

        //TWITTER_CONSUMER_KEY = getResources().getString(
            //  R.string.TWITTER_CONSUMER_KEY);
        //TWITTER_CONSUMER_SECRET = getResources().getString(
        //      R.string.TWITTER_CONSUMER_SECRET);
        //TWITTER_CALLBACK_URL = "oauth://"
            //  + getApplicationContext().getPackageName()
            //  + ".SettingsActivity";

        //uiHelper = new UiLifecycleHelper(this, callback);
        //uiHelper.onCreate(savedInstanceState);

        db = new DAO(this);
        db.open();

        addPreferencesFromResource(R.layout.settings);

        // Shared Preferences
        mSharedPreferences = getApplicationContext().getSharedPreferences(
                "MyPref", 0);           

        check = (Preference) findPreference("check");
        about = (Preference) findPreference("about");
        more = (Preference) findPreference("more");
        rate = (Preference) findPreference("rate");
        status = (Preference) findPreference("status");
        share = (Preference) findPreference("share");
        background = (Preference) findPreference("background");

        socialsCategory = (PreferenceCategory) findPreference("socials");

        preferenceScreen = getPreferenceScreen();


        check.setOnPreferenceClickListener(new OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference preference) {
                update = new UpdateClass(SettingsActivity.this);
                update.handleUpdates();
                //if (mInterstitial.isLoaded()) {
                //  mInterstitial.show();
                //}

                return false;
            }
        });

        // ==============================================================================

        about.setOnPreferenceClickListener(new OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference preference) {

                Intent intent = new Intent(SettingsActivity.this,
                        AboutActivity.class);
                startActivity(intent);
                if (mInterstitial.isLoaded()) {
                    mInterstitial.show();
                }

                return false;
            }
        });


        // ==============================================================================

                background
                        .setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

                            public boolean onPreferenceChange(Preference preference,
                                    Object newValue) {

                                if (newValue.equals(true)) {
                                    db.updateSetting("background", "1");
                                } else {
                                    db.updateSetting("background", "0");
                                }

                                return true;
                            }
                        });

                // ==============================================================================

        // ==============================================================================

                rate.setOnPreferenceClickListener(new OnPreferenceClickListener() {
                    @Override
                    public boolean onPreferenceClick(Preference preference) {
                        final String appPackageName = "com.karopass.hindishayari2016";
                        try {startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id="+ appPackageName)));
                        } catch (android.content.ActivityNotFoundException anfe) {
                            startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("http://play.google.com/store/apps/details?id="+ appPackageName)));

                        }
                        return true; 
                    }
                });

                // ==============================================================================

                more.setOnPreferenceClickListener(new OnPreferenceClickListener() {
                    @Override
                    public boolean onPreferenceClick(Preference preference) {
                        final String developerName = "karopass";
                        try {startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q="+ developerName)));
                        } catch (android.content.ActivityNotFoundException anfe) {
                            startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("https://play.google.com/store/search?q="+ developerName)));

                        }
                        return true; 
                    }
                });


                share.setOnPreferenceClickListener(new OnPreferenceClickListener() {
                    public boolean onPreferenceClick(Preference preference) {    
                        Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND); 
                        sharingIntent.setType("text/plain");
                        String shareBody = "आज ही डाउनलोड करे हिंदी शायरी एप्लीकेशन और पाइए बेस्ट हिंदी शायरी.इस एप्लीकेशन में 3000 से भी ज्यादा बढ़िया हिंदी शायरी का कलेक्शन है जिसे आप पढने या शेर करने के लिए यूज कर सकते है !! आज ही डाउनलोड करे !! http://play.google.com/store/apps/details?id=com.karopass.hindishayari2016";
                        sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, " ");
                        sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
                        startActivity(Intent.createChooser(sharingIntent, "Share via"));

                        return false;
                    }
                });


                // ==============================================================================

                status.setOnPreferenceClickListener(new OnPreferenceClickListener() {
                    @Override
                    public boolean onPreferenceClick(Preference preference) {
                        final String appPackageName = "com.karopass.hindi_status_2016";
                        try {startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id="+ appPackageName)));
                        } catch (android.content.ActivityNotFoundException anfe) {
                            startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("http://play.google.com/store/apps/details?id="+ appPackageName)));

                        }
                        return true; 
                    }
                });

                // ==============================================================================


                IntentFilter filter = new IntentFilter(MyDownloadReceiver.ACTION);
                filter.addCategory(Intent.CATEGORY_DEFAULT);
                receiver = new MyDownloadReceiver();
                registerReceiver(receiver, filter);

    }

    void showProgressBar() {
        progress = new MyProgressBarPreference(this);
        preferenceScreen.addPreference(progress);
    }

    void setDownloadProgress(int percent) {
        if (progress != null) {
            ((MyProgressBarPreference)progress).setProgress(percent);
            ((MyProgressBarPreference)progress).setLabel("Please wait... " +percent + "%"+" Downloading Done");
        }
    }

    void hideProgressBar()
    {
        if (progress != null)
            preferenceScreen.removePreference(progress);
    }

    public class MyDownloadReceiver extends BroadcastReceiver {

        public static final String ACTION = "com.karopass.hindishayari2016.intent.action.DOWNLOAD";

        public static final int INITIALIZE = 0x001;
        public static final int DOWNLOAD = 0x002;
        public static final int FINISH = 0x003;

        public static final String EXTRA_STATUS = "status";
        public static final String EXTRA_PERCENT = "percent";

        @Override
        public void onReceive(Context context, Intent intent) {
            int status = intent.getIntExtra(EXTRA_STATUS, -1);

            Log.d("DESOLF", "receive broadcast : " + status);

            switch(status) {
            case INITIALIZE:
                showProgressBar();
                break;

            case DOWNLOAD:
                int percent = intent.getIntExtra(MyDownloadReceiver.EXTRA_PERCENT, 0);
                setDownloadProgress(percent);

                break;
            case FINISH:
                hideProgressBar();
                //Toast.makeText(SettingsActivity.this, "Downloaded successfully", Toast.LENGTH_LONG).show();
                if (mInterstitial.isLoaded()) {
                    mInterstitial.show();
                }   
                break;


            default:

            }
        }
    }

    public class MyProgressBarPreference extends Preference {


        public MyProgressBarPreference(Context context) {
            super(context);
        }
        public MyProgressBarPreference(Context context, AttributeSet attrs) {
            super(context, attrs);
        }

        public MyProgressBarPreference(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
        }

        private ImageView mStatusIcon;
        private ProgressBar mProgressBar;
        private TextView mStatusText ;

        private int lastReqProgress=-1;
        private int lastReqMax=-1;
        private String lastLabel;

        @Override
        protected View onCreateView(ViewGroup parent) {

            LayoutInflater li = (LayoutInflater) getSystemService(Service.LAYOUT_INFLATER_SERVICE);
            View myLayout=li.inflate(R.layout.download_progress, null, false);

            RotateAnimation anim = new RotateAnimation(0.0f, 360.0f,
                    Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
                    0.5f);
            anim.setInterpolator(new LinearInterpolator());
            anim.setRepeatCount(Animation.INFINITE);
            anim.setDuration(700);          
            mStatusIcon = (ImageView) myLayout.findViewById(R.id.status_icon);
            mStatusIcon.startAnimation(anim);
            mProgressBar=(ProgressBar) myLayout.findViewById(R.id.status_progress);
            mStatusText=(TextView) myLayout.findViewById(R.id.status_text);

            mStatusIcon.setImageResource(R.drawable.rotate);
            mProgressBar.setProgress(0);
            mStatusText.setText(0 + "%");
            return myLayout;
        }


        public void setIcon(int resId) {
            mStatusIcon.setImageResource(resId);
        }

        public void setProgress(int value){
            if (mProgressBar!=null){
                mProgressBar.setProgress(value);
            } else {
                lastReqProgress=value;
            }

        }

        public void setMax(int value){
            if (mProgressBar!=null){
                int savedprogress=mProgressBar.getProgress();
                mProgressBar.setMax(0);
                mProgressBar.setMax(value);
                mProgressBar.setProgress(savedprogress);
            } else {
                lastReqMax=value;
            }

        }


        public void setLabel(String text){
            if (lastLabel!=null){
                mStatusText.setText(text);
            } else {
                lastLabel=text;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您可以尝试以下代码:

Intent i = new Intent(MainActivity.this, SecondActivity.class);
startActivity(i);

不要忘记在AndroidManifest.xml中添加第二个活动:

<activity android:label="@string/app_name" android:name="SecondActivity"/>

Android Page