我的安卓学习日记

初学,一开始的控件处理的时候出现了问题,原因在于在UI显示之前调用,造成空指针错误,但是不会报错,运行中会出现has stopped的字样


使用安卓爬取百度的部分音乐:(至2016-6-10链接还能用 api也能用)  有很多细节未处理


Activity部分:

package com.example.test8;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.util.ByteArrayBuffer;
import org.apache.http.util.EncodingUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;







import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import com.example.test8.MainActivity;
import com.example.test8.R;

import bean.Songs;

public class MainActivity extends Activity {

	private Button button1;
	private Handler handler;
	private ListView list;
	private ArrayList<Object> songsList = new ArrayList<Object>();
	private ArrayList<Object> al = new ArrayList<Object>();
	private Button buttonToDownload;
	public static final String ACTION = "com.example.test8.BinderService";
	
	private TextView tvDownloading;
	
	private TextView tvDownloadStatus;
	private Handler timerhandler;
	private Timer timerDownload;
	private TimerTask timerTask;
	private BinderService.localBinder sBinder;
	private ServiceConnection sc;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		button1 = (Button) this.findViewById(R.id.button1);
		list = (ListView) this.findViewById(R.id.listView1);
		final Context ctx = (Context) this;
		// serviceIntent = new Intent(ACTION);
		button1.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				System.out.println("8");
				new Thread(new Runnable() {

					public void run() {
						final int result = getHTML();
						Message m1 = new Message();
						m1.what = 100;
						m1.obj = songsList;
						handler.sendMessage(m1);
					}
				}).start();

			}
		});
		
		handler = new Handler() {
			public void handleMessage(Message msg) {
				if (msg.what == 100) {
					// button1.setText((String)msg.obj);
					JSONArray _jsa;
					try {
						_jsa = new JSONArray(msg.obj.toString());
						System.out.println(_jsa);
						for (int i = 0; i < _jsa.length(); i++) {
							al.add((_jsa.get(i)).toString());
						}
					} catch (JSONException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					final ArrayAdapter<Object> arrayAdapter = new MyAdapter(
							ctx, R.id.listView1, songsList);
					list.setAdapter(arrayAdapter);
				}
			}
		};
		tvDownloading = (TextView)this.findViewById(R.id.textView4);
		tvDownloadStatus = (TextView)this.findViewById(R.id.textView2);
		timerhandler = new Handler(){
			public void handleMessage(Message message)
			{
				System.out.println("timerhandler");
				DecimalFormat df = new DecimalFormat("0.00");
				double cur = ((double)message.arg2)/1024/1024;
				double tt = ((double)message.arg1)/1024/1024;
				cur = Double.parseDouble(df.format(cur));
				tt = Double.parseDouble(df.format(tt));
				tvDownloadStatus.setText(cur+"M/"+tt+"M");
			}
		};
		
		timerTask = new TimerTask(){

			@Override
			public void run() {
				System.out.println("sBinder:"+sBinder);
				if(sBinder!=null)
				{
					System.out.println("timertask");
					Message m2 = new Message();
					m2.what = 101;
					m2.arg1 = (sBinder.getService().getTotalbyte());
					m2.arg2 = (sBinder.getService().getDownloadedbyte());
					timerhandler.sendMessage(m2);
				}
				
			}
			
		};
		
		sc = new ServiceConnection() {
			
			@Override
			public void onServiceDisconnected(ComponentName arg0) {
				// TODO Auto-generated method stub
				System.out.println("disconnected");
			}
			
			@Override
			public void onServiceConnected(ComponentName arg0, IBinder arg1) {
				// TODO Auto-generated method stub
				System.out.println("connected");
				sBinder = (BinderService.localBinder)arg1;
				System.out.println(sBinder);
				Log.d("sbindering", "sbindering ok");
			}
		};
	}

	class MyAdapter extends ArrayAdapter<Object> {
		private ArrayList<Object> obj;

		public MyAdapter(Context context, int resource, ArrayList<Object> obj) {
			super(context, resource, obj);
			this.obj = obj;
		}

		public View getView(final int position, View convertView,
				ViewGroup parent) {
			if (convertView == null) {
				convertView = LayoutInflater.from(MainActivity.this).inflate(
						R.layout.li, null);

			}
			TextView tv1 = (TextView) convertView.findViewById(R.id.textView1);
			TextView tv2 = (TextView) convertView.findViewById(R.id.textView2);
			Button btnfordownload = (Button) convertView
					.findViewById(R.id.buttonfordownload);
			final Songs song = (Songs)obj.get(position);
			tv1.setText(song.getSongName());
			tv2.setText(song.getSingerName());
	
			btnfordownload.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View arg0) {
//					new Thread(new Runnable() {
//						public void run() {
//							
//							Message m1 = new Message();
//							m1.what = 101;
//							m1.obj = url;
//							handler.sendMessage(m1);
//						}
//					}).start();
					System.out.println("button click");
					Intent serviceIntent = new Intent(MainActivity.this,com.example.test8.BinderService.class);
					serviceIntent.putExtra("url",song.getDownloadURL());
					serviceIntent.putExtra("fileName", song.getSongName()+"-"+song.getSingerName()+".mp3");
					//startService(serviceIntent);
					getApplicationContext().bindService(serviceIntent, sc, Context.BIND_AUTO_CREATE);
					System.out.println("after button click");
					timerDownload = new Timer();
					timerDownload.schedule(timerTask,0,2000);
					tvDownloading.setText(song.getSongName()+"-"+song.getSingerName());
				}
			});
			
			
			return convertView;
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	public void onDestroy()
	{
		getApplicationContext().unbindService(sc);
	}

