简体   繁体   English

来自MainActivity以外的类的调用意图

[英]Call intent from class other than MainActivity

First let me point out that this is my very first time coding an app, and even Java. 首先让我指出,这是我第一次编写应用程序,甚至是Java。 I'm used to coding PHP and JS so please be kind 我习惯于对PHP和JS进行编码,所以请客气

Im following the Google guides http://developer.android.com/training/basics/network-ops/connecting.html 我遵循Google指南http://developer.android.com/training/basics/network-ops/connecting.html

Here's my Main Activity 这是我的主要活动

package com.example.eerstetest;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.eerstetest.MESSAGE";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

public void sendMessage(View view) {
    Intent intent = new Intent(this, DisplayMessageActivity.class); 
    EditText editText = (EditText) findViewById(R.id.edit_message);
    String message = editText.getText().toString();
    intent.putExtra(EXTRA_MESSAGE, message);
    startActivity(intent);
}

public void getUpdate(View view) {
    Intent intent = new Intent(this, DisplayMessageActivity.class); 

    // see if there is a data connection
    ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    if (networkInfo != null && networkInfo.isConnected()) {
        // fetch data
        //textView.setText("Network connection available.");
        String dataUrl = "http://www.myurl.com";
        new DownloadUpdate().execute(dataUrl);
    } else {
        // display error
        //textView.setText("No network connection available.");
        String message = "No network connection available.";
        intent.putExtra(EXTRA_MESSAGE, message);
        startActivity(intent);
    }
}
}

As you can see I have a sendMessage method which works, using the DisplayMessageActivity I also have the getUpdate method, wich calls the DownloadUpdate class which is in a seperate .java file 如您所见,我有一个可以使用DisplayMessageActivity的sendMessage方法,还有一个getUpdate方法,可以调用单独的.java文件中的DownloadUpdate类。

package com.example.eerstetest;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;

// Uses AsyncTask to create a task away from the main UI thread. This task takes a 
// URL string and uses it to create an HttpUrlConnection. Once the connection
// has been established, the AsyncTask downloads the contents of the webpage as
// an InputStream. Finally, the InputStream is converted into a string, which is
// displayed in the UI by the AsyncTask's onPostExecute method.
public class DownloadUpdate extends AsyncTask<String, Integer, String> {
private static final String DEBUG_TAG = "HttpExample";
//private TextView textView;
public final static String EXTRA_MESSAGE = "com.example.eerstetest.MESSAGE";

@Override
protected String doInBackground(String... url) {

   // params comes from the execute() call: params[0] is the url.
   try {
       return downloadUrl(url[0]);
   } catch (IOException e) {
       return "Unable to retrieve web page. URL may be invalid.";
   }
}

// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
   //textView.setText(result);
    Intent intent = new Intent(this, DisplayMessageActivity.class); 
    intent.putExtra(EXTRA_MESSAGE, result);
    startActivity(intent);
}

// Given a URL, establishes an HttpUrlConnection and retrieves
// the web page content as a InputStream, which it returns as
// a string.
private String downloadUrl(String myurl) throws IOException {
    InputStream is = null;
    // Only display the first 500 characters of the retrieved
    // web page content.
    int len = 500;

    try {
        URL url = new URL(myurl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        // Starts the query
        conn.connect();
        int response = conn.getResponseCode();
        Log.d(DEBUG_TAG, "The response is: " + response);
        is = conn.getInputStream();

        // Convert the InputStream into a string
        String contentAsString = readIt(is, len);
        return contentAsString;

    // Makes sure that the InputStream is closed after the app is
    // finished using it.
    } finally {
        if (is != null) {
            is.close();
        } 
    }
}

// Reads an InputStream and converts it to a String.
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
    Reader reader = null;
    reader = new InputStreamReader(stream, "UTF-8");        
    char[] buffer = new char[len];
    reader.read(buffer);
    return new String(buffer);
}
}

I don't understand what I have to fill in for the context when calling the DisplayMessageActivity from here 我不明白从此处调用DisplayMessageActivity时必须为上下文填写什么

To be complete, here is m manifest file 为了完整起见,这是清单文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.eerstetest"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="17" />

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.eerstetest.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name="com.example.eerstetest.DisplayMessageActivity"
        android:label="@string/title_activity_display_message"
        android:parentActivityName="com.example.eerstetest.MainActivity" >
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.eerstetest.MainActivity" />
    </activity>
    <activity
        android:name="com.example.eerstetest.DownloadUpdate"
        android:label="@string/title_activity_download_update" >
    </activity>
</application>

</manifest>

If there is anything additional I can provide, please let me know 如果我可以提供其他任何服务,请告诉我

pass the context as parameter like this : 像这样传递上下文作为参数:

new DownloadUpdate(MainActivity.this).execute(dataUrl);

add constructor in DownloadUpdate : 在DownloadUpdate中添加构造函数:

Context context;
public DownloadUpdate(Context context){
    this.context = context
}

and then use the context in your DownloadUpdate class as a global parameter and call intent using this 然后使用DownloadUpdate类中的上下文作为全局参数,并使用此方法调用意图

Intent intent = new Intent(DownloadUpdate.this, DisplayMessageActivity.class); 
intent.putExtra(EXTRA_MESSAGE, result);
context.startActivity(intent);

call like this: 像这样打电话:

Intent intent = new Intent(DownloadUpdate.this, DisplayMessageActivity.class); 
intent.putExtra(EXTRA_MESSAGE, result);
startActivity(intent);

i think ur calling DownloadUpdate from another class or activity as: 我认为您从另一个类或活动中调用DownloadUpdate为:

new DownloadUpdate().execute(params);

to solve the context problem in DownloadUpdate , create a constructor like: 要解决DownloadUpdate的上下文问题,请创建类似以下的构造函数:

public DownloadUpdate(Context context){
    this.context = context;
}

here this.context means your globally declared Context variable in DownloadUpdate class. 这里this.context表示您在DownloadUpdate类中全局声明的Context变量。 then call DownloadUpdate as: 然后以以下方式调用DownloadUpdate

new DownloadUpdate(your_context).execute(params);

then use the context you have get in DownloadUpdate to create your intent. 然后使用您在DownloadUpdate获得的上下文来创建您的意图。 like: 喜欢:

@Override
protected void onPostExecute(String result) {
   //textView.setText(result);
    Intent intent = new Intent(context, DisplayMessageActivity.class); 
    intent.putExtra(EXTRA_MESSAGE, result);
    startActivity(intent);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM