Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> 安卓小案例收集三

安卓小案例收集三

編輯:關於Android編程

對話框

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() {

                //下載完成後調用
                @Override
                public void onSuccess(ResponseInfo 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(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);
   }

接收:



    

        

    

優先級及最終接受者

  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);

    }       
 }

配置優先級:



    

    





      

    

    

    





    

    

服務

啟動停止:

 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);
    }   
}
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved