Notif用户最喜欢的比赛

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (19)

我想创建曲棍球结果的应用程序。在主页上,用户选择他最喜欢的球队,而不是他在片段Future Matches中看到的 - 他最喜欢的球队的比赛。在此之后,他可以选择他最喜欢的比赛(通过点击比赛)而不是,如果在该比赛中改变得分,则用户获得关于改变得分的通知。但我有问题,因为当我看到未来的比赛,点击比赛后,应用程序下降。我对解决这个问题一无所知。我需要帮助。

public class Future_matches extends Fragment {

    private static Future_matches fragment;
    private int favorite_team_id;
    private SharedPreferences sp;

    private RecyclerView rv_futureMatches;
    //   private FutureMatchesAdapter adapter;
    private List<FutureMatchModel> teams;
    private SharedPreferences.Editor ed;
    List<Thread> listOfActiveThreads;

    private RecyclerView.Adapter<FutureMatchesHolder> adapter;
    private RecyclerView.LayoutManager layoutManager;

    public Future_matches() {
    }

    public static Future_matches newInstance() {
        if (fragment == null)
            fragment = new Future_matches();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        listOfActiveThreads = new ArrayList<>();
        sp = getActivity().getSharedPreferences(Tools.PACKAGE_NAME, Context.MODE_PRIVATE);
        favorite_team_id = sp.getInt(Tools.FAVORITE_TEAM_ID, -1);
        ed = sp.edit();
    }

    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootview = inflater.inflate(R.layout.future_matches, container, false);
        rv_futureMatches = rootview.findViewById(R.id.rv_future_matches);
        RecyclerView.LayoutManager lm = new LinearLayoutManager(getActivity());
        //  rv_futureMatches.setLayoutManager(lm);
        //  rv_futureMatches.setHasFixedSize(true);

        if (favorite_team_id == -1) {
            Toast.makeText(getActivity(), R.string.warning_future_matches_choose_favorite_team, Toast.LENGTH_SHORT).show();
        } else {
            Tools.getApi().getFutureMatches(favorite_team_id, "2018-12-27", "2019-05-12").enqueue(new Callback<JsonObject>() {
                @Override
                public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                    if (response.code() == 200) {
                        teams = JsonTools.convertJsonToFutureMatches(response.body());
                        // JsonObject data = response.body();

                        layoutManager = new LinearLayoutManager(getActivity());
                        layoutManager = new LinearLayoutManager(getContext());


                        //         adapter = new FutureMatchesAdapter(JsonTools.convertJsonToFutureMatches(data), new WeakReference<Context>(getActivity()));


                        adapter = new FutureMatchesAdapter(teams, new WeakReference<Context>(getActivity()), new FutureMatchesAdapter.TeamClickHandler() {
                            @Override
                            public void onClick(int id) {
                                takeCareOfChanges(id);
                            }
                        });

                        rv_futureMatches.setHasFixedSize(true);
                        rv_futureMatches.setLayoutManager(layoutManager);
                        rv_futureMatches.setAdapter(adapter);
                    }
                }

                @Override
                public void onFailure(Call<JsonObject> call, Throwable t) {
                    Toast.makeText(getActivity(), t.getMessage(), Toast.LENGTH_LONG).show();
                }
            });

        }
        return rootview;
    }

    private boolean isItemInList(int id) {
        if (sp.contains(Tools.PREFS_PICKED_GAMES)) {
            Set<String> result = sp.getStringSet(Tools.PREFS_PICKED_GAMES, null);
            if (result.contains(Integer.toString(id))) {
                return true;
            } else {
                return false;
            }
        } else
            return false;

    }

    private void takeCareOfChanges(int id) {
        if (sp.contains(Tools.PREFS_PICKED_GAMES)) {
            Set<String> result = sp.getStringSet(Tools.PREFS_PICKED_GAMES, null);
            if (isItemInList(id)) {
                result.remove(Integer.toString(id));
                ed.putStringSet(Tools.PREFS_PICKED_GAMES, result);
                quitService(id);
            } else {
                result.add(Integer.toString(id));
                ed.putStringSet(Tools.PREFS_PICKED_GAMES, result);
                launchService(id);
            }
        } else {
            Set<String> result = new HashSet<>();
            result.add(Integer.toString(id));
            ed.putStringSet(Tools.PREFS_PICKED_GAMES, result);
            launchService(id);
        }
        ed.apply();
    }

    private void launchService(final int id){
                getActivity().startService(new Intent().putExtra(Tools.INTENT_EXTRA_ID,id));
    }
    private void quitService(int id){
        LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(new Intent().setAction(Tools.INTENT_ACTION_STOP_SERVICE).putExtra(Tools.INTENT_EXTRA_ID,id));
    }
}
public class GameChangeService extends Service {
    private final static String TAG = "GameChangeService";
    private BroadcastReceiver broadcastReceiver;
    private Handler h;
    private SharedPreferences sp;
    Notification notif;
    NotificationManager notifManager;
    private SharedPreferences.Editor ed;
    private Runnable r;
    private int id;

