安卓小案例收集三

原创 2016年05月30日 22:43:25

收集三

对话框

public void click1(View v){
    //创建对话框创建器
    AlertDialog.Builder builder = new Builder(this);
    //设置图标
    builder.setIcon(android.R.drawable.ic_dialog_alert);
    //设置标题
    builder.setTitle("警告");
    //设置内容
    builder.setMessage("欲练此功必先自宫,春晓你确定要自宫吗");

    //设置确定按钮
    builder.setPositiveButton("确定", new OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(MainActivity.this, "自宫完成,谢谢使用", 0).show();

        }
    });
    //设置取消按钮
    builder.setNegativeButton("取消", new OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(MainActivity.this, "若不自宫,一定不成功", 0).show();

        }
    });

    //显示对话框
    AlertDialog ad = builder.create();
    ad.show();
   }

   public void click2(View v){
    //创建对话框创建器
    AlertDialog.Builder builder = new Builder(this);
    //设置图标
    builder.setIcon(android.R.drawable.ic_dialog_alert);
    //设置标题
    builder.setTitle("选择您的家乡");

    final String[] items = new String[]{
            "火星",
            "塞伯坦",
            "氪星",
            "M78星云",
    };

    //设置单选选项
    builder.setSingleChoiceItems(items, 1, new OnClickListener() {

        //dialog:触发此方法执行的那个对话框
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(MainActivity.this, items[which], 0).show();
            //对话框消失
            dialog.dismiss();

        }
    });

    //显示对话框
    builder.show();
   }

   public void click3(View v){
    //创建对话框创建器
    AlertDialog.Builder builder = new Builder(this);
    //设置图标
    builder.setIcon(android.R.drawable.ic_dialog_alert);
    //设置标题
    builder.setTitle("选择您需要的武器");

    final String[] items = new String[]{
            "板凳",
            "啤酒瓶",
            "开山刀",
            "AK-47",
            "爱国者",
            "唐晓平"
    };

    final boolean[] checkedItems = new boolean[]{
            true,
            false,
            false,
            false,
            false,
            true
    };

    //设置多选选项
    builder.setMultiChoiceItems(items, checkedItems, new OnMultiChoiceClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which, boolean isChecked) {
            //记录用户的选择
            checkedItems[which] = isChecked;
        }
    });
    builder.setPositiveButton("确定", new OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            String text = "";
            for (int i = 0; i < checkedItems.length; i++) {
                text += checkedItems[i]? items[i] + ",": "";
            }
            Toast.makeText(MainActivity.this, text, 0).show();

        }
    });

    builder.show();
   }

   public void click4(View v){
    //创建进度条对话框
    final ProgressDialog dialog = new ProgressDialog(this);
    dialog.setIcon(android.R.drawable.ic_input_add);
    dialog.setTitle("正在自宫中,请稍候...");
    dialog.setMax(100);
    dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    Thread t = new Thread(){
        public void run() {
            for (int i = 0; i <= 100; i++) {
                dialog.setProgress(i);
                try {
                    sleep(20);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            //自宫完成,进度消失
            dialog.dismiss();
        }
    };
    t.start();
    dialog.show();
   }

多线程下载、断点续传

String path = "http://169.254.88.88:8080/LiebaoFreeWiFi5.1.exe";
int threadCount = 3;
int finishedThread = 0;
//所有线程下载总进度
int downloadProgress = 0;
private ProgressBar pb;
private TextView tv;

Handler handler = new Handler(){
    public void handleMessage(android.os.Message msg) {
        tv.setText((long)pb.getProgress() * 100 / pb.getMax() + "%");
    }
};
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    pb = (ProgressBar) findViewById(R.id.pb);
    tv = (TextView) findViewById(R.id.tv);
}


public void click(View v){
    Thread t = new Thread(){
        @Override
        public void run() {
            //发送http请求,拿到目标文件长度
            try {
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(8000);
                conn.setReadTimeout(8000);

                if(conn.getResponseCode() == 200){
                    //获取长度
                    int length = conn.getContentLength();

                    //创建临时文件
                    File file = new File(Environment.getExternalStorageDirectory(), getNameFromPath(path));
                    RandomAccessFile raf = new RandomAccessFile(file, "rwd");
                    //设置临时文件大小与目标文件一致
                    raf.setLength(length);
                    raf.close();

                    //设置进度条的最大值
                    pb.setMax(length);

                    //计算每个线程下载区间
                    int size = length / threadCount;

                    for (int id = 0; id < threadCount; id++) {
                        //计算每个线程下载的开始位置和结束位置
                        int startIndex = id * size;
                        int endIndex = (id + 1) * size - 1;
                        if(id == threadCount - 1){
                            endIndex = length - 1;
                        }
                        System.out.println("线程" + id + "下载的区间:" + startIndex + " ~ " + endIndex);
                        new DownLoadThread(id, startIndex, endIndex).start();
                    }

                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    };
    t.start();
}

public String getNameFromPath(String path){
    int index = path.lastIndexOf("/");
    return path.substring(index + 1);
}

class DownLoadThread extends Thread{

    int threadId;
    int startIndex;
    int endIndex;


    public DownLoadThread(int threadId, int startIndex, int endIndex) {
        super();
        this.threadId = threadId;
        this.startIndex = startIndex;
        this.endIndex = endIndex;
    }


    @Override
    public void run() {
        try {
            File fileProgress = new File(Environment.getExternalStorageDirectory(), threadId + ".txt");
            int lastProgress = 0;
            if(fileProgress.exists()){
                //读取进度临时文件中的内容
                FileInputStream fis = new FileInputStream(fileProgress);
                BufferedReader br = new BufferedReader(new InputStreamReader(fis));
                //得到上一次下载进度
                lastProgress = Integer.parseInt(br.readLine());
                //改变下载的开始位置,上一次下过的,这次就不请求了
                startIndex += lastProgress;
                fis.close();

                //把上一次下载进度加到进度条进度中
                downloadProgress += lastProgress;
                //发送消息,让文本进度条改变
                handler.sendEmptyMessage(1);
            }

            //发送http请求,请求要下载的数据
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(8000);
            conn.setReadTimeout(8000);
            //设置请求数据的区间
            conn.setRequestProperty("Range", "bytes=" + startIndex + "-" + endIndex);

            //请求部分数据,成功的响应码是206
            if(conn.getResponseCode() == 206){
                InputStream is = conn.getInputStream();

                byte[] b = new byte[1024];
                int len = 0;
                //当前线程下载的总进度
                int total = lastProgress;
                File file = new File(Environment.getExternalStorageDirectory(), getNameFromPath(path));
                RandomAccessFile raf = new RandomAccessFile(file, "rwd");
                //设置写入的开始位置
                raf.seek(startIndex);
                while((len = is.read(b)) != -1){
                    raf.write(b, 0, len);
                    total += len;
                    System.out.println("线程" + threadId + "下载了:" + total);


                    //创建一个进度临时文件,保存下载进度
                    RandomAccessFile rafProgress = new RandomAccessFile(fileProgress, "rwd");
                    //每次下载1024个字节,就,就马上把1024写入进度临时文件
                    rafProgress.write((total + "").getBytes());
                    rafProgress.close();

                    //每次下载len个长度的字节,马上把len加到下载进度中,让进度条能反应这len个长度的下载进度
                    downloadProgress += len;
                    pb.setProgress(downloadProgress);

                    //发送消息,让文本进度条改变
                    handler.sendEmptyMessage(1);

                }
                raf.close();
                System.out.println("线程" + threadId + "下载完毕------------------");

                //3条线程全部下载完毕,才去删除进度临时文件
                finishedThread++;

                synchronized (path) {
                    if(finishedThread == threadCount){
                        for (int i = 0; i < threadCount; i++) {
                            File f = new File(Environment.getExternalStorageDirectory(), i + ".txt");
                            f.delete();
                        }
                        finishedThread = 0;
                    }
                }
            }

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

XUtils的使用

private ProgressBar pb;
private TextView tv_progress;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    pb = (ProgressBar) findViewById(R.id.pb);
    tv_progress = (TextView) findViewById(R.id.tv_progress);
}

public void click(View v){
    String url = "http://169.254.244.136:8080/QQPlayer.exe";
    HttpUtils utils = new HttpUtils();
    utils.download(url, //目标文件的网址
            "sdcard/QQPlayer.exe", //指定存储的路径和文件名
            true, //是否支持断点续传
            true, //如果响应头中包含文件名,下载完成后自动重命名
            new RequestCallBack<File>() {

                //下载完成后调用
                @Override
                public void onSuccess(ResponseInfo<File> responseInfo) {
                    TextView tv_success = (TextView) findViewById(R.id.tv_success);
                    tv_success.setText(responseInfo.result.getPath());

                }

                //下载失败调用
                @Override
                public void onFailure(HttpException error, String msg) {
                    TextView tv_failure = (TextView) findViewById(R.id.tv_failure);
                    tv_failure.setText(msg);

                }

                //下载过程中不断调用
                @Override
                public void onLoading(long total, long current,
                        boolean isUploading) {

                    pb.setMax((int) total);
                    pb.setProgress((int) current);
                    tv_progress.setText(current * 100 / total + "%");
                }
            });
}

Activity跳转

protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
    //把“activity_main”这个布局文件能生成的视图界面作为它的上下文。
   }

   //隐式跳转至打电话Activity
   public void click1(View v){
    //创建意图,这个是隐式意图
    Intent intent = new Intent();
    //设置动作
    intent.setAction(Intent.ACTION_CALL);
    intent.setData(Uri.parse("tel:110"));
    //启动Activity
    startActivity(intent);
   }

   //显式启动SecondActivity
   public void click2(View v){
    //这个是显式意图
    Intent intent = new Intent();
    //设置上下文和目标Activity的字节码
    intent.setClass(this, SecondActivity.class);
    startActivity(intent);
   }
   //显式启动拨号器
   public void click3(View v){
    Intent intent = new Intent();
    //arg0:目标Activity所在的应用的包名
    //arg1:目标Activity的类名,注意要带上包名
    intent.setClassName("com.android.dialer", "com.android.dialer.DialtactsActivity");
    intent.setData(Uri.parse("tel:11670"));
    startActivity(intent);
   }

   /**
    * 隐式启动拨号器
    */
   public void click4(View v){
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_DIAL);
    intent.setData(Uri.parse("tel:76115230"));
    startActivity(intent);
   }
   /**
    * 隐式启动SecondActivity
    */
   public void click5(View v){
    Intent intent = new Intent();
    intent.setAction("a.b.c");
    //匹配mimetype
//      intent.setType("text/name");
    //匹配scheme
//      intent.setData(Uri.parse("heima:春眠不觉晓"));

    intent.setDataAndType(Uri.parse("heima:春眠不觉晓"), "text/name");

    //如果没有设置Category的匹配,那么自动匹配CATEGORY_DEFAULT
//      intent.addCategory(Intent.CATEGORY_DEFAULT);
    startActivity(intent);
   }

   /**
    * 显式启动浏览器
    */
   public void click6(View v){
    Intent intent = new Intent();
    intent.setClassName("com.android.browser", "com.android.browser.BrowserActivity");
    startActivity(intent);
   }
   /**
    * 隐式启动浏览器
    */
   public void click7(View v){
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    intent.setData(Uri.parse("http:www.baidu.com"));
    startActivity(intent);
   }

Intent跳转并携带数据(Intent、Bundle携带)

public void click(View v){
    EditText et_malename = (EditText) findViewById(R.id.et_malename);
    EditText et_femalename = (EditText) findViewById(R.id.et_femalename);

    String maleName = et_malename.getText().toString();
    String femaleName = et_femalename.getText().toString();

    //跳转到SecondActivity,在second中做姻缘计算
    Intent intent = new Intent(this, SecondActivity.class);
    //把数据封装至intent中
    //intent中可以封装数据,数据有八大基本数据类型和字符串及它们的数组,还有实现了序列化接口的对象,还有bundle对象
//      intent.putExtra("maleName", maleName);
//      intent.putExtra("femaleName", femaleName);

    //Bundle中也可以用键值对封装数据,封装类型与intent一致
    Bundle extras = new Bundle();
    extras.putString("maleName", maleName);
    extras.putString("femaleName", femaleName);
    intent.putExtras(extras);
    startActivity(intent);

   }

Activity销毁时传递数据

传递的那个示例:

//显示联系人列表
        ListView lv = (ListView) findViewById(R.id.lv);
        lv.setAdapter(new ArrayAdapter<String>(this, R.layout.item_listview, R.id.tv, names));

        lv.setOnItemClickListener(new OnItemClickListener() {
            //position:点击某个条目时,会通过position告诉程序员点击的是哪一个条目
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {

                Intent data = new Intent();
                //把要传递的数据封装至intent中
                data.putExtra("name", names[position]);
                //当此Activity销毁时,返回至上一个Activity时,会把这个intent对象传递给上一个Activity
                setResult(10, data);

                //销毁当前Activity
                finish();
            }

        });

接收的示例:

public static final int CONTACT = 10;
public static final int SMS = 20;
public static final int HANDLE_EXCEPTION = 30;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);

   }


   public void click(View v){
    Intent intent = new Intent(this, ContactActivity.class);
    //启动一个Activity去获取数据(结果)
    startActivityForResult(intent, CONTACT);
   }
   public void click2(View v){
    Intent intent = new Intent(this, SmsActivity.class);
    startActivityForResult(intent, SMS);
   }
   public void click3(View v){
    Intent intent = new Intent(this, HandleExceptionActivity.class);
    startActivityForResult(intent, HANDLE_EXCEPTION);
   }

   //只有通过startActivityForResult启动的Activity销毁时,才会回调这个方法,方法中传入的intent就封装了返回的数据
   @Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    //通过请求码来判断data来自哪一个Activity
    if(requestCode == CONTACT){
        String name = data.getStringExtra("name");

        EditText et_name = (EditText) findViewById(R.id.et_name);
        et_name.setText(name);
    }
    else if(requestCode == SMS){
        String sms = data.getStringExtra("sms");
        EditText et_content = (EditText) findViewById(R.id.et_content);
        et_content.setText(sms);
    }
    //先通过请求码判断data来自哪个Activity
    else if(requestCode == HANDLE_EXCEPTION){
        //通过结果码判断数据data中的数据是什么类型
        if(resultCode == 100){
            String name = data.getStringExtra("name");
            EditText et_name = (EditText) findViewById(R.id.et_name);
            et_name.setText(name);
        }
        else if(resultCode == 200){
            String sms = data.getStringExtra("sms");
            EditText et_content = (EditText) findViewById(R.id.et_content);
            et_content.setText(sms);
        }
    }
   }

Receiver案例

ip拨号器示例

public void onReceive(Context context, Intent intent) {
    //取出广播中的号码
    String number = getResultData();
    String newNumber = "17951" + number;
    //把修改后的号码放入广播中
    setResultData(newNumber);   
    //拦截是无效的
    abortBroadcast();
}

短信拦截

public void onReceive(Context context, Intent intent) {
    //取出短信内容
    Bundle bundle = intent.getExtras();
    //数组中的每一个元素,就是一条短信
    Object[] objects = (Object[]) bundle.get("pdus");

    for (Object object : objects) {
        //把数组中的元素转换成短信对象
        SmsMessage sms = SmsMessage.createFromPdu((byte[]) object);
        //获取对方号码
        String address = sms.getOriginatingAddress();
        //获取短信内容
        String body = sms.getMessageBody();

        System.out.println(address + ";" + body);

        if("13888".equals(address)){
            //拦截短信
            abortBroadcast();
        }
    }

}

SD卡状态监听

public void onReceive(Context context, Intent intent) {
    //判断收到的是神马广播
    //获取广播中的action
    String action = intent.getAction();

    if(Intent.ACTION_MEDIA_MOUNTED.equals(action)){
        Toast.makeText(context, "sd卡就绪", 0).show();
    }
    else if(Intent.ACTION_MEDIA_REMOVED.equals(action)){
        Toast.makeText(context, "sd卡被拔出了", 0).show();
    }
    else if(Intent.ACTION_MEDIA_UNMOUNTED.equals(action)){
        Toast.makeText(context, "sd卡被卸载了", 0).show();
    }

}

流氓软件

@Override
public void onReceive(Context context, Intent intent) {
    //启动勒索应用
    Intent it = new Intent(context, MainActivity.class);
    //创建新的任务栈,因为这行代码执行时,没有任务栈
    it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(it);
}

应用的安装卸载监听

public void onReceive(Context context, Intent intent) {
    //判断收到的是什么广播
    String action = intent.getAction();
    //获取安装更新卸载的是什么应用
    Uri uri = intent.getData();
    if(Intent.ACTION_PACKAGE_ADDED.equals(action)){
        Toast.makeText(context, uri + "被安装了", 0).show();
    }
    else if(Intent.ACTION_PACKAGE_REMOVED.equals(action)){
        Toast.makeText(context, uri + "被删除了", 0).show();
    }
    else if(Intent.ACTION_PACKAGE_REPLACED.equals(action)){
        Toast.makeText(context, uri + "被更新了", 0).show();
    }

}

发送无序广播

public void click(View v){
    Intent intent = new Intent();
    intent.setAction("a.b.c");
    //发送自定义无序广播
    sendBroadcast(intent);
   }

接收:

<receiver android:name="com.itheima.receivecustombroadcast.MyReceiver">

    <intent-filter >

        <action android:name="a.b.c"/>

    </intent-filter>

</receiver>

优先级及最终接受者

  public void click(View v){
  Intent intent = new Intent();
  intent.setAction("com.center.fdm");
    //发送自定义有序广播
    //resultReceiver:在所有广播接收者都收到广播之后,才会收到,一定是最后一个收到,并且一定能收到
    sendOrderedBroadcast(intent, null, new MyReceiver(), null, 0, "每人发100斤大米", null);
  }

  class MyReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        String order = getResultData();
        System.out.println("反贪局收到文件:" + order);

    }       
 }

