【问题标题】:How to start an application from an activity in android?如何从android中的活动启动应用程序?
【发布时间】:2016-03-08 06:21:55
【问题描述】:

我正在按照本教程http://www.androidhive.info/2014/06/android-facebook-like-custom-listview-feed-using-volley/ 创建一个像 Facebook 一样的新闻源。在本教程中,提要在启动应用程序时自行启动。但我需要通过单击应用程序中的按钮来启动提要。 简单地说,我需要做的是,有一个扩展应用程序的 AppController 类。我想通过 LoginActivity 类启动它。 AppController 和 LoginActivity 类都在我的应用程序包中。我不知道该怎么做,因为 AppController 类不是 Activity 类。 我在我的应用程序中尝试了以下代码来启动提要,但它在包中给出了 NameNotFoundException。

Intent loginIntent;
PackageManager manager = getPackageManager();
try {
      loginIntent = manager.getLaunchIntentForPackage("example.com.storyteller.app.AppController");

      if (loginIntent == null)
         throw new PackageManager.NameNotFoundException();
      loginIntent.addCategory(Intent.CATEGORY_LAUNCHER);
      startActivity(loginIntent);
} catch (PackageManager.NameNotFoundException e) {
      Log.e("TAG","feed name error");

}

这是我的清单文件

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="example.com.storyteller">

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

 <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".LoginActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name=".MainActivity"/>

这是我的文件层次结构。

请问有人可以在这件事上帮助我吗?任何帮助将不胜感激。

AppController.java

public class AppController extends Application {

public static final String TAG = AppController.class.getSimpleName();

private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
LruBitmapCache mLruBitmapCache;

private static AppController mInstance;

@Override
public void onCreate() {
    super.onCreate();
    mInstance = this;
}

public static synchronized AppController getInstance() {
    return mInstance;
}

public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        mRequestQueue = Volley.newRequestQueue(getApplicationContext());
    }

    return mRequestQueue;
}

public ImageLoader getImageLoader() {
    getRequestQueue();
    if (mImageLoader == null) {
        getLruBitmapCache();
        mImageLoader = new ImageLoader(this.mRequestQueue, mLruBitmapCache);
    }

    return this.mImageLoader;
}

public LruBitmapCache getLruBitmapCache() {
    if (mLruBitmapCache == null)
        mLruBitmapCache = new LruBitmapCache();
    return this.mLruBitmapCache;
}

public <T> void addToRequestQueue(Request<T> req, String tag) {
    req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
    getRequestQueue().add(req);
}

public <T> void addToRequestQueue(Request<T> req) {
    req.setTag(TAG);
    getRequestQueue().add(req);
}

public void cancelPendingRequests(Object tag) {
    if (mRequestQueue != null) {
        mRequestQueue.cancelAll(tag);
    }
}

}

MainActivity.java

public class MainActivity extends Activity {

private static final String TAG = MainActivity.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
private String URL_FEED = "http://api.androidhive.info/feed/feed.json";


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

    listView = (ListView) findViewById(R.id.list);

    feedItems = new ArrayList<FeedItem>();

    listAdapter = new FeedListAdapter(this, feedItems);
    listView.setAdapter(listAdapter);

    // These two lines not needed,
    // just to get the look of facebook (changing background color & hiding the icon)
    //getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3b5998")));
    //getActionBar().setIcon(
    //new ColorDrawable(getResources().getColor(android.R.color.transparent)));

    // We first check for cached request
    Cache cache = AppController.getInstance().getRequestQueue().getCache();
    Cache.Entry entry = cache.get(URL_FEED);
    if (entry != null) {
        // fetch the data from cache
        try {
            String data = new String(entry.data, "UTF-8");
            try {
                parseJsonFeed(new JSONObject(data));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    } else {
        // making fresh volley request and getting json
        JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.GET,
                URL_FEED, null, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                VolleyLog.d(TAG, "Response: " + response.toString());
                if (response != null) {
                    parseJsonFeed(response);
                }
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
            }
        });

