移动开发 \ Android \ service汇总(service模拟后台下载、service刷新UI、service与Activity生命周期关系、service和活动间的通信)

service汇总(service模拟后台下载、service刷新UI、service与Activity生命周期关系、service和活动间的通信)

总点击77
简介:转载请注明出处:http://blog.csdn.net/mr_leixiansheng/article/details/71107083 内容:详细讲解service

转载请注明出处:http://blog.csdn.net/mr_leixiansheng/article/details/71107083


内容:详细讲解service

一、模拟后台下载(所有后台运行情况都相似)

二、service刷新活动UI

三、service和活动间的通信()

四、service和活动生命周期关系


一、模拟后台下载(所有后台运行情况都相似)

二、service刷新活动UI


步骤:

1、新建两个活动,在第二个活动处开启service

2、service中启动下载,并不停发送广播

3、第二个活动重写  BroadcastReceiver 不停接收广播信息,并将接收的信息传递给活动进行UI更新

4、注册活动和service

代码如下:

package com.example.leixiansheng.servicetest2;

import android.content.Intent;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

Button button = (Button) findViewById(R.id.btn);

button.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View view) {

Intent intent = new Intent(MainActivity.this,SecondActivity.class);

startActivity(intent);

}

});

}

@Override

protected void onDestroy() {

super.onDestroy();

Intent intent = new Intent(this,TestService.class);

// bindService() 和活动关联,活动终止,绑定必须在次活动前解绑,否则报错

// startService() 与活动无关联,自行运行。(任何活动都可以终止service)

//退出程序也没有stopService ,service 依旧在运行

//停止service

stopService(intent);

}

}

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

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

android:id="@+id/activity_main"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical"

tools:context="com.example.leixiansheng.servicetest2.MainActivity">

<TextView

android:text="这是活动一"

android:textSize="20dp"

android:layout_width="match_parent"

android:layout_height="wrap_content" />

<Button

android:id="@+id/btn"

android:text="Go to SecondActivity"

android:textAllCaps="false"

android:layout_width="match_parent"

android:layout_height="wrap_content" />

</LinearLayout>

package com.example.leixiansheng.servicetest2;

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.content.IntentFilter;

import android.os.Bundle;

import android.os.Handler;

import android.os.Message;

import android.support.v7.app.AppCompatActivity;

import android.util.Log;

import android.view.View;

import android.widget.Button;

import android.widget.TextView;

/**

* Created by Leixiansheng on 2017/4/25.

*/

public class SecondActivity extends AppCompatActivity {

private Person person;

private Intent intent;

private TextView textView;

private int num;

private final static String MYACTION = "com.leixiansheng.broadcast";

//刷新UI

Handler handler = new Handler() {

@Override

public void handleMessage(Message msg) {

super.handleMessage(msg);

textView.setText("下载进度:" + num + "%");

}

};

/**

* person对象无用,

* 只是为了测试开启service后

* 再次进入时对象是否相同(测试结果:不同)

* @param savedInstanceState

*/

@Override

protected void onCreate( Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.second_layout);

//模拟(每次重新进入对象都不同)

person = new Person();

Log.i("SecondActivity",String.valueOf(person));

textView = (TextView) findViewById(R.id.text_view);

Button button = (Button) findViewById(R.id.start);

button.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View view) {

intent = new Intent(SecondActivity.this,TestService.class);

startService(intent);

person.setContext(SecondActivity.this);

person.getAll();

}

});

}

//接收广播传递的数据

BroadcastReceiver receiver = new BroadcastReceiver() {

@Override

public void onReceive(Context context,Intent intent) {

//判断是否是所需广播

if (MYACTION.equals(intent.getAction())) {

num = intent.getIntExtra("CurrentLoading",0);

Log.e("SecondActivity","get the broadcast from TestService..."+ num);

//发送消息,提醒handler刷新UI

handler.sendMessage(handler.obtainMessage());

}

}

};

//动态注册广播(也可以继承广播,以静态方式注册)

@Override

protected void onResume() {

super.onResume();

IntentFilter filter = new IntentFilter();

filter.addAction(MYACTION);

registerReceiver(receiver,filter);

}

//销毁时必须解绑

@Override

protected void onDestroy() {

super.onDestroy();

Log.i("MyBroadcastReceiver","unregister the broadcast receiver...");

unregisterReceiver(receiver);

// stopService(intent);

}

}

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:orientation="vertical" android:layout_width="match_parent"

android:layout_height="match_parent">

<TextView

android:id="@+id/text_view"

android:text="等待下载"

android:textSize="20dp"

android:layout_width="match_parent"

android:layout_height="wrap_content" />

<Button

android:id="@+id/start"

android:text="开始后台下载"

android:layout_width="match_parent"

android:layout_height="wrap_content" />

<TextView

android:text="这是活动二"

android:textSize="20dp"

android:layout_width="match_parent"

android:layout_height="wrap_content" />

</LinearLayout>package com.example.leixiansheng.servicetest2;

import android.app.Service;

import android.content.Intent;

import android.os.IBinder;

import android.util.Log;

import java.util.Timer;

import java.util.TimerTask;

/**

* Created by Leixiansheng on 2017/4/25.

*/