配置优先级:

<receiver android:name="com.itheima.local.ShengZF">

    <intent-filter android:priority="1000">

    <action android:name="com.center.fdm"/>

</intent-filter>

</receiver>

      <receiver android:name="com.itheima.local.ShiZF">

    <intent-filter android:priority="800">

    <action android:name="com.center.fdm"/>

    </intent-filter>

</receiver>

<receiver android:name="com.itheima.local.XianZF">

    <intent-filter android:priority="600">

    <action android:name="com.center.fdm"/>

</intent-filter>

服务

启动停止:

 public void start(View v){
    //启动服务
    Intent intent = new Intent(this, MyService.class);
    startService(intent);

 }
 public void stop(View v){
    //停止服务
    Intent intent = new Intent(this, MyService.class);
    stopService(intent);    
 }

电话录音服务

private MediaRecorder recorder;
@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public void onCreate() {
    super.onCreate();
    //获取电话管理器
    TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
    //监听电话状态
    tm.listen(new MyListener(), PhoneStateListener.LISTEN_CALL_STATE);
}

class MyListener extends PhoneStateListener{
    //电话状态改变时回调
    @Override
    public void onCallStateChanged(int state, String incomingNumber) {
        super.onCallStateChanged(state, incomingNumber);
        //判断当前是什么状态
        switch (state) {
        case TelephonyManager.CALL_STATE_IDLE:
            if(recorder != null){
                System.out.println("停止录音");
                //停止录音
                recorder.stop();
                //释放录音机占用的资源
                recorder.release();
                recorder = null;
            }
            break;
        case TelephonyManager.CALL_STATE_RINGING:
            if(recorder == null){
                recorder = new MediaRecorder();
                //设置音频来源
                recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                //设置输出格式
                recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
                recorder.setOutputFile("sdcard/voice.3gp");
                //设置音频编码
                recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
                try {
                    System.out.println("准备好");
                    recorder.prepare();
                } catch (IllegalStateException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
            break;
        case TelephonyManager.CALL_STATE_OFFHOOK:
            if(recorder != null){
                System.out.println("开始录音");
                recorder.start();
            }
            break;

        }
    }

}

服务的两种启动方式

private MyConn conn;
@Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);