    private String CHANNEL_ID = "ID";
    private int notifId = 1000;


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        sp = getSharedPreferences(Tools.PACKAGE_NAME, Context.MODE_PRIVATE);
        ed = sp.edit();
        notifManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        h = new Handler();
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                stopSelf();
            }
        };
        LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, new IntentFilter(Tools.INTENT_ACTION_STOP_SERVICE));
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        id = intent.getIntExtra(Tools.INTENT_EXTRA_ID, -1);
        if (id == -1) {
            stopSelf();
        } else {
            r = new Runnable() {
                @Override
                public void run() {
                    doStuff(id);
                    h.postDelayed(r, 15000);
                }
            };
            h.post(r);

            return Service.START_STICKY;
        }
        //TOTO TU JE VELMI DISKUTABILNE
        return Service.START_STICKY;
    }

    private void doStuff(final int id) {
        //TODO: Checkni pls ci je boxscore updatovany live alebo nie. Ak je tak ho mozes pouzit v IApiDefinition namiesto live feed
        // JA> V schedule je s gamepk aj online zapas s golmi - staci to pouzit
        ApiTools.getApi().getGame(id).enqueue(new Callback<JsonObject>() {
            @Override
            public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                if (sp.contains(Integer.toString(id))) {
                    int povodnyPocetGolovVZapase = sp.getInt(Integer.toString(id), 0);

                    //Z responsu zistit kolko eventov je teraz v zapase, t.j. ci uz zapas zacal.
                    //Dalej zistit ci su tam nejake eventy, ktore maju typ goal alebo ENDGAME (asi).
                    //AK sa zmenil pocet golov, tak posli notifikaciu ze padol gol aj s novym stavom

                    JsonObject data = response.body();
                    //pouzijem lastmatchmodel, aj ked to nie je pre toto robene, ale data mi stacia aj z neho
                    //List<LastMatchModel> livezapasy = new ArrayList<>();
                    //vytiahnem si zoznam
                    JsonArray zoznamZapasovZJsonu = data.get("dates").getAsJsonArray();

                    for (int i = 0; i < zoznamZapasovZJsonu.size(); i++) {
                        //pouzijem lastmatchmodel, aj ked to nie je pre toto robene, ale data mi stacia aj z neho
                        LastMatchModel novyZapas = new LastMatchModel();
                        JsonObject zapasDate = zoznamZapasovZJsonu.get(i).getAsJsonObject();

                        JsonArray games = zapasDate.get("games").getAsJsonArray();
                        if (games.size() >= 1) {
                            JsonObject teams = games.get(0).getAsJsonObject().get("teams").getAsJsonObject();

                            int golyHostia = teams.get("away").getAsJsonObject().get("score").getAsInt();
                            String timHostia = teams.get("away").getAsJsonObject().get("team").getAsJsonObject().get("name").getAsString();

                            int golyDomaci = teams.get("home").getAsJsonObject().get("score").getAsInt();
                            String timDomaci = teams.get("home").getAsJsonObject().get("team").getAsJsonObject().get("name").getAsString();

                            if (golyDomaci + golyHostia != povodnyPocetGolovVZapase) {

                                Intent intent = new Intent(GameChangeService.this, MatchNotification.class);
                                PendingIntent pendingIntent = PendingIntent.getActivity(GameChangeService.this, 0, intent, 0);
                                createNotificationChannel();


                                final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(GameChangeService.this, CHANNEL_ID)
                                        .setSmallIcon(R.mipmap.ic_launcher)
                                        .setContentTitle("GOAL")
                                        .setContentText(timDomaci + golyDomaci + " vs " + golyHostia + timHostia)
                                        .setContentIntent(pendingIntent)
                                        .setPriority(NotificationCompat.PRIORITY_DEFAULT);

                                NotificationManagerCompat nm = NotificationManagerCompat.from(GameChangeService.this);
                                nm.notify(notifId, mBuilder.build());


                            }
                        }
                    }


                } else {
                    int povodnyPocetEventovVZapase = 0;
                    //Z responsu zistit kolko eventov je teraz v zapase, t.j. ci uz zapas zacal.
                    //Dalej zistit ci su tam nejake eventy, ktore maju typ goal alebo ENDGAME (asi).
                    //AK sa zmenil pocet golov, tak posli notifikaciu ze padol gol aj s novym stavom


                }
            }

            @Override
            public void onFailure(Call<JsonObject> call, Throwable t) {
                Log.e(GameChangeService.TAG, "Nebavi to ");
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (h != null)
            h.removeCallbacks(r);
        LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver);
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = "Name of the channel";
            String description = "Description of the channel";
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
            channel.setDescription(description);
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }
}

