当我们在那时点击小部件时,我需要打开活动屏幕(或应用程序)。如何做到这一点?
答案 0 :(得分:14)
您需要在窗口小部件上设置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);
检查出来
答案 1 :(得分:7)
将此代码包含在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();
}
}
答案 2 :(得分:1)
使用Kotlin
您需要在窗口小部件视图的“点击”上添加PendingIntent
remoteViews.setOnClickPendingIntent(R.id.widgetRoot,
PendingIntent.getActivity(context, 0, Intent(context, MainActivity::class.java), 0))
其中 widgetRoot 是我的小部件的父ViewGroup
更新中
待定意向通常添加在 onUpdate 回调
中 override fun onUpdate(
context: Context,
appWidgetManager: AppWidgetManager,
appWidgetIds: IntArray) {
// There may be multiple widgets active, so update all of them
val widgetIds = appWidgetManager.getAppWidgetIds( ComponentName(context, ClockWidget::class.java))
for (appWidgetId in widgetIds) {
// Construct the RemoteViews object
val remoteViews = RemoteViews(context.packageName, R.layout.clock_widget)
//Open App on Widget Click
remoteViews.setOnClickPendingIntent(R.id.weatherRoot,
PendingIntent.getActivity(context, 0, Intent(context, MainActivity::class.java), 0))
//Update Widget
remoteViews.setTextViewText(R.id.appWidgetText, Date().toString())
appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
}
}
}
答案 3 :(得分:0)
App Widgets的Android开发人员页面提供了相关信息和完整示例:http://developer.android.com/guide/topics/appwidgets/index.html
答案 4 :(得分:0)
非常简单(在 xamarin c# android mono 中):
public override void OnReceive(Context context, Intent intent)
{
if (ViewClick.Equals(intent.Action))
{
var pm = context.PackageManager;
try
{
var packageName = "com.companyname.YOURPACKAGENAME";
var launchIntent = pm.GetLaunchIntentForPackage(packageName);
context.StartActivity(launchIntent);
}
catch
{
// Something went wrong :)
}
}
base.OnReceive(context, intent);
}