第十二章:访问Android服务

一.   创建自己的服务

服务是Android中的一个应用,他在后台运行,不需要与用户有任何交互。如 当使用一个应用时,你希望同时可以在后台播放音乐。这时,在后台播放音乐的代码不需要与用户交互;因此他可以作为一个服务运行。同时,应用不需要提供UI时,服务也是理想的选择

MyService类中实现三个方法:

onBind()使你能将一个Activity绑定到一个服务上

onStartCommand()该方***在显示的使用startService()方法启动服务时被调用。该方法表示服务启动,可以在该方法中编写任何想要为服务执行 的任务

onDestroy() 该方***在显示的使用stopService()方法停止服务时被调用,在该方法中清理服务使用的资源。

二.   在服务和Activity之间建立通信

三.   将Activity与服务绑定

四.   线程的概念


<?xml version="1.0" encoding="utf-8"?>

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:app="http://schemas.android.com/apk/res-auto"

    xmlns:tools="http://schemas.android.com/tools"

    android:id="@+id/activity_main"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    tools:context="com.jfdimarzio.services.MainActivity">



    <Button

        android:text="Start Service"

        android:layout_width="90dp"

        android:layout_height="50dp"

        android:id="@+id/btnStartService"

        app:layout_constraintLeft_toLeftOf="@+id/activity_main"

        app:layout_constraintTop_toTopOf="@+id/activity_main"

        android:layout_marginTop="16dp"

        app:layout_constraintRight_toRightOf="@+id/activity_main"

        app:layout_constraintBottom_toTopOf="@+id/btnStopService"

        android:layout_marginBottom="8dp"

        android:onClick="startService" />


    <Button

        android:text="Stop Service"

        android:layout_width="88dp"

        android:layout_height="48dp"

        android:id="@+id/btnStopService"

        android:onClick="stopService"

        app:layout_constraintLeft_toLeftOf="@+id/activity_main"

        android:layout_marginStart="16dp"

        app:layout_constraintTop_toTopOf="@+id/activity_main"

        app:layout_constraintRight_toRightOf="@+id/activity_main"

        android:layout_marginEnd="16dp"

        app:layout_constraintBottom_toBottomOf="@+id/activity_main" />

</android.support.constraint.ConstraintLayout>


package com.jfdimarzio.services;


import android.content.BroadcastReceiver;

import android.content.ComponentName;

import android.content.Context;

import android.content.Intent;

import android.content.IntentFilter;

import android.content.ServiceConnection;

import android.os.IBinder;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.widget.Toast;


import java.net.MalformedURLException;

import java.net.URL;


public class MainActivity extends AppCompatActivity {

    IntentFilter intentFilter;


    MyService serviceBinder;

    Intent i;

    private ServiceConnection connection = new ServiceConnection() {

        public void onServiceConnected(

                ComponentName className, IBinder service) {

            //—-called when the connection is made—-

            serviceBinder = ((MyService.MyBinder)service).getService();

            try {

                URL[] urls = new URL[] {

                        new URL("http://www.amazon.com/somefiles.pdf"),

                        new URL("http://www.wrox.com/somefiles.pdf"),

                        new URL("http://www.google.com/somefiles.pdf"),

                        new URL("http://www.learn2develop.net/somefiles.pdf")};

                //---assign the URLs to the service through the

                // serviceBinder object---

                serviceBinder.urls = urls;

            } catch (MalformedURLException e) {

                e.printStackTrace();

            }

            startService(i);

        }

        public void onServiceDisconnected(ComponentName className) {

            //---called when the service disconnects---

            serviceBinder = null;

        }

    };

    /** Called when the activity is first created. */

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

    }


    @Override

    public void onResume() {

        super.onResume();

        //---intent to filter for file downloaded intent---

        intentFilter = new IntentFilter();

        intentFilter.addAction("FILE_DOWNLOADED_ACTION");

        //---register the receiver---

        registerReceiver(intentReceiver, intentFilter);

    }


    @Override

    public void onPause() {

        super.onPause();


        //---unregister the receiver---

        unregisterReceiver(intentReceiver);

    }


    public void startService(View view) {

        i = new Intent(MainActivity.this, MyService.class);

        bindService(i, connection, Context.BIND_AUTO_CREATE);


    }


    public void stopService(View view) {


        stopService(new Intent(MainActivity.this, MyIntentService.class));

    }

    private BroadcastReceiver intentReceiver = new BroadcastReceiver() {

        @Override

        public void onReceive(Context context, Intent intent) {

            Toast.makeText(getBaseContext(), "File downloaded!",

            Toast.LENGTH_LONG).show();

        }

    };

}


package com.jfdimarzio.services;



import android.app.IntentService;

import android.content.Intent;

import android.util.Log;

import android.widget.Toast;


import java.net.MalformedURLException;

import java.net.URL;


public class MyIntentService extends IntentService {


    private Thread thread = new Thread();


    public MyIntentService() {

        super("MyIntentServiceName");

    }

    @Override

    protected void onHandleIntent(Intent intent) {

        try {

            int result =

                    DownloadFile(new URL("http://www.amazon.com/somefile.pdf"));

            thread.start();

            Log.d("IntentService", "Downloaded " + result + " bytes");


            //---send a broadcast to inform the activity

            // that the file has been downloaded---

            Intent broadcastIntent = new Intent();

            broadcastIntent.setAction("FILE_DOWNLOADED_ACTION");

            getBaseContext().sendBroadcast(broadcastIntent);


        } catch (MalformedURLException e) {

            e.printStackTrace();

        }

    }