       conn = new MyConn();
   }


   public void start(View v){
    //这些都是显示启动
    Intent intent = new Intent(this, MyService.class);
    startService(intent);
   }
   public void stop(View v){
    Intent intent = new Intent(this, MyService.class);
    stopService(intent);
   }
   public void bind(View v){
    Intent intent = new Intent(this, MyService.class);
    //绑定服务
    bindService(intent, conn, BIND_AUTO_CREATE);
   }

   public void unbind(View v){
    //解绑服务
    unbindService(conn);
   }

   class MyConn implements ServiceConnection{

    //到服务的连接被建立了,此方法调用
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        // TODO Auto-generated method stub

    }

    //到服务的连接中断了,此方法调用
    @Override
    public void onServiceDisconnected(ComponentName name) {
        // TODO Auto-generated method stub

    }

   }

   public void jump(View v){
    Intent intent = new Intent(this, SecondActivity.class);
    startActivity(intent);
   }

中间人服务

接口层:

public interface PublicBusiness {

    void qianXian();
}

Service:

public class LeaderService extends Service {
    @Override
    public IBinder onBind(Intent intent) {
        // 返回中间人对象
        return new FengMiShu();
    }
    class FengMiShu extends Binder implements PublicBusiness{
        //中间人的牵线
        @Override
        public void qianXian(){
            //调用领导的办证
            banZheng();
        }

