我有一个简单的文本视图小部件,我试图使用AlarmManager每秒更新一次。当我运行应用程序时,Log.d(“test”,“hello1”)显示在我的LogCat中,但是Log.d(“test”,“service”)没有出现,所以看起来程序不是甚至到达我的MyService类。
我非常感谢任何帮助。
谢谢。
这是我的AppWidgetProvider类:
public class NetworkSpeedWidget extends AppWidgetProvider {
private PendingIntent service = null;
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
Log.d("test", "hello");
super.onUpdate(context, appWidgetManager, appWidgetIds);
final AlarmManager m = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
final Intent i = new Intent(context, MyService.class);
if (service == null)
{
service = PendingIntent.getService(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
}
Log.d("test", "hello1");
m.setRepeating(AlarmManager.RTC, System.currentTimeMillis(),1000,service);
}
}
这是我的MyService类:
public class MyService extends Service{
@Override
public void onCreate()
{
Log.d("test", "service");
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
buildUpdate();
return super.onStartCommand(intent, flags, startId);
}
private void buildUpdate()
{
MainActivity object = new MainActivity();
String objectString = object.getMegaBitsPerSecondString();
AppWidgetManager manager = AppWidgetManager.getInstance(this);
ComponentName thisWidget = new ComponentName(this, NetworkSpeedWidget.class);
int[]ids = manager.getAppWidgetIds(thisWidget);
final int N = ids.length;
for (int i = 0; i < N; i++){
int awID = ids[i];
RemoteViews v = new RemoteViews(getPackageName(), R.layout.widget);
v.setTextViewText(R.id.widgetTextView,objectString);
manager.updateAppWidget(awID, v);
}
}
@Override
public IBinder onBind(Intent intent)
{
return null;
}
}
答案 0 :(得分:2)
我的所有代码都是正确的,我只需要在我的Manifest中声明它。
我只是添加了以下一行:
<service android:enabled="true" android:name=".MyService" />
谢谢你的帮助。