如何在Android中从小部件打开应用程序?

问题描述:

当我们点击小部件的时候,我需要打开一个活动屏幕(或应用程序)。如何做到这一点?如何在Android中从小部件打开应用程序?

你需要在你的widget设置onClickpendingIntent

Intent intent = new Intent(context, ExampleActivity.class); 
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); 
// Get the layout for the App Widget and attach an on-click listener to the button 
RemoteViews views = new RemoteViews(context.getPackageName(),R.layout.appwidget_provider_layout); 
views.setOnClickPendingIntent(R.id.button, pendingIntent); 

检查了这一点

Processing more than one button click at Android Widget

+0

第一个链接死了。 – 2013-01-07 08:42:16

+0

侧面的问题,你可以提取特定应用程序的活动? (也许我不知道ExampleActivity.class是什么类) – RelativeGames 2013-03-27 19:12:44

为App小部件的Android开发者页面已经信息和完整的例子做的正是这一点:http://developer.android.com/guide/topics/appwidgets/index.html

将此代码包含在您的WidgetProvider类的onUpdate()方法中。

for(int j = 0; j < appWidgetIds.length; j++) 
{ 
    int appWidgetId = appWidgetIds[j]; 

    try { 
     Intent intent = new Intent("android.intent.action.MAIN"); 
     intent.addCategory("android.intent.category.LAUNCHER"); 

     intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); 
     intent.setComponent(new ComponentName("your Application package", 
      "fully qualified name of main activity of the app")); 
     PendingIntent pendingIntent = PendingIntent.getActivity(
      context, 0, intent, 0); 
     RemoteViews views = new RemoteViews(context.getPackageName(), 
      layout id); 
     views.setOnClickPendingIntent(view Id on which onclick to be handled, pendingIntent); 
    appWidgetManager.updateAppWidget(appWidgetId, views); 
    } catch (ActivityNotFoundException e) { 
      Toast.makeText(context.getApplicationContext(), 
        "There was a problem loading the application: ", 
        Toast.LENGTH_SHORT).show(); 
    } 

} 
+0

Works令人惊叹!谢谢Shivanand Darur – 2015-01-08 08:04:17

+3

“你的应用程序包”,“应用程序主要活动的完全限定名称”是指'intent.setComponent(new ComponentName(context.getPackageName(),MainActivity.class.getName());'' – 2015-10-30 20:56:24