如何从 android 中的 activity 启动应用程序?
How to start an application from an activity in android?
我正在按照本教程 http://www.androidhive.info/2014/06/android-facebook-like-custom-listview-feed-using-volley/ 创建一个类似于 Facebook 的新闻源。在本教程中,提要在启动应用程序时自行启动。但我需要通过单击应用程序中的按钮来启动提要。
只是我需要做的是,有一个扩展应用程序的 AppController class。我想通过登录Activityclass来启动它。 AppController 和 LoginActivity classes 都在我的应用程序包中。我不知道该怎么做,因为 AppController class 不是 Activity class。
我在我的应用程序中尝试了以下代码来启动提要,但它在包中给出了 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();
}
}
}
您需要将 "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"
}
希望对您有所帮助。
因此您需要将代码替换为:
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 然后 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>
我正在按照本教程 http://www.androidhive.info/2014/06/android-facebook-like-custom-listview-feed-using-volley/ 创建一个类似于 Facebook 的新闻源。在本教程中,提要在启动应用程序时自行启动。但我需要通过单击应用程序中的按钮来启动提要。 只是我需要做的是,有一个扩展应用程序的 AppController class。我想通过登录Activityclass来启动它。 AppController 和 LoginActivity classes 都在我的应用程序包中。我不知道该怎么做,因为 AppController class 不是 Activity class。 我在我的应用程序中尝试了以下代码来启动提要,但它在包中给出了 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();
}
}
}
您需要将 "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"
}
希望对您有所帮助。
因此您需要将代码替换为:
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 然后 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>