//	public int startUrlCheck() {
//		HttpClient client = new DefaultHttpClient();
//		StringBuilder builder = new StringBuilder();
//		System.out.println("4");
//		String singer = "动力火车";
//
//		try {
//			singer = URLEncoder.encode(singer, "utf-8");
//		} catch (UnsupportedEncodingException e1) {
//			// TODO Auto-generated catch block
//			e1.printStackTrace();
//		}
//		System.out.println(singer);
//		String url = "http://musicmini.baidu.com/app/search/searchList.php?qword="+singer+"&ie=utf-8&page=0";
//
//		url = url.replaceAll(" ", "%20");
//		 url = url.replaceAll("&", "%26");
//		// try {
//		// url = URLEncoder.encode(url, "utf-8");
//		// } catch (UnsupportedEncodingException e1) {
//		// // TODO Auto-generated catch block
//		// e1.printStackTrace();
//		// }
//		// url = url.replaceAll("&", "%26");
//		//
//		// url = url.replaceAll("?", "%3F");
//		// url = url.replaceAll("|", "%124");
//		// url = url.replaceAll("=", "%3D");
//		// url = url.replaceAll("#", "%23");
//		// url = url.replaceAll("/ ", "%2F");
//		// url = url.replaceAll("+", "%2B");
//		// url = url.replaceAll("%", "%25");
//		System.out.println("5");
//		try {
//
//			HttpGet myget = new HttpGet(url);
//
//			System.out.println("1");
//			HttpResponse response = client.execute(myget);
//			System.out.println("2");
//			BufferedReader reader = new BufferedReader(new InputStreamReader(
//					response.getEntity().getContent()));
//			for (String s = reader.readLine(); s != null; s = reader.readLine()) {
//				builder.append(s);
//			}
//			System.out.println("3");
//			JSONObject jsonObject = new JSONObject(builder.toString());
//			System.out.println(jsonObject.toString());
//			// String re_username = jsonObject.getString("username");
//			// String re_password = jsonObject.getString("password");
//			int re_user_id = jsonObject.getInt("user_id");
//			// setTitle("用户id_"+re_user_id);
//			// Log.v("url response", "true="+re_username);
//			// Log.v("url response", "true="+re_password);
//		} catch (Exception e) {
//			Log.v("url response", "false");
//			e.printStackTrace();
//			System.out.println(e.getMessage());
//		}
//		return 1;
//	}
	
	public int getHTML()
	{
		songsList.clear();
		Document doc;
		String singer = "动力火车";
		
		try {
			singer = URLEncoder.encode(singer, "utf-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		System.out.println(singer);
		String url = "http://musicmini.baidu.com/app/search/searchList.php?qword="+singer+"&ie=utf-8&page=0";
		url = url.replaceAll(" ", "%20");
		 url = url.replaceAll("&", "%26");
		 String result = getHtmlString(url);
		 
		doc = Jsoup.parse(result);
		Elements songs = doc.getElementsByClass("sName");
		Elements singers = doc.getElementsByClass("uName");
		Elements songId = doc.getElementsByClass("sCheckBox");
		for(int i=0;i<8;i++)
		{
			String temp = songId.get(i).id();
			
			String infoURL = "http://ting.baidu.com/data/music/links?songIds="+temp;

			String songInfoPage = getHtmlString(infoURL);
	
			JSONObject job = null;
			String __temp = "";
			try {
				job = new JSONObject(songInfoPage);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				__temp = job.getString("data");

				JSONObject job2 = new JSONObject(__temp);
				
				JSONArray ja = job2.getJSONArray("songList");
				
				__temp = ja.getJSONObject(0).getString("songLink");
				
				if(__temp==null)
				{
					continue;
				}
				
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				Toast.makeText(this, "网络问题", Toast.LENGTH_SHORT).show();
				
				e.printStackTrace();
				
			}
			String singername = singers.get(i+1).attr("key");
			//System.out.println("singername:"+singername);
			String songname = songs.get(i+1).attr("key");
			//System.out.println("songname:"+songname);
			Songs song = new Songs();
			//System.out.println("songId:"+__temp);
			song.setDownloadURL(__temp);
			song.setSingerName(singername);
			song.setSongName(songname);
			songsList.add(song);
		}
		return 1;
	}
	
	public String getHtmlString(String urlString) {
		try {
			URL url = new URL(urlString);
			URLConnection ucon = url.openConnection();
			InputStream instr = ucon.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(instr);
			ByteArrayBuffer baf = new ByteArrayBuffer(50000);
			int current = 0;
			while ((current = bis.read()) != -1) {
				baf.append((byte) current);
			}
			return EncodingUtils.getString(baf.toByteArray(), "utf-8");
		} catch (Exception e) {
			return "";
		}
	}
	


}




service部分:

package com.example.test8;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.RandomAccessFile;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Service;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Binder;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.TextView;

public class BinderService extends Service {
	private Utils util = new Utils();
	public class localBinder extends Binder{
		String stringToSend = "this is a string for test";
		public BinderService getService()
		{
			return BinderService.this;
		}
	}
	
	private int downloadbyte = 0;
	private int totalbyte = 0;
	public int getDownloadedbyte()
	{
		return this.downloadbyte;
	}
	
	public int getTotalbyte()
	{
		return this.totalbyte;
	}
	
	private final IBinder mBinder = new localBinder();

	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		onStartCommand(arg0);
		return mBinder;
	}
	
	public void startDownloadThread(final String getURL,final String fileName)
	{
		new Thread(new Runnable(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				System.out.println("onStartCommand thread");
				RandomAccessFile randomAccessFile = null;
				BufferedInputStream rd = null;
				try{
					totalbyte = util.getFileSize(getURL);
					System.out.println("totalbyte:"+totalbyte);
					int length = 0;
					byte[] by = new byte[1024*80];
					int percent;
					//rd = util.getBufferedInputStream(getURL,0,totalbyte-1);
					rd = util.getBufferedInputStream(getURL);
					File destDir = new File(Environment.getExternalStorageDirectory().getPath()+"/hellowx/mp3");
					if(!destDir.exists())
					{
						destDir.mkdirs();
					}
					File file = new File(Environment.getExternalStorageDirectory().getPath()+"/hellowx/mp3/"+fileName);
					System.out.println("file"+file);
					System.out.println("onStartCommand file created");
					randomAccessFile = new RandomAccessFile(file, "rwd");
					randomAccessFile.seek(0);
					downloadbyte = 0;
					while((length=rd.read(by))!=-1)
					{
						randomAccessFile.write(by,0,length);
						downloadbyte+=length;
					}
				}
				catch(Exception ex)
				{
					System.out.println(ex.getMessage());
				}
				finally{
					try{
						if(rd!=null)
						{
							rd.close();
						}
					}
					catch(Exception ex)
					{
						try{
							if(randomAccessFile!=null)
							{
								randomAccessFile.close();
							}
						}
						catch(Exception ex2)
						{
							System.out.println(ex2.getMessage());
						}
					}
				}
			}
			
		}).start();
	}
	
	
	
	public void onCreate()
	{
		System.out.println("oncreate");
		super.onCreate();
	}
	
	
	public void onDestroy()
	{
		super.onDestroy();
	}

	public int onStartCommand(Intent intent)
	{
		System.out.println("onStartCommand");
		if(intent==null)
		{
			Log.d("BINDSERVER", "SDF");
		}
		else
		{
			System.out.println("onStartCommand else");
			Log.d("BINDSERVER","begin");
			final String getURL = intent.getStringExtra("url");
			final String fileName = intent.getStringExtra("fileName");
			startDownloadThread(getURL, fileName);
		}
		return 1;
	}
}


