Andriod编程权威指南(第28章 后台服务)

本文介绍了如何在Android中使用IntentService进行后台轮询检查网络状态,并获取最新结果。通过设置AlarmManager实现定时任务,当有新结果时通过Notification展示提醒。同时,文章还展示了如何添加和切换服务开关以及处理权限请求。
摘要由CSDN通过智能技术生成
一、创建IntentService

首先使用IntentService创建服务。IntentService并不是Android唯一的可用服务,但是最常用的,创建一个名为pollService的IntentService子类,它就是用来轮询搜索结果的服务。
1.创建PollService(PollService.java)

    private static final String TAG = "PollService";
    public static Intent newIntent(Context context) {
        return new Intent(context, PollService.class);
    }
    public PollService() {
        super(TAG);
    }
    @Override
    protected void onHandleIntent(Intent intent) {
        Log.i(TAG,"Received an intent:" +intent)
    }

在这里插入图片描述
2.在manifes配置文件中添加服务(AndroidManifest.xml)

 <service android:name=".PollService" />

在这里插入图片描述
3.添加服务启动代码(PhotoGalleryFragment.java)

        Intent i = pollService.newIntent(getActivity());
        getActivity().startService();

在这里插入图片描述

二、服务的作用

1.检查后台的可用性(PollService.java)

        if (!isNetworkAvailableAndConnected()) {
            return;
        }
    private boolean isNetworkAvailableAndConnected() {
        ConnectivityManager cm =
                (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);

        boolean isNetworkAvailable = cm.getActiveNetworkInfo() != null;
        boolean isNetworkConnected = isNetworkAvailable &&
                cm.getActiveNetworkInfo().isConnected();

        return isNetworkConnected;
    }

在这里插入图片描述
在这里插入图片描述
2.获取网络状态权限(AndroidManifest.xml)

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

在这里插入图片描述

三、查找最新返回结果

1.添加存储图片ID的preference常量(QueryPreferences.java)

 private static final String PREF_LAST_RESULT_ID = "lastResultId";
 public static String getLastResultId(Context context) {
        return PreferenceManager.getDefaultSharedPreferences(context)
                .getString(PREF_LAST_RESULT_ID, null);
    }

    public static void setLastResultId(Context context, String lastResultId) {
        PreferenceManager.getDefaultSharedPreferences(context)
                .edit()
                .putString(PREF_LAST_RESULT_ID, lastResultId)
                .apply();

在这里插入图片描述
在这里插入图片描述
2.检查最新返回结果(PollService.java)

        String query = QueryPreferences.getStoredQuery(this);
        String lastResultId = QueryPreferences.getLastResultId(this);
        List<GalleryItem> items;

        if (query == null) {
            items = new FlickrFetchr().fetchRecentPhotos();
        } else {
            items = new FlickrFetchr().searchPhotos(query);
        }

        if (items.size() == 0) {
            return;
        }

        String resultId = items.get(0).getId();
        if (resultId.equals(lastResultId)) {
            Log.i(TAG, "Got an old result: " + resultId);
        } else {
            Log.i(TAG, "Got a new result: " + resultId);
            QueryPreferences.setLastResultId(this,resultId);

在这里插入图片描述

四、使用AlarmManager延迟运行服务

1.添加定时方法(PollService.java)

    //Set interval to 1 minute
    private static final long POLL_INTERVAL_MS = TimeUnit.MINUTES.toMillis(1);
    public static void setServiceAlarm(Context context, boolean isOn) {
        Intent i = PollService.newIntent(context);
        PendingIntent pi = PendingIntent.getService(
                context, 0, i, 0);

        AlarmManager alarmManager = (AlarmManager)
                context.getSystemService(Context.ALARM_SERVICE);

        if (isOn) {
            alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME,
                    SystemClock.elapsedRealtime(), POLL_INTERVAL_MS, pi);
        } else {
            alarmManager.cancel(pi);
            pi.cancel();
        }

在这里插入图片描述
在这里插入图片描述
2.添加定时器启动代码(PhotoGalleryFragment.java)

PollService.setServiceAlarm(getActivity(),true);

在这里插入图片描述
3.添加isServiceAlarmOn方法(PollService.java)

    public static boolean isServiceAlarmOn(Context context) {
        Intent i = PollService.newIntent(context);
        PendingIntent pi = PendingIntent
                .getService(context, 0, i, PendingIntent.FLAG_NO_CREATE);
        return pi != null;
    }

在这里插入图片描述
4.添加服务开关(menu/fragment_photo_gallery.xml)

    <item android:id="@+id/menu_item_toggle_polling"
          android:title="@string/start_polling"
          app:showAsAction="ifRoom" />

在这里插入图片描述
5.添加polling字符串资源(res/values/strings.xml)

    <string name="start_polling">Start polling</string>
    <string name="stop_polling">Stop polling</string>
    <string name="new_pictures_title">New PhotoGallery Pictures</string>
    <string name="new_pictures_text">You have new pictures in PhotoGallery.</string>

在这里插入图片描述
6.菜单项切换实现(PhotoGalleryFragment.java)

            case R.id.menu_item_toggle_polling:
                boolean shouldStartAlarm = !PollService.isServiceAlarmOn(getActivity());
                PollService.setServiceAlarm(getActivity(), shouldStartAlarm);
                getActivity().invalidateOptionsMenu();
                return true;

在这里插入图片描述
7.菜单项切换(PhotoGalleryFragment.java)

 MenuItem toggleItem = menu.findItem(R.id.menu_item_toggle_polling);
        if (PollService.isServiceAlarmOn(getActivity())) {
            toggleItem.setTitle(R.string.stop_polling);
        } else {
            toggleItem.setTitle(R.string.start_polling);

在这里插入图片描述
8.让选项菜单失效(PhotoGalleryFragment.java)

getActivity().invalidateOptionsMenu();

在这里插入图片描述

五、通知信息

1.添加newIntent静态方法(PhotoGalleryActivity.java)

    public static Intent newIntent(Context context) {
        return new Intent(context, PhotoGalleryActivity.class);
    }

在这里插入图片描述
2.添加通知信息(PollService.java)

 Resources resources = getResources();
            Intent i = PhotoGalleryActivity.newIntent(this);
            PendingIntent pi = PendingIntent
                    .getActivity(this, 0, i, 0);

            Notification notification = new NotificationCompat.Builder(this)
                    .setTicker(resources.getString(R.string.new_pictures_title))
                    .setSmallIcon(android.R.drawable.ic_menu_report_image)
                    .setContentTitle(resources.getString(R.string.new_pictures_title))
                    .setContentText(resources.getString(R.string.new_pictures_text))
                    .setContentIntent(pi)
                    .setAutoCancel(true)
                    .build();

            NotificationManagerCompat notificationManager = 
                    NotificationManagerCompat.from(this);
            notificationManager.notify(0, notification);
        }

在这里插入图片描述
3.使用更为合理的定时器常量(PollService.java)

 private static final long POLL_INTERVAL_MS = TimeUnit.MINUTES.toMillis(15);

在这里插入图片描述

六、测试

由于没有秘钥,所以不能显示图片,得自己申请一个,放入代码中

在这里插入图片描述
申请秘钥之后的结果
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值