2019-08-19Service及练习

Service介绍

1.Service,服务,是四大组件之一, 和Activity 非常相似, 一般运行在后台, 没有用户界面, 可执行的程序
2.Activity 和 Service的区别
(1)不同点:
Activity : 可以和用户交互, 页面可见
Service : 后台运行, 没有界面
(2)相同点:
在清单文件中注册, 都有自己的生命周期

Service特点

service在后台运行,不用与用户进行交互。即使应用退出,服务也不会停止。
当应用进程被杀死时,服务便会停止.
service运行在主线程中,当需要执行耗时操作的时候,需要在服务中创建子线程完成
service 的用途:播放音乐;后台下载大文件等

练习:使用IntentService网络请求json串,将json串使用广播发送给activity界面

Activity代码+MyReceive类

public class MainActivity extends AppCompatActivity {
    private MyIntentService myIntentService;
    private Intent intent;
    private MyReceive myReceive;
    private TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView=findViewById(R.id.TextView);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //注册广播
                IntentFilter intentFilter = new IntentFilter();
                intentFilter.addAction("com.bawei.intentservice");
                myReceive=new MyReceive();
                registerReceiver(myReceive,intentFilter);

                //开启服务
                Intent intent = new Intent(MainActivity.this, MyIntentService.class);
                startService(intent);
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myReceive);
        stopService(intent);
    }
}
    class MyReceive extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if("com.bawei.intentservice".equals(action)){
                Bundle bundle = intent.getExtras();
                String json = bundle.getString("json", "");
                //展示数据
                Toast.makeText(context, ""+json, Toast.LENGTH_SHORT).show();
            }
        }
    }

服务类

public class MyIntentService extends IntentService {
    //必须提供无参数构造,不然清单文件中注册报错
    public MyIntentService() {
        super("MyIntentService");
    }

    public MyIntentService(String name) {
        super(name);
    }
    //将所有耗时操作都在该方法中完成,相当于开启线程
    @Override
    protected void onHandleIntent(Intent intent) {
        StringBuffer sb = new StringBuffer();
        HttpURLConnection connection=null;
        InputStream inputStream=null;

        try {
            URL url = new URL("http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&page=1");
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            if(connection.getResponseCode()==200){
                inputStream = connection.getInputStream();
                byte [] byt=new byte[1024];
                int len=0;
                while((len=inputStream.read(byt))!=-1){
                    sb.append(new String(byt,0,len));
                }
                //向Activity或Fragment发送json串
                Intent intent1 = new Intent();
                intent1.setAction("com.bawei.intentservice");
                Bundle bundle = new Bundle();
                bundle.putString("json",sb.toString());
                intent1.putExtras(bundle);
                sendBroadcast(intent1);

                inputStream.close();
                connection.disconnect();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

XML布局文件代码

<RelativeLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/TextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:layout_centerInParent="true" />

</RelativeLayout>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。