Android <8中Android TV的建议

问题描述

我坚持建议的实施(对于Android https://developer.android.com/training/tv/discovery/recommendations-row

似乎一切都已完成,但服务甚至没有启动。

我已经在清单中完成了下一个操作:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />    
<service
        android:name=".additional.androidTV.UpdateRecommendationsService"
        android:enabled="true" />

    <receiver android:name=".additional.androidTV.BootupActivity"
        android:enabled="true"
        android:exported="false">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"/>
        </intent-filter>
    </receiver>

我的UpdateRecommendationsService类:

public class UpdateRecommendationsService extends IntentService {
    private static final String TAG = "UpdateRecommendationsSe";
    private static final int MAX_RECOMMENDATIONS = 3;

    public UpdateRecommendationsService() {
        super("RecommendationService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.d(TAG,"Updating recommendation cards");
        HashMap<String,List<POJOMovie>> recommendations = new HashMap<>();
        if (recommendations == null) return;

        int count = 0;

        try {
            RecommendationBuilder builder = new RecommendationBuilder()
                    .setContext(getApplicationContext())
                    .setSmallIcon(R.drawable.gotposter);

            for (Map.Entry<String,List<POJOMovie>> entry : recommendations.entrySet()) {
                for (POJOMovie movie : entry.getValue()) {
                    Log.d(TAG,"Recommendation - " + movie.getTitle());

                    builder.setBackground("")
                            .setId(count + 1)
                            .setPriority(MAX_RECOMMENDATIONS - count)
                            .setTitle("test Title")
                            .setDescription("test Description")
//                            .setimage(movie.getPoster())
                            .setIntent(buildPendingIntent(movie))
                            .build();

                    if (++count >= MAX_RECOMMENDATIONS) {
                        break;
                    }
                }
                if (++count >= MAX_RECOMMENDATIONS) {
                    break;
                }
            }
        } catch (IOException e) {
            Log.e(TAG,"Unable to update recommendation",e);
        }
    }

    private PendingIntent buildPendingIntent(POJOMovie movie) {
        Intent detailsIntent = new Intent(this,MainActivity.class);
//        detailsIntent.putExtra("POJOMovie",movie);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(MainActivity.class);
        stackBuilder.addNextIntent(detailsIntent);
        // Ensure a unique PendingIntents,otherwise all
        // recommendations end up with the same PendingIntent
        detailsIntent.setAction(movie.getId());


        PendingIntent pendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);

        return pendingIntent;
    }
}

RecommendationBuilder类:

public class RecommendationBuilder {
    private static final String TAG = "RecommendationBuilder";
    private static final String BACKGROUND_URI_PREFIX = "content://com.example.android.tvleanback.recommendation/";
    private Context mContext;

    private int mId;
    private int mPriority;
    private int mSmallIcon;
    String mTitle;
    String mDescription;
    String mImageUri;
    String mBackgroundUri;
    private PendingIntent mIntent;
    private notificationmanager mnotificationmanager;

    private int mProgress = -1;

    public RecommendationBuilder() {
    }

    public RecommendationBuilder setId(int id) {
        mId = id;
        return this;
    }

    public RecommendationBuilder setContext(Context context) {
        mContext = context;
        return this;
    }

    public RecommendationBuilder setSmallIcon(int resourceId) {
        mSmallIcon = resourceId;
        return this;
    }

    public RecommendationBuilder setPriority(int priority) {
        mPriority = priority;
        return this;
    }

    public RecommendationBuilder setIntent(PendingIntent intent) {
        mIntent = intent;
        return this;
    }

    public RecommendationBuilder setTitle(String title) {
        mTitle = title;
        return this;
    }

    public RecommendationBuilder setDescription(String description) {
        mDescription = description;
        return this;
    }

    public RecommendationBuilder setimage(String uri) {
        mImageUri = uri;
        return this;
    }

    public RecommendationBuilder setBackground(String uri) {
        mBackgroundUri = uri;
        return this;
    }

    public Notification build() throws IOException {

        if (mnotificationmanager == null) {
            mnotificationmanager = (notificationmanager) mContext
                    .getSystemService(Context.NOTIFICATION_SERVICE);
        }

        Bundle extras = new Bundle();

        Notification notification = new NotificationCompat.BigPictureStyle(
                new NotificationCompat.Builder(mContext)
                        .setContentTitle("test Title2")
                        .setContentText("test Description2")
                        .setPriority(mPriority)
                        .setLocalOnly(true)
                        .setongoing(true)
                        .setColor(mContext.getResources().getColor(R.color.red))
                        .setCategory(Notification.CATEGORY_RECOMMENDATION)
//                        .setLargeIcon(R.drawable.gotposter)
                        .setSmallIcon(mSmallIcon)
                        .setContentIntent(mIntent)
                        .setExtras(extras))
                .build();
        mnotificationmanager.notify(mId,notification);
        mnotificationmanager = null;

        return notification;
    }

}

和BootupActivity:

public class BootupActivity extends broadcastReceiver {
    private static final String TAG = "BootupActivity";

    private static final long INITIAL_DELAY = 5000;

    @Override
    public void onReceive(Context context,Intent intent) {
        Log.d(TAG,"BootupActivity initiated");
        if (android.os.Build.VERSION.SDK_INT <= Build.VERSION_CODES.N_MR1) {
            if (Objects.requireNonNull(intent.getAction()).endsWith(Intent.ACTION_BOOT_COMPLETED)) {
                scheduleRecommendationUpdate(context);
            }
        } else{
            Log.d(TAG,"other service for higher API started");
        }
    }

    private void scheduleRecommendationUpdate(Context context) {
        Log.d(TAG,"Scheduling recommendations update");

        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent recommendationIntent = new Intent(context,UpdateRecommendationsService.class);
        PendingIntent alarmIntent = PendingIntent.getService(context,recommendationIntent,0);

        alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,INITIAL_DELAY,//                AlarmManager.INTERVAL_HALF_HOUR,AlarmManager.INTERVAL_FIFTEEN_MINUTES,alarmIntent);
    }.
}

据我了解,当应用启动时,服务也应自动启动。

我已经为此类中的每一行设置了调试点,但没有任何反应。我的代码有什么问题?我忘了清单上的东西吗?

UPD 21.09.2020 :很遗憾,仍在寻找答案。

解决方法

似乎您的BroadcastReceiver设置为不导出,这意味着它无法从具有不同用户ID的任何内容(如果您未在清单中明确设置,则仅表示自身)接收消息。如果您设置exported = true,则应该使您的接收器能够获得启动完成消息。请注意,在安装该应用程序后,您必须至少运行一次该应用程序,才能接收广播。

作为旁注,由于“活动”在Android中是非常具体的事情,因此建议您不要将您的BroadcastReceiver称为“ BootupActivity”。诸如BootupReceiver之类的东西更加清晰。