拜托,我有点卡在这里。我正在使用后台服务更新我的窗口小部件(而不是使用“onUpdate”方法),使用AlarmManager进行间隔重复。一切似乎都运行良好,ListView填充数据,但由于某些原因,ListView上的项目没有启动单击时PendingIntent上设置的Activity。
更新:
认为代码工作正常。在其他设备上测试它并且工作正常(摩托罗拉和HTC)。但由于某种原因,它不适用于我的三星Galaxy S5
以下是代码
WidgetService.java
public class WidgetService extends Service implements LocationListener, GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks {
private LocationManager locationManager;
private LocationRequest locationRequest;
private GoogleApiClient googleApiClient;
@Override
public void onCreate() {
super.onCreate();
//Initialize Google API client build and connect
buildGoogleApiClient();
//Initialize Android Location Service
locationManager = (LocationManager) this.getSystemService(this.LOCATION_SERVICE);
//Check if Location is Enabled
if (LocationHelper.checkLocationEnabled(null, locationManager)) {
//TODO: Check Google Play Services Availability
googleApiClient.connect();
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
int[] widget_ids = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
if (widget_ids != null) {
buildUpdate(widget_ids);
}
return super.onStartCommand(intent, flags, startId);
}
private void buildUpdate(int... appwidget_ids) {
for (int appwidget_id : appwidget_ids) {
RemoteViews views = new RemoteViews(getPackageName(), R.layout.closest_banks_appwidget);
if (ClosestBanksWidget.LAST_LOCATION != null) {
Intent intent = new Intent(this, WidgetRemoteViewsService.class);
// Add the app widget ID to the intent extras.
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appwidget_id);
intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
/*
Intent start_activity_intent = new Intent(this, BankFinderBroadcastReceiver.class);
intent.setAction(ClosestBanksWidget.WIDGET_CLICK_INTENT_ACTION);
PendingIntent start_activity_PI = PendingIntent.getBroadcast(this, 0,
start_activity_intent, 0);
*/
Intent start_activity_intent = new Intent(this, LocationDetailActivity.class);
PendingIntent start_activity_PI = PendingIntent.getActivity(this, 0,
start_activity_intent, PendingIntent.FLAG_UPDATE_CURRENT);
String[] params = {"search", String.valueOf(ClosestBanksWidget.LAST_LOCATION.getLatitude()), String.valueOf(ClosestBanksWidget.LAST_LOCATION.getLongitude()), "", ""};
intent.putExtra("query_params", params);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
views.setRemoteAdapter(R.id.widget_location_list_view, intent);
else
views.setRemoteAdapter(appwidget_id, R.id.widget_location_list_view, intent);
views.setPendingIntentTemplate(R.id.widget_location_list_view, start_activity_PI);
}
// Push update for this widget to the home screen
//ComponentName thisWidget = new ComponentName(this, ClosestBanksWidget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(this);
manager.notifyAppWidgetViewDataChanged(appwidget_id, R.id.widget_location_list_view);
manager.updateAppWidget(appwidget_id, views);
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
protected synchronized void buildGoogleApiClient() {
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
protected void startLocationUpdates() {
createLocationRequest();
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
protected void createLocationRequest() {
locationRequest = new LocationRequest();
locationRequest.setInterval(victorikoro.com.bankfinder.objects.Constants.LOCATION_UPDATE_FAST_INTERVAL * 2);
locationRequest.setFastestInterval(victorikoro.com.bankfinder.objects.Constants.LOCATION_UPDATE_FAST_INTERVAL);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
//locationRequest.setSmallestDisplacement(Constants.MINIMUM_LOCATION_DISPLACEMENT);
}
@Override
public void onConnected(Bundle bundle) {
//Get Last Location
ClosestBanksWidget.LAST_LOCATION = LocationServices.FusedLocationApi.getLastLocation(
googleApiClient);
//Start getting periodic location updates
startLocationUpdates();
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onLocationChanged(Location location) {
ClosestBanksWidget.LAST_LOCATION = location;
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
ClosestBankWidget.java
public class ClosestBanksWidget extends AppWidgetProvider {
protected Context mContext;
public static Location LAST_LOCATION;
public static String WIDGET_CLICK_INTENT_ACTION = "victorikoro.com.bankfinder.WIDGET_START_ACTIVITY";
private PendingIntent service;
public ClosestBanksWidget() {
super();
}
@Override
public void onEnabled(Context context) {
super.onEnabled(context);
mContext = context;
Intent intent = new Intent(context, WidgetService.class);
context.startService(intent);
}
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
int N = appWidgetIds.length;
int[] widget_ids = new int[N];
int[] widget_ids_clone = new int[N];
final AlarmManager m = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
for (int i = 0; i < appWidgetIds.length; i++) {
widget_ids[i] = appWidgetIds[i];
}
final Calendar TIME = Calendar.getInstance();
TIME.set(Calendar.MINUTE, 0);
TIME.set(Calendar.SECOND, 0);
TIME.set(Calendar.MILLISECOND, 0);
final Intent i = new Intent(context, WidgetService.class);
i.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, widget_ids);
if (service == null) {
service = PendingIntent.getService(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
}
m.setRepeating(AlarmManager.RTC, TIME.getTime().getTime(), Constants.WIDGET_UPDATE_INTERVAL, service);
super.onUpdate(context, appWidgetManager, appWidgetIds);
}
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
}
}
WidgetRemoteViewService.java
public class WidgetRemoteViewsService extends RemoteViewsService {
@Override
public RemoteViewsFactory onGetViewFactory(Intent intent) {
return new WidgetRemoteViewsFactory(this.getApplicationContext(), intent);
}
class WidgetRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory {
private static final int mCount = 10;
protected List<ATMLocation> locations = new ArrayList<ATMLocation>();
private Context mContext;
private int mAppWidgetId;
private Intent intent;
protected jsqlite.Database db;
public WidgetRemoteViewsFactory(Context applicationContext, Intent intent) {
this.mContext = applicationContext;
this.intent = intent;
//Initialize DB
db = DBHelper.getDBInstance(mContext);
if (db != null) {
String[] params = intent.getStringArrayExtra("query_params");
this.locations = LocationHelper.getATMLocations(db, params).subList(0, mCount);
}
}
@Override
public void onCreate() {
}
public void onDestroy() {
if (db != null) {
try {
db.close();
} catch (jsqlite.Exception e) {
e.printStackTrace();
}
}
}
@Override
public int getCount() {
return locations.size();
}
public RemoteViews getViewAt(int position) {
ATMLocation location = locations.get(position);
RemoteViews rv = new RemoteViews(mContext.getPackageName(), R.layout.list_item_widget);
String bank_name = LocationHelper.getFormattedBankName(location.bank, mContext);
if (location.branch.equalsIgnoreCase("true")) {
bank_name += ("(Branch)");
}
rv.setTextViewText(R.id.widget_bank_name, bank_name);
rv.setTextViewText(R.id.widget_bank_address, location.address);
rv.setTextViewText(R.id.widget_distance, LocationHelper.getFormattedDistance(location.distance));
rv.setImageViewResource(R.id.widget_bank_logo_small, LocationHelper.getBankLogoResourceID(location.bank, mContext));
// Return the remote views object.
Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putString("latitude", location.latitude);
bundle.putString("longitude", location.longitude);
bundle.putString("id", location.id);
bundle.putString("given_id", location.given_id);
bundle.putString("bank", location.bank);
bundle.putString("email", location.email);
bundle.putString("address", location.address);
bundle.putString("tel", location.tel);
bundle.putString("tel2", location.tel2);
bundle.putString("branch", location.branch);
bundle.putString("distance", location.distance);
bundle.putString("other", location.other);
bundle.putString("machines", location.machines);
intent.putExtras(bundle);
rv.setOnClickFillInIntent(R.id.widget_list_item, intent);
return rv;
}
@Override
public RemoteViews getLoadingView() {
return null;
}
@Override
public int getViewTypeCount() {
return 1;
}
public long getItemId(int position) {
return position;
}
public boolean hasStableIds() {
return true;
}
public void onDataSetChanged() {
if (db != null) {
locations = LocationHelper.getATMLocations(db, intent.getStringArrayExtra("query_params"));
}
}
}
}
closest_bank_appwidget.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/cardview_light_background">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
android:backgroundTint="@color/colorPrimaryDark"
android:backgroundTintMode="screen">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_margin="10dp"
android:textSize="18sp"
android:text="@string/widget_title"
android:textColor="@android:color/white"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:textSize="15sp"
android:text="--"
android:textStyle="italic"
android:textColor="@android:color/white"
android:layout_centerInParent="true"
android:layout_marginRight="5dp" />
</RelativeLayout>
<ListView
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:id="@+id/widget_location_list_view"
android:divider="@android:drawable/divider_horizontal_textfield"
android:dividerHeight="1dp"
android:layout_margin="10dp"
android:drawSelectorOnTop="true">
</ListView>
</LinearLayout>
list_item_widget.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/widget_list_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:elevation="2dp"
android:orientation="vertical"
android:padding="10dp">
<ImageView
android:id="@+id/widget_bank_logo_small"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginRight="12dp"
android:focusable="false"
android:src="@drawable/wema_logo" />
<TextView
android:id="@+id/widget_bank_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="@+id/widget_bank_logo_small"
android:focusable="false"
android:text="@string/wema"
android:textColor="@color/colorPrimary"
android:textSize="14sp"
android:textStyle="bold" />
<TextView
android:id="@+id/widget_bank_address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/widget_bank_name"
android:layout_marginBottom="4dp"
android:layout_marginTop="4dp"
android:layout_toEndOf="@+id/widget_bank_logo_small"
android:layout_toRightOf="@+id/widget_bank_logo_small"
android:focusable="false"
android:text="@string/wema_loc"
android:textColor="#565656"
android:textSize="14sp" />
<TextView
android:id="@+id/widget_distance"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_below="@+id/widget_bank_logo_small"
android:layout_marginTop="10dp"
android:focusable="false"
android:text="--"
android:textColor="@color/colorPrimary"
android:textSize="13sp"
android:textStyle="bold" />
</RelativeLayout>