public class TestService extends Service {

private Person person;

private int i;

private Intent intent;

private Timer timer;

@Override

public IBinder onBind(Intent intent) {

return null;

}

@Override

public void onCreate() {

super.onCreate();

person = new Person();

Log.i("TestService",String.valueOf(person));

intent = new Intent("com.leixiansheng.broadcast");

//模拟开启后台下载

timer = new Timer();

timer.schedule(new MyTimerTask(),500);

}

private class MyTimerTask extends TimerTask {

@Override

public void run() {

if (i == 100) {

i = 0;

}

//携带数据,发送广播

intent.putExtra("CurrentLoading",i);

sendBroadcast(intent);

i++;

Log.e("TestService","i=" + i);

}

}

//活动结束,销毁timer

@Override

public void onDestroy() {

super.onDestroy();

timer.cancel();

}

}

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

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="com.example.leixiansheng.servicetest2">

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:supportsRtl="true"

android:theme="@style/AppTheme">

<activity android:name=".MainActivity">

<intent-filter>

<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

<activity android:name=".SecondActivity" />

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

</application>

</manifest>


三、service和活动间的通信

四、service和活动生命周期关系

代码如下:

package com.example.leixiansheng.test;

import android.content.ComponentName;

import android.content.Intent;

import android.content.ServiceConnection;

import android.os.IBinder;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.util.Log;

public class MainActivity extends AppCompatActivity {

private final static String TAG = "MainActivity";

private Intent intent;

private MyService.DownloadBinder downloadBinder;

//此处与service进行通信

private ServiceConnection connection = new ServiceConnection() {

@Override

public void onServiceConnected(ComponentName componentName,IBinder iBinder) {

downloadBinder = (MyService.DownloadBinder) iBinder;

downloadBinder.progress();

}

@Override

public void onServiceDisconnected(ComponentName componentName) {

}

};

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

intent = new Intent(this,MyService.class);

startService(intent);

bindService(intent,connection,BIND_AUTO_CREATE);

Log.i(TAG,"onCreate");

}

@Override

protected void onStart() {

super.onStart();

Log.i(TAG,"onStart");

}

@Override

protected void onResume() {

super.onResume();

Log.i(TAG,"onResume");

}

@Override

protected void onPause() {

super.onPause();

Log.i(TAG,"onPause");

}

@Override

protected void onStop() {

super.onStop();

Log.i(TAG,"onStop");

}

//必须解绑

@Override

protected void onDestroy() {

super.onDestroy();

Log.i(TAG,"onDestroy");

unbindService(connection);

stopService(intent);

}

}

package com.example.leixiansheng.test;

import android.app.DownloadManager;

import android.app.Service;

import android.content.Intent;

import android.os.Binder;

import android.os.IBinder;

import android.util.Log;

/**

* Created by Leixiansheng on 2017/5/2.

*/

public class MyService extends Service {

private final static String TAG = "MyService";

private DownloadBinder downloadBinder = new DownloadBinder();

public class DownloadBinder extends Binder {

public void progress() {

Log.i(TAG,"progress");

}

}

@Override

public IBinder onBind(Intent intent) {

Log.i(TAG,"onBind");

return downloadBinder;

}

@Override

public void onCreate() {

super.onCreate();

Log.i(TAG,"onCreate");

}

@Override

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

Log.i(TAG,"onStartCommand");

return super.onStartCommand(intent,flags,startId);

}

@Override

public void onDestroy() {

super.onDestroy();

Log.i(TAG,"onDestroy");

}

}

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

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="com.example.leixiansheng.test">

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:supportsRtl="true"

android:theme="@style/AppTheme">

<activity android:name=".MainActivity">

<intent-filter>

<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

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

</application>

</manifest>


运行顺序:

05-03 10:22:07.805 16119-16119/com.example.leixiansheng.test I/MainActivity: onCreate

05-03 10:22:07.805 16119-16119/com.example.leixiansheng.test I/MainActivity: onStart

05-03 10:22:07.805 16119-16119/com.example.leixiansheng.test I/MainActivity: onResume

05-03 10:22:07.835 16119-16119/com.example.leixiansheng.test I/MyService: onCreate

05-03 10:22:07.835 16119-16119/com.example.leixiansheng.test I/MyService: onStartCommand

05-03 10:22:07.835 16119-16119/com.example.leixiansheng.test I/MyService: onBind

05-03 10:22:07.915 16119-16119/com.example.leixiansheng.test I/MyService: progress

05-03 10:22:47.615 16119-16119/com.example.leixiansheng.test I/MainActivity: onPause

05-03 10:22:47.945 16119-16119/com.example.leixiansheng.test I/MainActivity: onStop

05-03 10:22:47.945 16119-16119/com.example.leixiansheng.test I/MainActivity: onDestroy

05-03 10:22:47.955 16119-16119/com.example.leixiansheng.test I/MyService: onDestroy


小结:

1、bindService() 和活动关联,活动终止,绑定必须在次活动前解绑,否则报错


      startService() 与活动无关联,自行运行。(任何活动都可以终止service),退出程序也没有stopService ,service 依旧在运行


2、服务 onCreate 只执行一次,后面再startService 只执行onStartCommand


3、server本身就继承了活动的context


4、活动和服务的生命周期关系是,先开启活动,再执行服务,先销毁活动,再销毁服务


5、····待补充


意见反馈 常见问题 官方微信 返回顶部