        public void takeSoap(){

        }
    }   
    public void banZheng(){
        System.out.println("成功办证");
    }
}

调用服务:

protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       //服务是需要通过intent来实现的。
       Intent intent = new Intent(this, LeaderService.class);
       bindService(intent, new ServiceConnection() {

        //连接因为异常而终止才会调用
        @Override
        public void onServiceDisconnected(ComponentName name) {

        }

        //onBind有返回值此方法才会调用
        //service:这个对象就是onBind返回的中间人
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            pb = (PublicBusiness) service;

        }
    }, BIND_AUTO_CREATE);
   }


   public void click(View v){
    pb.qianXian();
 }

音乐播放

接口:

public interface ControllerInterface {

    void play();
    void pause();
}

服务:

public class MusicService extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        return new MusicController();
    }

    class MusicController extends Binder implements ControllerInterface{

        @Override
        public void play() {
            MusicService.this.play();

        }

        @Override
        public void pause() {
            MusicService.this.pause();

        }

    }

    public void play(){
        System.out.println("开始播放音乐");
    }
    public void pause(){
        System.out.println("暂停播放音乐");
    }
}

调用:

public class MainActivity extends Activity {

    ControllerInterface ci;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent intent = new Intent(this, MusicService.class);
        //把进程变成服务进程,这样可以后台播放
        startService(intent);
        //绑定服务获取中间人对象
        bindService(intent, new ServiceConnection() {

            @Override
            public void onServiceDisconnected(ComponentName name) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                ci = (ControllerInterface) service;

            }
        }, BIND_AUTO_CREATE);
    }


    public void play(View v){
        ci.play();
    }
    public void pause(View v){
        ci.pause();
    }
}

