使用services在后台实现下载与远程服务


使用services在后台实现下载

AndroidManifest.xml

<!--配置服务-->
        <service android:name=".MyService2"
            android:enabled="true"
            android:exported="true"></service>

Main2Activity.java

package com.zking.administrator.g160628_android23_services;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

public class Main2Activity extends AppCompatActivity {

    private ProgressBar pb_progressbar_bar;
    private TextView tv_progressbar_num;
    private Intent intent;
    private MyReceiver myReceiver;
    private IntentFilter intentFilter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        myReceiver = new MyReceiver();
        intentFilter = new IntentFilter();
        intentFilter.addAction("com.zking.administrator.g160628_android23_services.download");
        intent=new Intent(this,MyService2.class);//服务器
        pb_progressbar_bar= (ProgressBar) findViewById(R.id.pb_progressbar);
        tv_progressbar_num= (TextView) findViewById(R.id.tv_progressbar_num);
    }

    //动态配置广播接收器
    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(myReceiver,intentFilter);
    }

    //动态配置广播接收器
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myReceiver);
    }
    //单击下载按钮,启动服务,记得配置服务
    public void download(View view){
        startService(intent);
    }
    Handler handler=new Handler(){
        //接受消息,更新UI界面
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int i=msg.what;
            tv_progressbar_num.setText(i+"");
        }
    };
    //接收广播的内部类
    class MyReceiver extends BroadcastReceiver{

        private int content;
        @Override
        public void onReceive(Context context, Intent intent) {
            //获取广播的名字
            String action=intent.getAction();
            if("com.zking.administrator.g160628_android23_services.download".equals(action)) {
                content = intent.getIntExtra("content", 50);//接收发送过来的广播,默认值为50
                new MyThread().start();//启动线程
            }
        }
            //通过线程拿到发送过来的值
            class MyThread extends Thread {
                @Override
                public void run() {
                    super.run();
                    for (int i = 0; i <= 100; i++) {
                        pb_progressbar_bar.setProgress(content);//将接收的值设置给进度条
                        handler.sendEmptyMessage(content);//通过handler发送给本界面
                        try {
                            sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

MyService2.java

package com.zking.administrator.g160628_android23_services;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.IntDef;
import android.support.annotation.Nullable;
import android.util.Log;

/**
 * Created by Administrator on 2017/7/14.
 */

public class MyService2 extends Service{
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        new MyThread(startId).start();
        return Service.START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
    class MyThread extends Thread{
        private int startId;
        public MyThread(int startId){
            this.startId=startId;
        }

        @Override
        public void run() {
            //创建发送广播
            Intent intent= new Intent();
            //广播的名字
            intent.setAction("com.zking.administrator.g160628_android23_services.download");
            for (int i = 1; i <=100 ; i++) {
                //设置发送的值
                intent.putExtra("content",i);
                Log.i("test","content,"+i);
                //发送
                sendBroadcast(intent);
                try {
                    sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //服务自杀
            stopSelf();
        }
    }
}

服务端(QQ)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    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"
    android:orientation="vertical"
    tools:context="com.zking.administrator.g160628_android24_myqq.MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="MyQQ"
        android:textSize="30sp"/>
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/et_main_number"
        android:hint="请输入用户名"/>
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入密码"
        android:id="@+id/et_main_pass"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="登录"
        android:onClick="login"/>
</LinearLayout>

MainActivity.java

package com.zking.administrator.g160628_android24_myqq;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

/**
 * 所谓的远程服务,是同一部手机,里面的两个应用程序之间相互通信,被称为应用程序
 * 什么样的应用需要远程服务?
 * QQ 微信 QQ输入法,-->它们共同的特点就是登陆
 * 写一个QQ登陆,把一个公共的模块把它提取出来,让其他手机上所有应用程序都调用它
 * C客户端(微信和QQ输入法) S服务端(QQ和QQ登录)
 */
public class MainActivity extends AppCompatActivity {

    private EditText et_main_number;
    private EditText et_main_pass;
    private Intent intent;
//    private QQLoginService.MyIBinder myIBinder;
    //3.0版本使用接口
//    private QQLogin qqLogin;
    //自动生成的类
    private QQLoginInterface qqLoginInterface;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_main_number = (EditText) findViewById(R.id.et_main_number);
        et_main_pass = (EditText) findViewById(R.id.et_main_pass);
        intent = new Intent(this,QQLoginService.class);
    }

    ServiceConnection connection=new ServiceConnection() {



        //连接成功
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i("test","绑定成功");
            // 把IBinder强转成我们自己写的MyIBinder
//            myIBinder = (QQLoginService.MyIBinder) service;
            //给接口
//            qqLogin = (QQLogin) service;
            //自动生成的类
            qqLoginInterface = QQLoginInterface.Stub.asInterface(service);
        }

        //连接失败
        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i("test","绑定失败");

        }
    };
    @Override
    protected void onResume() {
        super.onResume();
        //绑定服务
        //Service.BIND_AUTO_CREATE在我绑定的时候自动创建服务
        bindService(intent,connection, Service.BIND_AUTO_CREATE);
    }

    public void login(View view){
        //当我一点登录按钮,首先拿到用户名和密码
        String number=et_main_number.getText().toString();
        String pass=et_main_pass.getText().toString();
        boolean flag= false;
        //自动生成抛异常
        try {
            flag = qqLoginInterface.login(number,pass);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        if(flag){
            Toast.makeText(this, "登录成功!", Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(this, "登录失败!", Toast.LENGTH_SHORT).show();
        }
        //3.0使用接口
//        boolean flag=qqLogin.login(number,pass);
//        if(flag){
//            Toast.makeText(this, "登录成功!", Toast.LENGTH_SHORT).show();
//        }else{
//            Toast.makeText(this, "登录失败!", Toast.LENGTH_SHORT).show();
//
//        }
        //当我一点登录按钮,我就可以调用myIBinder(2.0版本利用服务实现登录)
//        boolean flag=myIBinder.login(number,pass);
//        if(flag){
//            Toast.makeText(this, "登录成功!", Toast.LENGTH_SHORT).show();
//        }else{
//            Toast.makeText(this, "登录失败!", Toast.LENGTH_SHORT).show();
//
//        }
//        //判断用户名和密码(1.0版本)
//        if("00000".equals(number)&&"123456".equals(pass)){
//            Toast.makeText(this, "登录成功!", Toast.LENGTH_SHORT).show();
//        }else{
//            Toast.makeText(this, "登录失败!", Toast.LENGTH_SHORT).show();
//        }
    }
}

QQLogin.java

package com.zking.administrator.g160628_android24_myqq;

/**
 * Created by Administrator on 2017/7/15.
 */

public interface QQLogin {
    public boolean login(String number,String pass);
}
QQLoginInterface.aidl

// QQLoginInterface.aidl
package com.zking.administrator.g160628_android24_myqq;

// Declare any non-default types here with import statements

interface QQLoginInterface {
//不允许用修饰符
   boolean login(String number,String pass);
}

QQLoginService.java

package com.zking.administrator.g160628_android24_myqq;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

/**
 * Created by Administrator on 2017/7/15.
 */

public class QQLoginService extends Service{
    //自动生成的内只要继承QQLoginInterface
    class MyIBinder extends QQLoginInterface.Stub{

        @Override
        public boolean login(String number, String pass) throws RemoteException {
            if("00000".equals( number)&&"123456".equals(pass)){
            return true;
        }
            return false;
        }
    }
    //写一个自己的内部类
    //把它看做jsp,servlet里的业务逻辑类Dao层
//    class MyIBinder extends Binder implements QQLogin{
//        public boolean login(String number,String pass){
//            if("00000".equals(number)&&"123456".equals(pass)){
//                return true;
//            }else{
//                return false;
//            }
//        }
//    }
    //远程服务就onBind一个就够了
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.i("test","onBind");
        return new MyIBinder();
    }
}

AndroidManifest.xml

<!--配置-->
        <service android:name=".QQLoginService"
            android:enabled="true"
            android:exported="true"></service>

客户端(微信)

QQLoginInterface.java

/*
 * This file is auto-generated.  DO NOT MODIFY.
 * Original file: D:\\Android\\AndroidStudioProjects\\MyApplication3\\g160628_android24_myqq\\src\\main\\aidl\\com\\zking\\administrator\\g160628_android24_myqq\\QQLoginInterface.aidl
 */
package com.zking.administrator.g160628_android24_myqq;
// Declare any non-default types here with import statements

public interface QQLoginInterface extends android.os.IInterface
{
/** Local-side IPC implementation stub class. */
public static abstract class Stub extends android.os.Binder implements QQLoginInterface
{
private static final String DESCRIPTOR = "com.zking.administrator.g160628_android24_myqq.QQLoginInterface";
/** Construct the stub at attach it to the interface. */
public Stub()
{
this.attachInterface(this, DESCRIPTOR);
}
/**
 * Cast an IBinder object into an com.zking.administrator.g160628_android24_myqq.QQLoginInterface interface,
 * generating a proxy if needed.
 */
public static QQLoginInterface asInterface(android.os.IBinder obj)
{
if ((obj==null)) {
return null;
}
android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
if (((iin!=null)&&(iin instanceof QQLoginInterface))) {
return ((QQLoginInterface)iin);
}
return new Proxy(obj);
}
@Override public android.os.IBinder asBinder()
{
return this;
}
@Override public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException
{
switch (code)
{
case INTERFACE_TRANSACTION:
{
reply.writeString(DESCRIPTOR);
return true;
}
case TRANSACTION_login:
{
data.enforceInterface(DESCRIPTOR);
String _arg0;
_arg0 = data.readString();
String _arg1;
_arg1 = data.readString();
boolean _result = this.login(_arg0, _arg1);
reply.writeNoException();
reply.writeInt(((_result)?(1):(0)));
return true;
}
}
return super.onTransact(code, data, reply, flags);
}
private static class Proxy implements QQLoginInterface
{
private android.os.IBinder mRemote;
Proxy(android.os.IBinder remote)
{
mRemote = remote;
}
@Override public android.os.IBinder asBinder()
{
return mRemote;
}
public String getInterfaceDescriptor()
{
return DESCRIPTOR;
}
//不允许用修饰符

@Override public boolean login(String number, String pass) throws android.os.RemoteException
{
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
boolean _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeString(number);
_data.writeString(pass);
mRemote.transact(Stub.TRANSACTION_login, _data, _reply, 0);
_reply.readException();
_result = (0!=_reply.readInt());
}
finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
}
static final int TRANSACTION_login = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
}
//不允许用修饰符

public boolean login(String number, String pass) throws android.os.RemoteException;
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    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"
    android:orientation="vertical"
    tools:context="com.zking.administrator.g160628_android24_myweixin.MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="MyWeiXin"
        android:textSize="30sp"/>
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/et_main_number"
        android:hint="请输入用户名"/>
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入密码"
        android:id="@+id/et_main_pass"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="登录"
        android:onClick="login"/>
</LinearLayout>

MainActivity.java

package com.zking.administrator.g160628_android24_myweixin;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.zking.administrator.g160628_android24_myqq.QQLoginInterface;

/**
 *同一部手机里边两个应用程序之间,一个客户端《微信》,一个服务端《QQ》
 *
 */
public class MainActivity extends AppCompatActivity {

    private EditText et_main_number;
    private EditText et_main_pass;
    private Intent intent;
    private QQLoginInterface qqLoginInterface;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_main_number = (EditText) findViewById(R.id.et_main_number);
        et_main_pass = (EditText) findViewById(R.id.et_main_pass);
        intent = new Intent();
        //QQLoginService包名加类名(第一个双引号指的是应用程序的包名,在这样的情况下就可以用微信启动QQ的服务)
        ComponentName componentName=new ComponentName("com.zking.administrator.g160628_android24_myqq","com.zking.administrator.g160628_android24_myqq.QQLoginService");
        intent.setComponent(componentName);
    }

    ServiceConnection connection=new ServiceConnection() {


        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i("test","绑定成功");
            qqLoginInterface = QQLoginInterface.Stub.asInterface(service);

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i("test","绑定失败");
        }
    };
    @Override
    protected void onResume() {
        super.onResume();
        //绑定服务
        bindService(intent,connection, Service.BIND_AUTO_CREATE);
    }

    public void login(View view){
        String number=et_main_number.getText().toString();
        String pass=et_main_pass.getText().toString();
        try {
            boolean b=qqLoginInterface.login(number,pass);
            if(b){
                Toast.makeText(this, "登录成功!", Toast.LENGTH_SHORT).show();
            }else {
                Toast.makeText(this, "登录失败!", Toast.LENGTH_SHORT).show();

            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值