Android 자체 애플리케이션에 Widget 추가

6263 단어
Widget 추가 방법: 긴 데스크톱 - Widget 목록 팝업 - 선택하면 데스크톱에 추가됩니다. 다음은 자신의 프로그램에 추가할 수 있는 기능을 지원합니다. 쓸데없는 말은 하지 않고 코드로 바로 갑니다.
1. ViewGroup을 계승하여 Widget을 추가할 수 있는 컨트롤을 실현
package cn.winplus.w2h;

import android.content.Context;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

public class WidgetLayout extends ViewGroup {

	//   touch   
	private int[] cellInfo = new int[2];
	private OnLongClickListener mClickListener;

	public WidgetLayout(Context context) {
		super(context);

		mClickListener = new OnLongClickListener() {

			@Override
			public boolean onLongClick(View arg0) {

				return false;
			}
		};

	}

	public void addInScreen(View child, int width, int height) {
		LayoutParams lp = new LayoutParams(width, height);
		lp.x = cellInfo[0];
		lp.y = cellInfo[1];
		child.setOnLongClickListener(mClickListener);
		addView(child, lp);
	}

	@Override
	protected void onLayout(boolean arg0, int arg1, int arg2, int arg3, int arg4) {
		LayoutParams lParams;
		for (int i = 0; i < getChildCount(); i++) {
			lParams = (LayoutParams) getChildAt(i).getLayoutParams();
			getChildAt(i).layout(lParams.x, lParams.y,
					lParams.x + lParams.width, lParams.y + lParams.height);
		}
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);

		LayoutParams lParams;
		for (int i = 0; i < getChildCount(); i++) {
			lParams = (LayoutParams) getChildAt(i).getLayoutParams();
			getChildAt(i).measure(
					MeasureSpec.makeMeasureSpec(MeasureSpec.EXACTLY,lParams.width),
					MeasureSpec.makeMeasureSpec(MeasureSpec.EXACTLY,lParams.height));
		}
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		cellInfo[0] = (int) ev.getX();
		cellInfo[1] = (int) ev.getY();
		return super.dispatchTouchEvent(ev);
	}

	private class LayoutParams extends ViewGroup.LayoutParams {

		int x;
		int y;

		public LayoutParams(int arg0, int arg1) {
			super(arg0, arg1);
		}

	}

}

2. Widget 관련 작업 추가
package cn.winplus.w2h;

import android.app.Activity;
import android.appwidget.AppWidgetHost;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProviderInfo;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnLongClickListener;

public class Widget2HomeActivity extends Activity implements OnLongClickListener{

	
	private static final String TAG = "Widget2HomeActivity";
	
	private AppWidgetHost mAppWidgetHost;
	private AppWidgetManager mAppWidgetManager;
	private WidgetLayout mWidgetLayout;
	private Context context;
	private static final int APPWIDGET_HOST_ID = 0x100;
	private static final int REQUEST_PICK_APPWIDGET = 0;
	private static final int REQUEST_CREATE_APPWIDGET = 1;
	private static final String EXTRA_CUSTOM_WIDGET = "custom_widget";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		context = getApplicationContext();

		mAppWidgetManager = AppWidgetManager.getInstance(context);
		mAppWidgetHost = new AppWidgetHost(context, APPWIDGET_HOST_ID);
		mAppWidgetHost.startListening(); 

		mWidgetLayout = new WidgetLayout(this);

		mWidgetLayout.setOnLongClickListener(this);
		setContentView(mWidgetLayout);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case REQUEST_PICK_APPWIDGET:
				addAppWidget(data);
				break;
			case REQUEST_CREATE_APPWIDGET:
				completeAddAppWidget(data);
				break;
			}
		} else if (requestCode == REQUEST_PICK_APPWIDGET
				&& resultCode == RESULT_CANCELED && data != null) {
			int appWidgetId = data.getIntExtra(
					AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
			if (appWidgetId != -1) {
				mAppWidgetHost.deleteAppWidgetId(appWidgetId);
			}
		}
	}

	private void addAppWidget(Intent data) {
		int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,-1);
		String customWidget = data.getStringExtra(EXTRA_CUSTOM_WIDGET);
		if ("search_widget".equals(customWidget)) {
			mAppWidgetHost.deleteAppWidgetId(appWidgetId);
		} else {
			AppWidgetProviderInfo appWidget = mAppWidgetManager
					.getAppWidgetInfo(appWidgetId);

			Log.d("addAppWidget", "configure:" + appWidget.configure);
			if (appWidget.configure != null) {
				//       
				Intent intent = new Intent(
						AppWidgetManager.ACTION_APPWIDGET_CONFIGURE);
				intent.setComponent(appWidget.configure);
				intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
						appWidgetId);

				startActivityForResult(intent, REQUEST_CREATE_APPWIDGET);
			} else {
				//        
				onActivityResult(REQUEST_CREATE_APPWIDGET, Activity.RESULT_OK,
						data);
			}
		}
	}

	

	/**
	 *   widget
	 * 
	 * @param data
	 */
	private void completeAddAppWidget(Intent data) {
		Bundle extras = data.getExtras();
		int appWidgetId = extras
				.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);

		AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager
				.getAppWidgetInfo(appWidgetId);

		View hostView = mAppWidgetHost.createView(this, appWidgetId,
				appWidgetInfo);

		mWidgetLayout.addInScreen(hostView, appWidgetInfo.minWidth,
				appWidgetInfo.minHeight);
	}
	
	@Override
	protected void onDestroy() {
		try {
            mAppWidgetHost.stopListening();
        } catch (NullPointerException ex) {
            Log.i(TAG, "problem while stopping AppWidgetHost during Launcher destruction", ex);
        }
		super.onDestroy();
	}

	@Override
	public boolean onLongClick(View v) {
		Intent pickIntent = new Intent(AppWidgetManager.ACTION_APPWIDGET_PICK);
		pickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetHost.allocateAppWidgetId());
		// start the pick activity
		startActivityForResult(pickIntent, REQUEST_PICK_APPWIDGET);
		return false;
	}
}

효과도를 보십시오.
전재는 출처를 밝혀 주십시오.http://blog.csdn.net/tangcheng_ok/article/details/6857975

좋은 웹페이지 즐겨찾기