package com.example.test8;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import org.apache.http.HttpStatus;

public class Utils {
	public Utils(){}
	public int getFileSize(String urlString) throws IOException, Exception {
		System.out.println("getFileSizeStart");
		int length = 0;
		//String url = URLEncoder.encode(urlString, "UTF-8");
		URL mUrl = new URL(urlString);
		//URL mUrl = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) mUrl.openConnection();
		conn.setConnectTimeout(5 * 1000);
		conn.setRequestMethod("GET");
		conn.setRequestProperty("Accept-Encoding", "identity");
		conn.setRequestProperty("Referer", urlString);
		// conn.setRequestProperty("Referer", urlString);
		conn.setRequestProperty("Charset", "UTF-8");
		conn.setRequestProperty("Connection", "Keep-Alive");
		conn.connect();

		int responseCode = conn.getResponseCode();
		// 判断请求是否成功处理
		if (responseCode == HttpStatus.SC_OK) {
			length = conn.getContentLength();
		}
		System.out.println("file length:"+length);
		return length;
	}
	public BufferedInputStream getBufferedInputStream(String urlString) throws IOException, Exception {

		//String url = URLEncoder.encode(urlString, "UTF-8");
		URL mUrl = new URL(urlString);
		HttpURLConnection conn = (HttpURLConnection) mUrl.openConnection();
		InputStream is= conn.getInputStream();
		BufferedInputStream bis = new BufferedInputStream(is);
		return bis;
	}
}






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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值