2012-02-11 100 views
4

我需要创建一个Widget,一旦点击它即可启动服务。服务会执行某些操作,更改小部件图片,播放声音等,然后停止。Android Widget不会启动服务

的AppWidgetProvider:

public class WidgetActivity extends AppWidgetProvider { 


@Override 
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { 

     RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout); 
     Intent intent = new Intent(context.getApplicationContext(), SilentService.class); 
     intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds); 
     PendingIntent pendingIntent = PendingIntent.getService(
       context.getApplicationContext(), 0, intent, 
       PendingIntent.FLAG_UPDATE_CURRENT); 
     remoteViews.setOnClickPendingIntent(R.id.LinLayWiget, pendingIntent); 
     appWidgetManager.updateAppWidget(appWidgetIds, remoteViews); 

     context.startService(intent); 

} 


} 

服务:

public class SilentService extends Service { 
    @Override 
    public IBinder onBind(Intent intent) { 
    return null; 
    } 
    @Override 
    public void onCreate() { 

     Toast.makeText(this, "I'm Alive!", 1500).show(); 
     MediaPlayer mpl = MediaPlayer.create(this, R.raw.enter); 
     mpl.start(); 

    } 



    @Override 
    public void onDestroy() { 
    //code to execute when the service is shutting down 
    } 
    @Override 
    public void onStart(Intent intent, int startid) { 
    //code to execute when the service is starting up 
    } 



    } 

清单:

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
     package="FX.Widget" 
     android:versionCode="1" 
     android:versionName="1.0"> 
    <uses-sdk android:minSdkVersion="8" /> 

    <application android:icon="@drawable/icon" android:label="@string/app_name"> 

     <receiver android:name="widget.cam.com.WidgetActivity" android:label="FXMaster" android:icon="@drawable/assiconwi"> 
      <intent-filter> 
       <action android:name="android.appwidget.action.APPWIDGET_UPDATE" /> 
       <action android:name="android.appwidget.action.APPWIDGET_ENABLED"/> 
      </intent-filter> 
      <meta-data 
       android:name="android.appwidget.provider" 
       android:resource="@xml/widgetprovider" /> 
     </receiver> 


     <service 
     android:enabled="true" 
     android:name=".SilentService"> 
     </service> 


    </application> 
</manifest> 

但是,一旦我点击窗口小部件,没有任何反应......任何想法,为什么?

谢谢!

回答

2

看看本教程一旦你可能得到一些想法。

Widget Tutorial Using Service

+0

谢谢,我已经收窄,使用教程,但仍是点击不来通过。请参阅 - http://stackoverflow.com/questions/9242039/android-widget-wont-have-a-click – 2012-02-11 16:55:04

+0

解决了它!在示例的源代码中,有一个main.xml文件,它似乎与应用程序的其余部分无关!但是如果没有它,点击功能将不起作用。 :) – 2012-02-11 22:03:42