Android应用程序小部件打开,当应用程序关闭时单击"不工作"



请不要将此标记为重复没有找到解决方法

所以基本上我试图建立一个简单的小部件上有4个按钮,但onreceive是不被调用时,应用程序没有在后台打开,我看了到处(甚至谷歌的第二页),但不能找到一个解决方案,工作。

接收者已注册在Manifest中:

<receiver android:name=".Amount.WidgetAdd" android:exported="true" >
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/widget_add_info" />
</receiver>

我的On Budget是这样设置的:

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
for (int i = 0; i<appWidgetIds.length; i++) {
int id = appWidgetIds[i];
remoteViews = new RemoteViews(context.getPackageName(),R.layout.widget_add);
remoteViews.setOnClickPendingIntent(R.id.image_joints, getPendingSelfIntent(context, JointOnClick));
remoteViews.setOnClickPendingIntent(R.id.image_bowls, getPendingSelfIntent(context, BowlOnClick));
remoteViews.setOnClickPendingIntent(R.id.image_pipe, getPendingSelfIntent(context, PipeOnClick));
remoteViews.setOnClickPendingIntent(R.id.image_more, getPendingSelfIntent(context, MoreOnClick));
Intent intent = new Intent(context, WidgetAdd.class);
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
420, intent, PendingIntent.FLAG_UPDATE_CURRENT);
c = context;
prefs = c.getSharedPreferences("WT", Context.MODE_PRIVATE);

appWidgetManager.updateAppWidget(id, remoteViews);
}
super.onUpdate(context, appWidgetManager, appWidgetIds);
}

和我的OnReceive看起来像这样:

@Override
public void onReceive(Context context, Intent intent) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
context.startForegroundService(intent);
} else {
context.startService(intent);
}
if (JointOnClick.equals(intent.getAction())){
Toast.makeText(context, "Joint", Toast.LENGTH_SHORT).show();
try {
AddJoint();
} catch (IOException e) {
e.printStackTrace();
}
}
if (BowlOnClick.equals(intent.getAction())){
Toast.makeText(context, "Bowl", Toast.LENGTH_SHORT).show();
try {
AddBowl();
} catch (IOException e) {
e.printStackTrace();
}
//your onClick action is here
}
if (PipeOnClick.equals(intent.getAction())){
//your onClick action is here
Toast.makeText(context, "Pipe", Toast.LENGTH_SHORT).show();
try {
AddPipe();
} catch (IOException e) {
e.printStackTrace();
}
}
if (MoreOnClick.equals(intent.getAction())){
//your onClick action is here
Toast.makeText(context, "More", Toast.LENGTH_SHORT).show();
Log.w("WidgetAdd", "More");
}
super.onReceive(context, intent);
}

有人有什么建议吗?

您必须添加标志FLAG_ACTIVITY_NEW_TASK以表示意图。

intent.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK );

相关内容