Android进阶篇Service和广播

项目中我们经常会碰到这种情况,开启一个后台Service进行网络请求。

当满足我们的条件发送一个广播,通过广播来改变UI。

首先:

我们应该注册Service和广播:

mainfest.xml:

        <!--Service服务-->
        <service android:enabled="true" android:name=".service.MyService">
            <intent-filter>
            <action android:name="org.allin.android.musicService" />
            </intent-filter>
        </service>

开启Service:

        Intent intent = new Intent("org.allin.android.musicService");
        startService(intent);

注册广播:

        receiver = new NotificationReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("org.allin.android.receiver");
        registerReceiver(receiver, filter);//注册Broadcast Receiver 

在Activity的onDestroy方法里卸载广播:

unregisterReceiver(receiver);

MyService类通过开启一个计时器进行网络请求,当满足条件的时候发送广播:

public class MyService extends Service{
    private static final String TAG = MyService.class.getSimpleName();
    private static final int PERION = 1000*60*30;

    private PreferencesHelper mHelper;
    private String sid;
    private String token;
    private String lastDate = "";
    
    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        LogUtil.info(TAG, "-------onBind-------");
        return null;
    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        LogUtil.info(TAG, "-------onCreate-------");
        super.onCreate();
        
        initData();
        
        Timer timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            
            @Override
            public void run() {
                // TODO Auto-generated method stub
                try {
                    Messages messages = DataCommple.getInstance().getMessage(token,sid,lastDate,MyService.this);
                    if(messages.getResult().equals("0")){
                        List<Message> mMessages = messages.getMessages();
                        if(mMessages.size() != 0){
                            Bundle bundle = new Bundle();
                            bundle.putParcelable("message", messages);
                            Intent intent = new Intent("org.allin.android.receiver");
                            intent.putExtras(bundle);
                            sendBroadcast(intent);
                        }
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
            }
        };
        timer.schedule(timerTask, 0, PERION);
    }
    
    private void initData(){
        mHelper = new PreferencesHelper(this, PreferencesHelper.HOMESCHOOL);
        token = mHelper.getString(PreferencesHelper.TOKEN, "");
        sid = mHelper.getString(PreferencesHelper.SID, "");
    }

    @Override
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub
        LogUtil.info(TAG, "-------onStart-------");
        super.onStart(intent, startId);
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        LogUtil.info(TAG, "-------onDestroy-------");
        super.onDestroy();
    }
}

广播接收类:(Notification通知栏提醒)

public class NotificationReceiver extends BroadcastReceiver {
    private static final String TAG = NotificationReceiver.class.getSimpleName();
    
    private NotificationManager manager;
    private Notification notification;

    private static final int NOTIFICATION_ID = 0x12;
    private Messages entity;
    
    @Override
    public void onReceive(Context context, Intent intent) {
        LogUtil.info(TAG, "---------onReceive-------");
        initNotification(context);
        
        entity = (Messages) intent.getParcelableExtra("message");
        Bundle bundle = new Bundle();
        bundle.putParcelable("message", entity);
        
        /**
         * 根据FuncitonId来进行跳转
         */
        Intent mIntent = new Intent(context,TradeNoticeActivity.class);
        mIntent.putExtras(bundle);
        
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, mIntent,0);
        notification.contentIntent = pendingIntent;
        notification.contentView.setTextViewText(R.id.txt_downTitle, "有新消息啦");
        manager.notify(NOTIFICATION_ID, notification);
    }
    
    /**
     * 初始化Notification
     * @param context
     */
    private void initNotification(Context context){
        notification = new Notification(R.drawable.logo, "你有新消息",System.currentTimeMillis());
        manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        notification.defaults |= Notification.DEFAULT_SOUND;
        notification.defaults |= Notification.DEFAULT_VIBRATE;
        notification.audioStreamType = android.media.AudioManager.ADJUST_LOWER;
        notification.contentView = new RemoteViews(context.getPackageName(), R.layout.custom_dialog);;
    }
}
原文地址:https://www.cnblogs.com/gongcb/p/2951752.html