通过服务手动启动广播接受者

public class RegisterService extends Service {

    private ScreenOnOFFReceiver receiver;

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //1.创建广播接收者对象
        receiver = new ScreenOnOFFReceiver();
        //2.创建意图过滤器对象
        IntentFilter filter = new IntentFilter();
        //指定接收什么广播
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_SCREEN_ON);
        //3.注册广播接收者
        registerReceiver(receiver, filter);

    }   
    @Override
    public void onDestroy() {
        super.onDestroy();
        //反注册广播接收者
        unregisterReceiver(receiver);
    }   
}
版权声明:本文为博主原创文章,未经博主允许不得转载。

安卓小案例收集四(多媒体)

加载大图片 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInst...

安卓小案例收集五(内容提供者、动画)

内容提供者 获取系统短息 插入系统短信 获取系统联系人 插入联系人 内容观察者 Fragment Fragment数据传递 帧动画 补间动画 属性动画内容提供者配置:...

RSS阅读器-安卓小案例

  • 2016年04月17日 18:33
  • 1.95MB
  • 下载

【Android小游戏】安卓小游戏开发(手把手教学系列三)

想起当年初学安卓时,Java还不懂,大一做类似这样的游戏的时候,居然不用线程 想想也是醉了,现在来填几年前的坑 开始: 就像之前两篇一样,要一个游戏人物,一个游戏运行Activity 1.游戏人物: ...

安卓小游戏-猜猜鸡蛋在哪里

  • 2017年11月24日 15:30
  • 17.03MB
  • 下载

BMI测试 安卓小应用

  • 2016年01月20日 12:41
  • 590KB
  • 下载

2.一个随机生成多种颜色并获取颜色RGB值以及对应十六进制的安卓小应用

安卓学习中,每次选择颜色十六进制都让人头大,试着开发一个应用解决这个问题。 实现效果如下图: 主要功能: 1. 随机生成100种颜色(有重复,重复并不影响选择,没喜欢的颜...

安卓小视频压缩代码

  • 2017年08月15日 16:59
  • 47.7MB
  • 下载

安卓小软件

  • 2013年04月06日 13:17
  • 19KB
  • 下载

初识安卓小程序(Android短信发送器)

首先,先创建一个安卓项目(我的版本是4.4.2的),名字为"短信发送器" 然后在res文件夹下找到layout文件夹,找到activity_main.xml或fragment_main.xml,在里...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:安卓小案例收集三
举报原因:
原因补充:

(最多只允许输入30个字)