문제

나는 정말 쉬운 일을하려고 노력하고 있지만 그것은 나를 미치게 만들고 있습니다. 위젯의 구성 활동과 같은 홈 화면 위젯이 눌렀을 때 활동을 시작하려고합니다. 나는 Android 개발자 웹 사이트의 튜토리얼과 비공식 튜토리얼의 Word The Word를 따랐다고 생각하지만 효과가 없으므로 중요한 것을 놓치고 있어야합니다.

코드는 다음과 같습니다.

public class VolumeChangerWidget extends AppWidgetProvider {

public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds){
    final int N = appWidgetIds.length;

    for (int i=0; i < N; i++) {
        int appWidgetId = appWidgetIds[i];

        Log.d("Steve", "Running for appWidgetId " + appWidgetId);
        Toast.makeText(context, "Hello from onUpdate", Toast.LENGTH_SHORT);
        Log.d("Steve", "After the toast line");

        Intent intent = new Intent(context, WidgetTest.class);

        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
        views.setOnClickPendingIntent(R.id.button, pendingIntent);

        appWidgetManager.updateAppWidget(appWidgetId, views);
    }
}

}

위젯을 홈 화면에 추가 할 때 로그 캣은 토스트가 아닌 두 개의 디버깅 라인을 보여줍니다. (어떤 아이디어라도 그렇지 않습니까?) 그러나, 더 많은 vexing은 내가 보드 인트와 관련된 상태에서 버튼을 클릭하면 아무 일도 일어나지 않는다는 것입니다. 주요 활동 내에서 의도를 설정하면 잘 시작되기 때문에 "위젯 테스트"활동이 실행될 수 있다는 것을 알고 있습니다.

중요한 경우 Android Manifest 파일이 있습니다.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.steve"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".Volume_Change_Program"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name=".WidgetTest"
              android:label="@string/hello">
        <intent_filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent_filter>
    </activity>

    <receiver android:name=".VolumeChangerWidget" >
        <intent-filter>
            <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
        </intent-filter>
        <meta-data  android:name="android.appwidget.provider"
                    android:resource="@xml/volume_changer_info" />
    </receiver>

</application>
<uses-sdk android:minSdkVersion="3" />

결함이 어디에 있는지 테스트하는 방법이 있습니까? 즉, 버튼이 보드 인디언트에 제대로 연결되지 않았거나 보드 인디언트 또는 의도가 WidgetTest.class 등을 찾지 못한다는 결함입니까?

도와 주셔서 대단히 감사합니다!

스티브

도움이 되었습니까?

해결책

나는 같은 문제를 겪고 있었다. 수정 사항은 AppWidget 관리자를 통해 업데이트를 호출하는 것임을 발견했습니다. 다음은 OneNabled에서이를 수행하는 방법의 예입니다. 장치가 클릭 의도에 전원을 공급할 때 클릭 의도도 세분화되도록 OneNabled 및 Onupdated에서 수행 해야하는 것으로 보입니다.

@Override 
    public void onEnabled(Context context) {  
          //Log.v("toggle_widget","Enabled is being called"); 

          AppWidgetManager mgr = AppWidgetManager.getInstance(context); 
          //retrieve a ref to the manager so we can pass a view update 

          Intent i = new Intent(); 
          i.setClassName("yourdoman.yourpackage", "yourdomain.yourpackage.yourclass"); 
          PendingIntent myPI = PendingIntent.getService(context, 0, i, 0); 
          //intent to start service 

        // Get the layout for the App Widget 
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.togglelayout); 

        //attach the click listener for the service start command intent 
        views.setOnClickPendingIntent(R.id.toggleButton, myPI); 

        //define the componenet for self 
        ComponentName comp = new ComponentName(context.getPackageName(), ToggleWidget.class.getName()); 

        //tell the manager to update all instances of the toggle widget with the click listener 
        mgr.updateAppWidget(comp, views); 
} 

다른 팁

이것을 가져옵니다 방법 죽음에서 돌아 왔지만 비슷한 문제가 있었는데 마침내 그것을 해결했다고 생각합니다 ... 당신처럼, 나는 Remoteview에 첨부 한 보드 인디언트가있었습니다. 때때로 그것은 작동 할 것이고 때로는 실패 할 것입니다. 그것은 나를 미치게했다.

pendingintent.getActivty ()의 툴팁에서 찾은 것은 다음과 같습니다.

활동은 기존 활동의 컨텍스트 외부에서 시작되므로 의도의 의도를 사용해야합니다.

그래서 나는 다음을 덧붙였다.

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

내가 지금까지 본 코드는 이것을 수행하지 않지만 내 문제를 해결했습니다. 설정 활동은 이제 안정적으로 시작됩니다.

잘 작동하는 전체 코드 ...

Intent intent = new Intent(context, Settings.class);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appId);  // Identifies the particular widget...
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Make the pending intent unique...
intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
PendingIntent pendIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.wwwidget);
views.setOnClickPendingIntent(R.id.widget, pendIntent);
appWidgetManager.updateAppWidget(appId,views);