        // Adding request to volley request queue
        AppController.getInstance().addToRequestQueue(jsonReq);
    }

}

/**
 * Parsing json reponse and passing the data to feed view list adapter
 * */
private void parseJsonFeed(JSONObject response) {
    try {
        JSONArray feedArray = response.getJSONArray("feed");

        for (int i = 0; i < feedArray.length(); i++) {
            JSONObject feedObj = (JSONObject) feedArray.get(i);

            FeedItem item = new FeedItem();
            item.setId(feedObj.getInt("id"));
            item.setName(feedObj.getString("name"));

            // Image might be null sometimes
            String image = feedObj.isNull("image") ? null : feedObj
                    .getString("image");
            item.setImge(image);
            item.setStatus(feedObj.getString("status"));
            item.setProfilePic(feedObj.getString("profilePic"));
            item.setTimeStamp(feedObj.getString("timeStamp"));

            // url might be null sometimes
            String feedUrl = feedObj.isNull("url") ? null : feedObj
                    .getString("url");
            item.setUrl(feedUrl);

            feedItems.add(item);
        }

        // notify data changes to list adapater
        listAdapter.notifyDataSetChanged();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

}

【问题讨论】:

  • 包名正确。 AppController 类扩展了应用程序。因此,它不是一项活动。所以我想在这种情况下我不能使用 startActivity() 方法。
  • 不,那不是我想做的。有一个扩展应用程序的 AppController 类。我想通过 LoginActivity 类启动它。 AppController 和 LoginActivity 类都在我的应用程序包中。我不知道该怎么做,因为 AppController 类不是 Activity 类。
  • 你能分享 AppController 以及它将从哪个 Activity 类调用 Next Activity
  • MainActivity 类需要一些从 AppController 类获取的数据。这就是为什么我需要先启动它。如果您还需要引用它,则添加了 MainActivity 类

标签: android listview android-adapter feed


【解决方案1】:

在您的清单中更改此项 定义首先调用 AppController 然后 category.LAUNCHER 在

中添加 AppController(android:name=".AppController")
<application
android:name=".AppController"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
    android:name=".LoginActivity"
    android:label="@string/app_name"
    android:theme="@style/AppTheme.NoActionBar">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

【讨论】:

    【解决方案2】:

    您需要将“example.com.storyteller.app.AppController”替换为您的应用程序包。

    应用程序包配置在清单文件的顶部

    例如:

     <manifest
      xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.google.zxing.client.android"
    

    或者在 gradle 文件中

     defaultConfig {
            applicationId "example.com.storyteller.app"
            //applicationId  "com.studio.eyeprotect"
            minSdkVersion 15
            targetSdkVersion 23
            versionCode 2
            versionName "1.0.1"
        }
    

    希望对你有帮助。

    【讨论】:

    • example.com.storyteller 是一个应用包。
    【解决方案3】:

    所以你需要将代码替换为:

    Intent loginIntent;
    PackageManager manager = getPackageManager();
    try {
          loginIntent = manager.getLaunchIntentForPackage("example.com.storyteller");
    
          if (loginIntent == null)
             throw new PackageManager.NameNotFoundException();
          loginIntent.addCategory(Intent.CATEGORY_LAUNCHER);
          startActivity(loginIntent);
    } catch (PackageManager.NameNotFoundException e) {
          Log.e("TAG","feed name error");
    
    }
    

    【讨论】:

    • 不,那不是我想做的。有一个扩展应用程序的 AppController 类。我想通过 LoginActivity 类启动它。 AppController 和 LoginActivity 类都在我的应用程序包中。我不知道该怎么做,因为 AppController 类不是 Activity 类。
    • 啊,也许我理解你的想法,请研究一下:Url Schema
    猜你喜欢
    • 2012-04-21
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 2016-12-09
    • 2012-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多