    private int DownloadFile(URL url) {

        try {

            //---simulate taking some time to download a file---

            thread.sleep(5000);

        } catch (InterruptedException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

        return 100;

    }


    @Override

    public void onDestroy() {


        thread.interrupt();


        Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();


        super.onDestroy();

    }


}


package com.jfdimarzio.services;


import android.app.Service;

        import android.content.Intent;

        import android.os.AsyncTask;

import android.os.Binder;

import android.os.IBinder;

        import android.util.Log;

        import android.widget.Toast;


        import java.net.MalformedURLException;

        import java.net.URL;

        import java.util.Timer;

        import java.util.TimerTask;


public class MyService extends Service {

    int counter = 0;

    URL[] urls;

    static final int UPDATE_INTERVAL = 1000;

    private Timer timer = new Timer();

    private final IBinder binder = new MyBinder();

    public class MyBinder extends Binder {

        MyService getService() {

            return MyService.this;

        }

    }

    @Override

    public IBinder onBind(Intent arg0) {

        return binder;

    }

    @Override

    public int onStartCommand(Intent intent, int flags, int startId) {

        // We want this service to continue running until it is explicitly

        // stopped, so return sticky.

        Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();

        new DoBackgroundTask().execute(urls);

        return START_STICKY;

    }


    private void doSomethingRepeatedly() {

        timer.scheduleAtFixedRate(new TimerTask() {

            public void run() {

                Log.d("MyService", String.valueOf(++counter));

            }

        }, 0, UPDATE_INTERVAL);

    }


    private int DownloadFile(URL url) {

        try {

            //---simulate taking some time to download a file---

            Thread.sleep(5000);

        } catch (InterruptedException e) {

            e.printStackTrace();

        }

        //---return an arbitrary number representing

        // the size of the file downloaded---

        return 100;

    }

    private class DoBackgroundTask extends AsyncTask<URL, Integer, Long> {

        protected Long doInBackground(URL... urls) {

            int count = urls.length;

            long totalBytesDownloaded = 0;

            for (int i = 0; i < count; i++) {

                totalBytesDownloaded += DownloadFile(urls[i]);

                //---calculate percentage downloaded and

                // report its progress---

                publishProgress((int) (((i+1) / (float) count) * 100));

            }

            return totalBytesDownloaded;

        }

        protected void onProgressUpdate(Integer... progress) {

            Log.d("Downloading files",

                    String.valueOf(progress[0]) + "% downloaded");

            Toast.makeText(getBaseContext(),

                    String.valueOf(progress[0]) + "% downloaded",

                    Toast.LENGTH_LONG).show();

        }

        protected void onPostExecute(Long result) {

            Toast.makeText(getBaseContext(),

                    "Downloaded " + result + " bytes",

                    Toast.LENGTH_LONG).show();

            stopSelf();

        }

    }


    @Override

    public void onDestroy() {

        super.onDestroy();


        if (timer != null){

            timer.cancel();

        }


        Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();

    }


}


#Android#
全部评论

相关推荐

想干测开的tomca...:让我来压力你!!!: 这份简历看着“技术词堆得满”,实则是“虚胖没干货”,槽点一抓一大把: 1. **项目描述是“技术名词报菜名”,没半分自己的实际价值** 不管是IntelliDoc还是人人探店,全是堆Redis、Elasticsearch、RAG这些时髦词,但你到底干了啥?“基于Redis Bitmap管理分片”是你写了核心逻辑还是只调用了API?“QPS提升至1500”是你独立压测优化的,还是团队成果你蹭着写?全程没“我负责XX模块”“解决了XX具体问题”,纯把技术文档里的术语扒下来凑字数,看着像“知道名词但没实际动手”的实习生抄的。 2. **短项目塞满超纲技术点,可信度直接***** IntelliDoc就干了5个月,又是RAG又是大模型流式响应又是RBAC权限,这堆活儿正经团队分工干都得小半年,你一个后端开发5个月能吃透这么多?明显是把能想到的技术全往里面塞,生怕别人知道你实际只做了个文件上传——这种“技术堆砌式造假”,面试官一眼就能看出水分。 3. **技能栏是“模糊词混子集合”,没半点硬核度** “熟悉HashMap底层”“了解JVM内存模型”——“熟悉”是能手写扩容逻辑?“了解”是能排查GC问题?全是模棱两可的词,既没对应项目里的实践,也没体现深度,等于白写;项目里用了Elasticsearch的KNN检索,技能栏里提都没提具体掌握程度,明显是“用过但不懂”的硬凑。 4. **教育背景和自我评价全是“无效信息垃圾”** GPA前10%这么好的牌,只列“Java程序设计”这种基础课,分布式、微服务这些后端核心课提都不提,白瞎了专业优势;自我评价那堆“积极认真、细心负责”,是从招聘网站抄的模板吧?没有任何和项目挂钩的具体事例,比如“解决过XX bug”“优化过XX性能”,纯废话,看完等于没看。 总结:这简历是“技术名词缝合怪+自我感动式凑数”,看着像“背了后端技术栈名词的应届生”,实则没干货、没重点、没可信度——面试官扫30秒就会丢一边,因为连“你能干嘛”都没说清楚。
点赞 评论 收藏
分享
牛客67381407...:我们学校华为是点击就送的
点赞 评论 收藏
分享
12-24 20:44
武汉大学 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务