이것은 정보, With Widget 샘플, 그리고 여기 튜토리얼

       Intent intent = new Intent(Intent.ACTION_MAIN, null);
      intent.addCategory(Intent.CATEGORY_LAUNCHER);
      // first param is app package name, second is package.class of the main activity
      ComponentName cn = new ComponentName("com....","com...MainActivity");
      intent.setComponent(cn);
      intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
      PendingIntent myPI = PendingIntent.getActivity(context, 0, intent, 0); 

    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_word); 


    views.setOnClickPendingIntent(R.id.widget, myPI); 

    AppWidgetManager mgr = AppWidgetManager.getInstance(context); 
    mgr.updateAppWidget(comp, views); 

토스트가 표시되지 않는 문제는 쉽습니다. 당신은 show ()를 부르지 않습니다.

Toast.makeText(context, "Hello from onUpdate", Toast.LENGTH_SHORT).show();

대신에

Toast.makeText(context, "Hello from onUpdate", Toast.LENGTH_SHORT);

스티브,

문제를 찾았습니까? 나는 위젯을 사용하고 oneenabled 트릭없이 나에게 잘 작동합니다. 나는 그것이 당신을위한 이유에 관심이 있습니다.

내 추측 : 원래 코드에서 시도하십시오

PendingIntent pendingIntent = PendingIntent.getActivity(context, 1, intent, 0);

대신에

PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

위젯을 홈 화면에 추가 할 때 로그 캣은 토스트가 아닌 두 개의 디버깅 라인을 보여줍니다. (어떤 아이디어도 그렇지 않습니까?)

출시를 시도하지 마십시오 Toasts a BroadcastReceiver.

결함이 어디에 있는지 테스트하는 방법이 있습니까?

Logcat을보십시오 adb logcat, 일식의 DDMS 또는 DDMS 관점. 주어진과 일치하는 활동을 찾지 않는 것에 대한 경고를 찾을 수 있습니다. Intent.

나는 명백한 문제가 없다. 당신은 엿보기를 원할 수도 있습니다 내 책 예 중 하나 그것이 당신에게 효과가 있는지, 그리고 그것이 당신에게 어떤 일이 일어날 지에 대한 아이디어를 줄 것인지 확인하십시오.

res/xml/volume_changer_info.xml에서 구성 활동을 정의해야합니다. 이 태그를 추가하고 구성 활동에 대한 자격을 갖춘 경로를 제공하십시오.

안드로이드 : configure = ""


예를 들어

<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:minWidth="200dip"
    android:minHeight="100dip"
    android:updatePeriodMillis="60000"
    android:initialLayout="@layout/widget_loading"
    android:configure = "org.raza.ConfigureWidgetActivity"/>

나는이 실이 고대라는 것을 알고 있지만 ... 다른 답변은 당신의 불타는 토스트 문제를 묘사합니다. 팝업 활동이 터치로 시작되지 않는 이유에 대해서는 onupdate () 메소드를 시작하고 호출하려면 "업데이트"작업을 활성화해야 할 수도 있습니다. 이를 위해 나는 당신이 다음과 같은 "appwidget_update"동작을 추가해야한다고 생각합니다.

<activity android:name=".WidgetTest" android:label="@string/hello">
    <intent_filter>
        <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
        <action android:name="android.intent.action.MAIN"/>
        <category android:name="android.intent.category.LAUNCHER"/>
    </intent_filter>
</activity>

마찬가지로 해당 메소드를 무시하려는 경우 APPWIDGET_ENABLED 및 APPWIDGET_DISABLED 작업을 추가하십시오.

호출하려는 재정의 방법을 선언 해야하는 매우 특이한 API 인 것 같습니다. 부모의 사용자 정의 버전을받는 일반적인 방법은 부모 버전을 간단히 재정의/구현하는 것입니다. 어쩌면이 이상한 패턴에 대한 좋은 이유가 있지만, 이전에 본 자바 패턴은 아닙니다. 그러므로 나는 그것이 많은 앱 위젯 작성자를 여행 할 가능성이 있다고 생각합니다. 앱 위젯 이이 메커니즘없이 충분히 혼란스럽지 않은 것처럼.

한 가지 추가 요점 : 위젯에서 호출되는 활동은 매니페스트 파일에서 선언해야합니다. 예외는 버리지 않고 아무 일도 일어나지 않는 것처럼 보입니다 ...

나는 이번 밤 밤에 (아주 어리석게) 싸우고있는 것처럼 여기 어딘가에 이것을 주목하고 싶었다. 기본적으로 나는 모든 의도 코드를 올바르게 수행했지만 아무것도 시작되지 않았습니다.

문제는 실수로 이와 같은 전화를 받았다는 것입니다.

super.onUpdate(context, appWidgetManager, appWidgetIds);

재정의 된 OnupDate () 함수의 끝에

당신을 확인하십시오 하지 마라 설정 한 모든 보류 의도를 정리할 수 있으므로이 호출을 받으십시오!

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top