android service更新widget,Android Widget+Service

问题

I have a music player which plays music using a service,all the broadcast receivers within that service are defined inside the service and not externally.

I am totally new to widgets so i had been seeing a few tutorials.But they didn't help me much

I am totally new to pending intents soo.I am so confused right now please help me out...

All i want to do is just trigger the broadcast inside the service using the button of the widget ...

Here is the copy pasted code which i had been trying to understand

RemoteViews controlButtons = new RemoteViews(context.getPackageName(),

R.layout.widget);

Intent playIntent = new Intent(context, Music_service.class);

PendingIntent playPendingIntent = PendingIntent.getService(

context, REQUEST_CODE, playIntent, INTENT_FLAGS);

controlButtons.setOnClickPendingIntent(

R.id.bPlay, playPendingIntent);

appWidgetManager.updateAppWidget(appWidgetIds, controlButtons);

And here is my app

:D

f0db5dafdd61373f33ceabe6380bec47.png

回答1:

Create a custom Intent Action and set it as PendingIntent to the widget item ( button in your case)

Intent intent = new Intent("com.example.app.ACTION_PLAY");

PendingIntent pendingIntent = PendingIntent.getService(context.getApplicationContext(), 100,

intent, PendingIntent.FLAG_UPDATE_CURRENT);

RemoteViews remoteViews = new RemoteViews(context.getPackageName(),R.layout.widget_layout);

remoteViews.setOnClickPendingIntent(R.id.bPlay, pendingIntent);

Then, change your manifest to handle the Action passed in PendingIntent

Finally , when the play button is clicked , the Service will receive the Action and started. Check for the Action in onStartCommand

@Override

public int onStartCommand(Intent intent, int flag, int startId) {

if(intent.getAction().equalsIgnoreCase("com.example.app.ACTION_PLAY")){

// do your stuff here

}

You can set similar custom Actions for all the required views in the Widget.

See the compile code here https://gist.github.com/androidbensin/4a9f044ac0b3110c049e

Hope your are good now. Let me know if any issues

来源:https://stackoverflow.com/questions/23553816/android-widgetservice

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值