在Android Studio中运行通知错误

要么

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.luky.nhlvysledky, PID: 23251
    java.lang.IllegalArgumentException: Service Intent must be explicit: Intent { (has extras) }
        at android.app.ContextImpl.validateServiceIntent(ContextImpl.java:1519)
        at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1560)
        at android.app.ContextImpl.startService(ContextImpl.java:1532)
        at android.content.ContextWrapper.startService(ContextWrapper.java:664)
        at com.example.luky.nhlvysledky.Future_matches.launchService(Future_matches.java:148)
        at com.example.luky.nhlvysledky.Future_matches.takeCareOfChanges(Future_matches.java:142)
        at com.example.luky.nhlvysledky.Future_matches.access$300(Future_matches.java:33)
        at com.example.luky.nhlvysledky.Future_matches$1$1.onClick(Future_matches.java:93)
        at com.example.luky.nhlvysledky.RecycleView.FutureMatchesHolder$1.onClick(FutureMatchesHolder.java:46)
        at android.view.View.performClick(View.java:6597)
        at android.view.View.performClickInternal(View.java:6574)
        at android.view.View.access$3100(View.java:778)
        at android.view.View$PerformClick.run(View.java:25885)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
提问于
用户回答回答于

您需要在intent中明确定义您想启动的服务。

getActivity().startService(new Intent(getActivity(), GameChangeService.class).putExtra(Tools.INTENT_EXTRA_ID,id));

您还需要在AndroidManifest.xml中定义服务。

<service android:enabled="true" android:name=".GameChangeService" />

热门问答

cos.sliceUploadFile支持断点续传吗?

如果用的是 cos-js-sdk,那么 cos.restartTask 是会断点续传的,用法没有问题。 PS: sdk 使用可以参考 demo.js https://github.com/tencentyun/cos-js-sdk-v5/blob/master/demo/demo...... 展开详请

使用独立H5接入人脸核身,在微信浏览器拍摄视频按钮无法点击?

旺仔小小鹿

社区 · 运营 (已认证)

Less is more
推荐

使用iframe会有问题 ,微信有限制,不允许使用iframe调用jsapi摄像头 ,微信里,不能用iframe

ios应该都不行的,安卓需要看是什么浏览器。

云服务器中ping不可达,请教一下如何恢复?

推荐已采纳
本地主机 ping 不通实例可能由以下问题导致: 目标服务器的设置不正确 域名没有正确解析 链路故障 在确保本地网络正常的前提下(即您可以正常 ping 通其他网站),可根据以下操作进行排查: 检查实例是否配置公网 IP 检查安全组设置 检查系统设置 检查域名是否备案 检查域名解...... 展开详请

为什么加固之后生成四个文件?

腾讯云@移动安全

腾讯 · 移动开发工程师 (已认证)

腾讯云移动安全前端开发
推荐

选择最后一个_legu_aligned_signed.apk 文件,这个是加固并已重签名的文件。

COS Javascript SDK 为何没有 getService 方法?

因为 getService 请求的是 service.cos.myqcloud.com 或 cos.<Region>.myqcloud.com 域名,前端直接请求会导致跨域问题。 前端 js sdk 直接请求 bucket/object 相关的接口,虽然也会跨域,但你可以在 你...... 展开详请

iot设备通过mqtt协议连接,没有办法设置clientid?

DylanRichard

腾讯 · 产品经理 (已认证)

万物互联的时代,欢迎来到IoT的世界
推荐

物联网接入层有设备互踢的逻辑,如果是用同一个设备 ID 在不同地方登录,会导致其中一方被另一方踢下线。因此发现设备一直上下线时,需要确认是否有不同的人或者多线程在使用同一个设备 ID 执行登录操作。

所属标签

扫码关注云+社区

领取腾讯云代金券