1.自定义Toast
步骤,首先需要添加一个自定义的toast布局,然后通过构造方法实例化一个Toast对象即可
public void onToast(View view) {
//1.加载自定义布局
LayoutInflater layoutInflater = LayoutInflater.from(this);
View view1 = layoutInflater.inflate(R.layout.toast_laout, null);
//创建对象
Toast toast = new Toast(this);
//设置自定义布局
toast.setView(view1);
//设置显示时间
toast.setDuration(Toast.LENGTH_SHORT);
//设置位置
toast.setGravity(Gravity.CENTER, 0, 0);
//显示
toast.show();
}
步骤,创建一个继承自View绘图的类DrawView,获取组件并显示
DrawView.java
package com.example.movball;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
/**
* Created by y0n on 2017/5/9.
*/
public class DrawView extends View{
public float currentX = 40;
public float currentY = 50;
//创建画笔
Paint p = new Paint();
public DrawView(Context context) {
super(context);
}
public DrawView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 设置画笔颜色
p.setColor(Color.RED);
// 绘制小圆
canvas.drawCircle(currentX, currentY, 15, p);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
//修改X,Y的属性
currentX = event.getX();
currentY = event.getY();
//通知当前组件重绘自己
invalidate();
//返回true表明已经处理该时间
return true;
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取容器
LinearLayout root = (LinearLayout) findViewById(R.id.activity_main);
//创建DrawView组件
DrawView drawView = new DrawView(this);
//设置自定义组件大小
drawView.setMinimumWidth(300);
drawView.setMinimumHeight(500);
root.addView(drawView);
}
步骤,添加布局及控件,再使用Intent发送意图
package com.example.phonecall;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.EditText;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void callphone(View view){
//获取电话号码
EditText editText = (EditText)findViewById(R.id.edt1);
String num = editText.getText().toString();
//1.创建Intent对象,封装数据,传递数据
Intent intent = new Intent();
//2.设置打电话动作
intent.setAction(Intent.ACTION_CALL);
//3.封装数据打包到Intent中
//按照打电话的规定格式
Uri uri = Uri.parse("tel:" + num);
intent.setData(uri);
//4.根据Intent传递的动作,启动应用
startActivity(intent);
}
public void sendsms(View view){
//1.获取电话号码
EditText editText = (EditText) findViewById(R.id.edt1);
String num = editText.getText().toString();
//2.获取短信内容
EditText editText1 = (EditText)findViewById(R.id.edt2);
String content = editText1.getText().toString();
//3.获取短信管理器对象
SmsManager smsManager = SmsManager.getDefault();
//4.拆分短信
ArrayList smss = smsManager.divideMessage(content);
//5.发送短信
smsManager.sendMultipartTextMessage(num,null,smss,null,null);
}
}
4.ListViewBaseAdapter
listview实现方式有使用ArrayAdapter,BaseAdapter,SimpleAdapter,实现步骤大致相同,先获取数据源,然后再创建适配器,再显示到控件中
BaseAdapter例子如下:
package com.example.baseadapterlistview;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by y0n on 2017/5/16.
*/
public class MyListAdapter extends BaseAdapter{
private static final String TAG = "sc";
List
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//1.获取ListView对象
ListView listView = (ListView) findViewById(R.id.lv);
//2.创建适配器
MyListAdapter adapter = new MyListAdapter(this);
adapter.InitList();
//3.关联listView对象
listView.setAdapter(adapter);
}
}
步骤,编写布局及控件,实现控件响应
package com.example.inner;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//1.加载文件中的用户信息
String string = loadUserAndPass();
if (string == null)
{
return ;
}
//2.拆分用户名和密码,进行设置
String[] userInfo = string.split("##");
EditText edituser = (EditText) findViewById(R.id.edt_usr);
EditText editpass = (EditText) findViewById(R.id.edt_pass);
edituser.setText(userInfo[0]);
editpass.setText(userInfo[1]);
}
public String loadUserAndPass() {
//1.获取路径
//String path = "data/data/com.bluelesson.inner/info.txt";
String path = "data/data/"+ getPackageName() +"/info.txt";
// 2. 创建文件对象, 判断是否已经存在,不存在直接退出
File file = new File(path);
//File file = getFilesDir();
if (!file.exists()){
Toast.makeText(this, "用户配置文件不存在", Toast.LENGTH_SHORT).show();
return null;
}
//3.加载用户信息
String strings = null;
try{
FileInputStream fileInputStream = new FileInputStream(file);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
strings = bufferedReader.readLine();
fileInputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return strings;
}
public void saveUserAndPass(String user, String pass)
{
// 保存用户名和密码,保存到安装的app目录下
// 1. 获取路径
String path = "data/data/com.example.inner/info.txt";
//2.创建文件对象
File file = new File(path);
//3.将用户信息写入到文件对象中
String info = user + "##" + pass;
//使用文件输出流写入到文件对象中
try{
FileOutputStream fileoutputStream = new FileOutputStream(file);
fileoutputStream.write(info.getBytes());
fileoutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void login(View view) {
//1.获取用户名
EditText editUser = (EditText) findViewById(R.id.edt_usr);
EditText editPass = (EditText) findViewById(R.id.edt_pass);
String user = editUser.getText().toString();
String pass = editPass.getText().toString();
//2.判断是否一致
if (user.equals(pass))
{
Toast.makeText(this, "登录成功!", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this, "登录失败!", Toast.LENGTH_SHORT).show();
}
//3.判断是否需要保存
CheckBox checkBoxUser = (CheckBox) findViewById(R.id.checkbox_usr);
CheckBox checkBoxPass = (CheckBox) findViewById(R.id.checkbox_pass);
if (checkBoxUser.isChecked() || checkBoxPass.isChecked()){
saveUserAndPass(user, pass);
}
}
}
package com.example.filechangemod;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View view) {
int id = view.getId();
String name = "";
int mode = 0;
switch (id){
case R.id.btn_private:
name = "private.txt";
mode = Context.MODE_PRIVATE;
break;
case R.id.btn_append:
name = "append.txt";
mode = Context.MODE_APPEND;
break;
case R.id.btn_global_read:
name = "global_read.txt";
mode = Context.MODE_WORLD_READABLE;
break;
case R.id.btn_global_write:
name = "global_write.txt";
mode = Context.MODE_WORLD_WRITEABLE;
break;
case R.id.btn_global_rw:
name = "global_wr.txt";
mode = Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE;
break;
}
try{
FileOutputStream fileOutputStream = openFileOutput(name, mode);
fileOutputStream.write("文件信息:".getBytes());
fileOutputStream.write(name.getBytes());
fileOutputStream.write(mode);
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void save(View view){
SharedPreferences sharedPreferences = getSharedPreferences("lock", Context.MODE_WORLD_READABLE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("password", "hello");
editor.commit();
Toast.makeText(this, "editor.commit()", Toast.LENGTH_SHORT).show();
}
public void onClickRead(View view) {
String name = "private.txt";
try{
FileInputStream fileInputStream = openFileInput(name);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
String info = bufferedReader.readLine();
bufferedReader.close();
fileInputStream.close();
Toast.makeText(this, info, Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
7.sqlite
package com.example.sqlite;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* Created by y0n on 2017/5/17.
*/
public class DBHelper extends SQLiteOpenHelper {
private static final String TAG = "DBHelper";
public DBHelper(Context context, String name){
super(context, name, null, 1);
}
public DBHelper(Context context, String name, int version){
super(context, name, null, version);
}
public DBHelper(Context context,
String name,
SQLiteDatabase.CursorFactory factory,
int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.d(TAG, "onCreate");
// 创建数据库中的表信息
String sql = "create table user(id int,name varchar(20))";
// 执行sql语句
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d(TAG, "onUpgrade");
}
}
package com.example.sqlite;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void create_database(View view) {
//1.创建一个sqlite数据版主类对象
DBHelper dbHelper = new DBHelper(this, "test_db");
//2.创建并打开数据库
SQLiteDatabase db = dbHelper.getReadableDatabase();
if (db.isOpen())
{
Toast.makeText(this, "创建数据库成功!", Toast.LENGTH_SHORT).show();
}
//3.关闭数据库
db.close();
}
public void update_database(View view) {
//1.创建一个sqlite数据的版主类对象
DBHelper dbHelper = new DBHelper(this, "test_db");
//2.创建并打开数据库
SQLiteDatabase db = dbHelper.getReadableDatabase();
//3.关闭数据库
db.close();
}
public void add_data(View view) {
//1.打开数据库,获取数据库对象
DBHelper dbHelper = new DBHelper(this, "test_db");
SQLiteDatabase db = dbHelper.getReadableDatabase();
if (db.isOpen())
{
//2.添加数据
ContentValues values = new ContentValues();
values.put("id", "1001");
values.put("name", "北京");
db.insert("user", null, values);
values.put("id", "1002");
values.put("name", "上海");
db.insert("user", null, values);
values.put("id", "1003");
values.put("name", "深圳");
db.insert("user", null, values);
values.put("id", "1004");
values.put("name", "广州");
db.insert("user", null, values);
//3.关闭数据库
db.close();
Toast.makeText(this, "数据插入成功!", Toast.LENGTH_SHORT).show();
}
}
public void delete_data(View view) {
//1.打开数据库,获取数据库对象
DBHelper dbHelper = new DBHelper(this, "test_db");
SQLiteDatabase db = dbHelper.getReadableDatabase();
if (db.isOpen())
{
//2.删除数据
db.delete("user", "id=?", new String []{"1002"});
//3.关闭数据库
db.close();
Toast.makeText(this, "删除数据成功!", Toast.LENGTH_SHORT).show();
}
}
public void update_data(View view) {
//1.打开数据库,获取数据库对象
DBHelper dbHelper = new DBHelper(this, "test_db");
SQLiteDatabase db = dbHelper.getReadableDatabase();
if (db.isOpen())
{
//2.更新数据
ContentValues values = new ContentValues();
values.put("name", "成都");
db.update("user", values, "id=?", new String []{"1003"});
//3.关闭数据库
db.close();
Toast.makeText(this, "更新数据成功!", Toast.LENGTH_SHORT).show();
}
}
public void select_data(View view) {
//1.打开数据库,获取数据库对象
DBHelper dbHelper = new DBHelper(this, "test_db");
SQLiteDatabase db = dbHelper.getReadableDatabase();
//2.返回数据集
Cursor cursor = db.query("user", new String[]{"id", "name"}, null, null, null, null, null);
//3.遍历数据
int count = cursor.getCount();
if (count <= 0)
return ;
cursor.moveToFirst();
do {
String[] cols = cursor.getColumnNames();
String id = cursor.getString(0);
String name = cursor.getString(1);
Toast.makeText(this, "id="+ id +",name="+name, Toast.LENGTH_SHORT).show();
}while(cursor.moveToNext());
//3.关闭数据库
db.close();
}
}
package com.example.keyevent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
byte[] byPassword = new byte[20];
char[] chAscii = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
char[] chPassword = new char[20];
int count = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
Toast.makeText(this, "onKeyDown"+event.getAction(), Toast.LENGTH_SHORT).show();
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (count > 20)
return super.onKeyUp(keyCode,event);
if (keyCode >= 7 && keyCode <= (7+9))
{
byPassword[count] = (byte)(keyCode-7);
chPassword[count] = chAscii[byPassword[count]];
count++;
}
else if (count != 0 && keyCode == 38)
{
count--;
}
Toast.makeText(this, "onKeyUP:"+(keyCode-7)+event.getAction(), Toast.LENGTH_SHORT).show();
return super.onKeyUp(keyCode, event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Toast.makeText(this, "onTouchEvent"+event.getAction(), Toast.LENGTH_SHORT).show();
return super.onTouchEvent(event);
}
public void onClick(View view) {
String password = String.copyValueOf(chPassword, 0, count);
String encode = Base64.encodeToString(password.getBytes(), 0);
byte[] decode = Base64.decode(encode, 0);
Toast.makeText(this, "password:"+encode, Toast.LENGTH_SHORT).show();
Toast.makeText(this, "password:"+decode, Toast.LENGTH_SHORT).show();
}
}
public class SDcardReceiver extends BroadcastReceiver {
public SDcardReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
String action = intent.getAction();
if (action.equals("android.intent.action.MEDIA_MOUNTED")){
Log.v("sdCard", "sd卡就绪");
}
else if (action.equals("android.intent.action.MEDIA_UNMOUNTED")){
Log.v("sdCard", "sd卡被移除");
}
else if (action.equals("android.intent.action.MEDIA_REMOVED")){
Log.v("sdCard", "sd卡被拔出");
}
}
}
package com.example.applisten;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
public class MyAPPInstallReceiver extends BroadcastReceiver {
public MyAPPInstallReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
Uri uri = intent.getData();
String action = intent.getAction();
if (action.equals("action.intent.action.PACKAGE_ADDED")){
Log.v("APPReceiver", uri + "被安装了");
}
else if (action.equals("action.intent.action.PACKAGE_REPLACED")){
Log.v("APPReceiver", uri + "被更新了");
}
else if (action.equals("action.intent.action.PACKAGE_REMOVED")){
Log.v("APPReceiver", uri + "被卸载了");
}
}
}
public class smsHookReceiver extends BroadcastReceiver {
public smsHookReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
Bundle bundle = intent.getExtras();
Object[] objects = (Object[])bundle.get("pdus");
for (int i = 0; i < objects.length; i++)
{
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[])objects[i]);
String sms = smsMessage.getMessageBody();
Toast.makeText(context, "sms:" + sms, Toast.LENGTH_SHORT).show();
String num = smsMessage.getOriginatingAddress();
Toast.makeText(context, "num:" + num, Toast.LENGTH_SHORT).show();
}
}
}
package com.example.phonelisten;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
public class MyService extends Service {
private final String TAG = "MyService";
private TelephonyManager tm;
private MyPhoneStateListener listener;
public MyService() {
}
@Override
public void onDestroy() {
Log.d(TAG, "onDestroy");
super.onDestroy();
tm.listen(listener, PhoneStateListener.LISTEN_NONE);
}
@Override
public void onCreate() {
super.onCreate();
tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
listener = new MyPhoneStateListener();
tm.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
private class MyPhoneStateListener extends PhoneStateListener{
@Override
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
switch (state){
case TelephonyManager.CALL_STATE_IDLE:
Log.d(TAG, "电话闲置");
break;
case TelephonyManager.CALL_STATE_RINGING:
Log.d(TAG, "电话响铃");
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
Log.d(TAG, "电话接听");
break;
}
}
}
}
package com.example.localselectperson;
/**
* Created by y0n on 2017/5/19.
*/
public interface IPerson {
public String queryNameByID(int id);
}
package com.example.localselectperson;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
public class MyService extends Service {
MyBinder binder;
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return binder;
}
@Override
public void onCreate() {
super.onCreate();
binder = new MyBinder();
}
class MyBinder extends Binder implements IPerson{
String[] mStrings = {"张山", "里斯", "王五", "找刘", "前期"};
@Override
public String queryNameByID(int id) {
if (id < 0 || id >= 4)
{
return "查入此人";
}
return mStrings[id];
}
}
@Override
public void onDestroy() {
super.onDestroy();
if (binder != null){
binder = null;
}
}
}
package com.example.localselectperson;
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.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Intent mIntent;
private MyServiceConn conn;
MyService.MyBinder mMyBinder = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onStartService(View view) {
mIntent = new Intent(this, MyService.class);
conn = new MyServiceConn();
bindService(mIntent, conn, BIND_AUTO_CREATE);
Toast.makeText(this, "绑定完成", Toast.LENGTH_SHORT).show();
}
public void onStopService(View view) {
unbindService(conn);
stopService(mIntent);
mMyBinder = null;
Toast.makeText(this, "mMyBinder = null", Toast.LENGTH_SHORT).show();
}
public void onSelect(View view){
EditText editText = (EditText)findViewById(R.id.edit_query);
String id = editText.getText().toString();
if (id.length() > 7)
{
Toast.makeText(this, "长度不能超过7", Toast.LENGTH_SHORT).show();
return;
}
if (mMyBinder != null)
{
String name = mMyBinder.queryNameByID(Integer.parseInt(id));
TextView textView = (TextView) findViewById(R.id.show_text);
textView.setText(name);
}
else
{
TextView textView = (TextView) findViewById(R.id.show_text);
textView.setText("没有开启服务");
}
}
private class MyServiceConn implements ServiceConnection{
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mMyBinder = (MyService.MyBinder) service;
}
@Override
public void onServiceDisconnected(ComponentName name) {
//非正常情况下bind服务断开时或被杀死时调用
mMyBinder = null;
}
}
}
package com.example.appmanager;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
//刷新//直接点击按钮响应
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onAllAPK(View view) {
Intent intentALL = new Intent(MainActivity.this, ActivityAllApk.class);
startActivity(intentALL);
}
public void onSysAPK(View view) {
Intent intentSys = new Intent(MainActivity.this, ActivitySystemApk.class);
startActivity(intentSys);
}
public void onThirdAPK(View view) {
Intent intentThird = new Intent(MainActivity.this, ActivityThirdApk.class);
startActivity(intentThird);
}
}
package com.example.appmanager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import java.util.ArrayList;
import java.util.List;
/**
* Created by y0n on 2017/5/20.
*/
public class GetAppsinfo {
public static final int FILTER_ALL_APP = 0; // 所有应用程序
public static final int FILTER_SYSTEM_APP = 1; // 系统程序
public static final int FILTER_THIRD_APP = 2; // 第三方应用程序
private Context mContext = null;
private PackageManager mPackageManager = null;
private List mAppsInfoList = new ArrayList();
public GetAppsinfo(Context mContext) {
this.mContext = mContext;
// PackageManager 类表示已安装的应用程序信息
mPackageManager = mContext.getPackageManager(); }
public List filterApp(int filter){
//查询所有已经安装的应用程序
ListapplicationInfos=
mPackageManager.getInstalledApplications(
PackageManager.GET_UNINSTALLED_PACKAGES);
mAppsInfoList.clear();
switch (filter){
case FILTER_ALL_APP:
{
for (ApplicationInfo applicationInfo: applicationInfos ){
getApkInfo(applicationInfo);
}
}
break;
case FILTER_SYSTEM_APP:
{
for (ApplicationInfo applicationInfo : applicationInfos) {
if ((applicationInfo.flags &
ApplicationInfo.FLAG_SYSTEM) != 0) {
getApkInfo(applicationInfo);
}
}
}
break;
case FILTER_THIRD_APP:
{
for (ApplicationInfo applicationInfo : applicationInfos) {
// 非系统应用
if ((applicationInfo.flags &
ApplicationInfo.FLAG_SYSTEM) <= 0) {
getApkInfo(applicationInfo);
}
// 系统应用,但更新后变成不是系统应用了
else if ((applicationInfo.flags &
ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
getApkInfo(applicationInfo);
}
}
}
break;
}
return mAppsInfoList;
}
private void getApkInfo(ApplicationInfo app){
AppsInfo appsInfo = new AppsInfo();
// 获取应用名称
String appName = app.loadLabel(mPackageManager).toString();
String packageName = app.packageName; // 包名
Drawable drIcon = app.loadIcon(mPackageManager); // 图标
appsInfo.setStrApkName(appName);
appsInfo.setStrPackageName(packageName);
appsInfo.setDrIcon(drIcon);
mAppsInfoList.add(appsInfo);
System.out.println("程序名:" + appName +
" 包名:" + packageName);
}
//卸载
public void unInstall(String strPackgeName){
Intent intent = new Intent(Intent.ACTION_DELETE);
intent.setData(Uri.parse("package:"+ strPackgeName));
mContext.startActivity(intent);
}
}
package com.example.appmanager;
import android.graphics.drawable.Drawable;
/**
* Created by y0nz1 on 2017/5/19.
*/
public class AppsInfo {
String strApkName; //程序名
String strPackageName; //包名
Drawable drIcon; //图标
public Drawable getDrIcon() {
return drIcon;
}
public void setDrIcon(Drawable drIcon) {
this.drIcon = drIcon;
}
public String getStrApkName() {
return strApkName;
}
public void setStrApkName(String strApkName) {
this.strApkName = strApkName;
}
public String getStrPackageName() {
return strPackageName;
}
public void setStrPackageName(String strPackageName) {
this.strPackageName = strPackageName;
}
public AppsInfo(Drawable drIcon, String strApkName, String strPackageName) {
this.drIcon = drIcon;
this.strApkName = strApkName;
this.strPackageName = strPackageName;
}
public AppsInfo() {
}
}
package com.example.appmanager;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by y0n on 2017/5/19.
*/
public class APKAdapter extends BaseAdapter {
List mAppsInfoList = new ArrayList();
Context mContext;
public APKAdapter(List mAppsInfoList, Context mContext) {
this.mAppsInfoList = mAppsInfoList;
this.mContext = mContext;
}
@Override
public int getCount() {
return mAppsInfoList.size();
}
@Override
public Object getItem(int position) {
return mAppsInfoList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
View view = null;
//1.当 covertView 为空时(第一次调用)
if (convertView == null){
//1.获取布局加载器
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
//2.获取 view 对象
view = layoutInflater.inflate(R.layout.item,null);
//3.获取 item 中的控件对象
viewHolder = new ViewHolder(view);
view.setTag(viewHolder);
}else {
view = convertView;
viewHolder = (ViewHolder) view.getTag();
}
//2.将信息显示都界面上
AppsInfo appsInfo = (AppsInfo) getItem(position);
viewHolder.mImIcon.setImageDrawable(appsInfo.getDrIcon());
viewHolder.mTvAppName.setText(appsInfo.getStrApkName());
viewHolder.mTvAppPackge.setText(appsInfo.getStrPackageName());
return view;
}
public class ViewHolder{
ImageView mImIcon = null;
TextView mTvAppName = null;
TextView mTvAppPackge = null;
public ViewHolder(View view){
mImIcon = (ImageView) view.findViewById(R.id.im_icon);
mTvAppName = (TextView) view.findViewById(R.id.tv_appname);
mTvAppPackge = (TextView) view.findViewById(R.id.tv_apppackge);
}
}
}
package com.example.appmanager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import static com.example.appmanager.GetAppsinfo.FILTER_ALL_APP;
public class ActivityAllApk extends AppCompatActivity {
private long mid;
private String packgename;
private List mAppsInfoList;
private GetAppsinfo apkinfo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_apk);
// 1. 获取 ListView 对象
ListView listView = (ListView) findViewById(R.id.list_all_apk);
// 2. 创建适配器
mAppsInfoList = new ArrayList();
// 3. 获取APk信息
apkinfo = new GetAppsinfo(getApplicationContext());
mAppsInfoList = apkinfo.filterApp(FILTER_ALL_APP);
APKAdapter adapter = new APKAdapter(mAppsInfoList, getApplicationContext());
// 3. 关联 listView 对象
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView> parent, View view, int position, long id) {
Log.v("apkinfo", "uninstall");
mid = id;
Button button = (Button) view.findViewById(R.id.btn_uninstall);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
packgename = mAppsInfoList.get((int) mid).getStrPackageName();
String appname = mAppsInfoList.get((int) mid).getStrApkName();
apkinfo.unInstall(packgename);
Toast.makeText(v.getContext(), "将卸载" + appname, Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
package com.example.appmanager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import static com.example.appmanager.GetAppsinfo.FILTER_SYSTEM_APP;
public class ActivitySystemApk extends AppCompatActivity {
private long mid;
private String packgename;
private List mAppsInfoList;
private GetAppsinfo apkinfo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_system_apk);
// 1. 获取 ListView 对象
ListView listView = (ListView) findViewById(R.id.list_system_apk);
// 2. 创建适配器
mAppsInfoList = new ArrayList();
// 3. 获取APk信息
apkinfo = new GetAppsinfo(getApplicationContext());
mAppsInfoList = apkinfo.filterApp(FILTER_SYSTEM_APP);
APKAdapter adapter = new APKAdapter(mAppsInfoList, getApplicationContext());
// 3. 关联 listView 对象
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView> parent, View view, int position, long id) {
Log.v("apkinfo", "uninstall");
mid = id;
Button button = (Button) view.findViewById(R.id.btn_uninstall);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
packgename = mAppsInfoList.get((int)mid).getStrPackageName();
String appname = mAppsInfoList.get((int)mid).getStrApkName();
apkinfo.unInstall(packgename);
Toast.makeText(v.getContext(), "将卸载" + appname, Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
package com.example.appmanager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import static com.example.appmanager.GetAppsinfo.FILTER_THIRD_APP;
import static com.example.appmanager.R.layout.activity_third_apk;
public class ActivityThirdApk extends AppCompatActivity {
private List mAppsInfoList;
private String packgename;
private long mid;
private View mview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_third_apk);
// 1. 获取 ListView 对象
ListView listView = (ListView) findViewById(R.id.list_third_apk);
// 2. 创建适配器
mAppsInfoList = new ArrayList();
// 3. 获取APk信息
final GetAppsinfo apkinfo = new GetAppsinfo(getApplicationContext());
mAppsInfoList = apkinfo.filterApp(FILTER_THIRD_APP);
APKAdapter adapter = new APKAdapter(mAppsInfoList, getApplicationContext());
// 3. 关联 listView 对象
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView> parent, View view, int position, long id) {
Log.v("apkinfo", "uninstall");
mid = id;
Button button = (Button) view.findViewById(R.id.btn_uninstall);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
packgename = mAppsInfoList.get((int)mid).getStrPackageName();
String appname = mAppsInfoList.get((int)mid).getStrApkName();
apkinfo.unInstall(packgename);
Toast.makeText(v.getContext(), "将卸载" + appname, Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
package com.example.htmlsourceviewplus;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private Button mBtnOpenUrl;
private Button mBtnCancel;
private SeekBar mSeekBar;
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBtnOpenUrl = (Button) findViewById(R.id.btn);
mBtnCancel = (Button) findViewById(R.id.btn_cancel);
mSeekBar = (SeekBar) findViewById(R.id.seekBar);
mTextView = (TextView) findViewById(R.id.tv_text);
mBtnOpenUrl.setEnabled(true);
mBtnCancel.setEnabled(false);
}
public void openurl(View view) {
MyAyncTask myAyncTask = new MyAyncTask();
myAyncTask.execute("http://www.hao123.com");
mBtnOpenUrl.setEnabled(false);
mBtnCancel.setEnabled(true);
}
public void cancel(View view) {
mBtnOpenUrl.setEnabled(true);
mBtnCancel.setEnabled(false);
}
//异步任务
private class MyAyncTask extends AsyncTask{
//初始化UI
@Override
protected void onPreExecute() {
super.onPreExecute();
mSeekBar.setProgress(0);
mSeekBar.setMax(100);
mTextView.setText("loading ...");
}
//后台操作
@Override
protected String doInBackground(String... params) {
try {
// 1. 构造URL对象
String path = params[0];
URL url = new URL(path);
// 2. 创建一个URL连接对象
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// 3. 设置URL的请求模式或者其他信息
urlConnection.setRequestMethod("GET");
urlConnection.setConnectTimeout(5000);
urlConnection.setRequestProperty("Accept-Encoding", "identity");
// 4. 请求数据,获取返回码
int code = urlConnection.getResponseCode();
// 200 OK 302 found 404 not fount 500 内部错误
if (code == 200) {
// 获取内容长度,需要指定RequestProperty
int nMaxLen = urlConnection.getContentLength();
int nLen = 0;
// 4.1 读取信息
InputStream inputStream = urlConnection.getInputStream();
byte[] bytes = new byte[50];
int iReadSize = 0;
// 创建字节流对象,用于保存输入流的信息
ByteArrayOutputStream byteObj = new ByteArrayOutputStream();
while (iReadSize != -1) {
// 循环读取数据信息,每次读取1024字节,会自动移动指针
// 第二个参数指的值字节数组的起始偏移
iReadSize = inputStream.read(bytes, 0, 50);
if (iReadSize == -1) break;
// 计算已经读取的长度
nLen += iReadSize;
// 更新进度
this.publishProgress((int) (((float) nLen / (float) nMaxLen) * 100));
byteObj.write(bytes, 0, iReadSize);
}
inputStream.close();
//获取字符
String strings = new String(byteObj.toByteArray());
return strings;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//更新进度
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
mSeekBar.setProgress(values[0]);
}
//处理返回信息
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
mTextView.setText(s);
}
}
}
16.解析Android清单文件
package com.example.parsemanifast;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private List tagList;
private List retStr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* 1.获取文件path,getAssets
* 2.打开文件,inputStream
* 3.new 一个字符数组
* 4.new一个字符数组输出流对象
* 5.循环读取,read到字符数组输出流对象中
* 6.再转成字符串
* 7.再解析,myXMLParse
* 8.创建ui线程显示到界面
*/
//读取文件并解析,测试
public void onParseXML(View view) {
String xml = null;
AssetManager assetManager = getAssets();
try {
InputStream inputStream = assetManager.open("manifast.xml");
byte[] bytes = new byte[1024];
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int nReadSize = 0;
while (nReadSize != -1) {
nReadSize = inputStream.read(bytes, 0, 1024);
if (nReadSize == -1) break;
byteArrayOutputStream.write(bytes);
}
inputStream.close();
xml = new String(byteArrayOutputStream.toByteArray());
//调用标签解析函数
//测试
List listTag = myParseTag(xml);
retStr = new ArrayList<>();
int j = 0;
for (int i = 0; i < listTag.size(); i ++)
{
Map mapnameval = myParesVat(xml, listTag.get(i));
for (Map.Entry entry : mapnameval.entrySet())
{
System.out.println("<" + listTag.get(i) + ">:"
+ "\t" + entry.getKey()
+ "=" + entry.getValue());
String strTextView = "<" + listTag.get(i) + ">:"
+ "\t" + entry.getKey()
+ "=" + entry.getValue();
retStr.add(strTextView);
}
}
} catch (Exception e) {
e.printStackTrace();
}
//1.获取对象
ListView lv = (ListView) findViewById(R.id.listview1);
//2.获取数据
ArrayAdapter arrayAdapter =
new ArrayAdapter(this, R.layout.item,R.id.text1, retStr);
// setListAdapter();
lv.setAdapter(arrayAdapter);
}
/**
* 1.获取xml解析工厂
* 2.获取xml解析器
* 3.设置解析的文件
* 4.获取事件类型
* 5.循环解析
* 6.getName,保存到list中
* 7.返回List数据为标签列表
*/
//解析出标签,保存到List中
public List myParseTag(String xml) {
XmlPullParserFactory factory = null;
//标签列表
tagList = new ArrayList<>();
// //属性列表
// attrList = new ArrayList<>();
// //属性和值的映射
// Map attrMap = new HashMap<>();
// //属性和值的映射的列表
// List
package com.example.jsoup;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private TextView textView;
private List content = new ArrayList<>();
//http://m.kugou.com/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.tv_show);
textView.setText("抓取中...");
runSubThread();
}
public void runSubThread(){
new Thread(){
@Override
public void run() {
super.run();
String path = "http://m.kugou.com";
try {
Document doc = Jsoup.connect(path).userAgent("Mozilla/5.0 (Linux;" +
" Android 6.0;" +
" Nexus 5 Build/MRA58N) AppleWebKit/537.36" +
" (KHTML, like Gecko) Chrome/58.0.3029.110 Mobile Safari/537.36").
timeout(5000).
get();
Elements links = doc.select("a[href]");
Elements media = doc.select("img[src]");
Elements imports = doc.select("link[href]");
System.out.println(String.format("Media:(%d)", media.size()));
for (Element src : media)
{
if (src.tagName().equals("img")){
System.out.println("" + String.format("%s:%s",
src.tagName(),
src.attr("abs:src")));
content.add("" + String.format("%s:%s",
src.tagName(),
src.attr("abs:src")));
}
}
runOnUiThread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < content.size(); i++)
textView.setText(content.get(i));
}
});
}
catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
}
18.使用jsoup解析KuGou
package com.example.getkugoumusic;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.util.ArrayList;
import java.util.List;
//1.访问http://m.kugou.com获取网页源码
//2.然后通过选择器进行过滤,过滤出歌曲列表中的id属性
//3.提取其中的id值为songs_BB8BF48B08C0AEC4F8058EB95C8285B9,提取出其中的hash值
//4.构造访问服务器的url = “http://m.kugou.com/app/i/getSongInfo.php?cmd=playInfo&hash=
// “+id的hash值 + “&from=mkugou”,采用GET方式发送
//5.获取从服务端返回的json格式数据
//6.构造歌曲信息java bean对象,解析json数据
//7.通过返回的json数据获取其中的歌曲资源的url,访问资源,保存到本地文件中
//8.测试文件是否可用。
public class MainActivity extends AppCompatActivity {
private List strIDList;
private List docsList;
private List kugouMusicInfosList;
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
visitKugou();
textView = (TextView) findViewById(R.id.text1);
}
//访问http://m.kugou.com获取新歌列表中的li标签的id属性和id值
public void visitKugou(){
//创建线程
new Thread(){
@Override
public void run() {
super.run();
//定义path
String path = "http://m.kugou.com";
try {
//使用jsoup连接Kugou,设置代理及超时
Document doc = Jsoup.connect(path).userAgent("Mozilla/5.0 (Linux;" +
" Android 6.0;" +
" Nexus 5 Build/MRA58N) AppleWebKit/537.36" +
" (KHTML, like Gecko) Chrome/58.0.3029.110 Mobile Safari/537.36").
timeout(5000).
get();
//设置选择器,查找li标签中的id属性
Elements liID = doc.select("li[id]");
//测试输出
System.out.println(String.format("li:%d", liID.size()));
//使用list保存提取出来的strID
strIDList = new ArrayList<>();
for (Element li : liID){
if (li.tagName().equals("li")){
System.out.println("" + String.format("%s:%s",
li.tagName(),
li.attr("id")));
String strID = li.attr("id");
int begin = strID.indexOf("_") + 1;
strID = strID.substring(begin, 38);
System.out.println(strID);
strIDList.add(strID);
}
}
//构造访问服务器的URL采用get方式
//“http://m.kugou.com/app/i/getSongInfo.php?cmd=playInfo&hash=
// “+id的hash值 + “&from=mkugou”,采用GET方式发送
//创建一个list保存这个对象
kugouMusicInfosList = new ArrayList();
for (int i = 0; i < strIDList.size(); i++)
{
String strPath = "http://m.kugou.com/app/i/getSongInfo.php?cmd=playInfo&hash="
+ strIDList.get(i) + "&from=mkugou";
// docsList = new ArrayList();
//使用构造好的url访问服务器,并接收返回的json数据,并保存在docList中
Document docs = Jsoup.connect(strPath).userAgent("Mozilla/5.0 (Linux;" +
" Android 6.0;" +
" Nexus 5 Build/MRA58N) AppleWebKit/537.36" +
" (KHTML, like Gecko) Chrome/58.0.3029.110 Mobile Safari/537.36").
timeout(5000).
get();
//docsList.add(docs);
//创建一个MusicInfo对象
final KugouMusicInfo kugouMusicInfo = new KugouMusicInfo();
//对获取到的docs字符串进行提取,取得json格式数据
String strDocs = docs.toString();
int begin = strDocs.indexOf("") + "".length();
int end = strDocs.indexOf("");
strDocs = strDocs.substring(begin, end);
//json解析
//获取json对象
JSONObject jsonObject = new JSONObject(strDocs);
//根据key获取value
String songName = jsonObject.getString("songName");
kugouMusicInfo.setSongName(songName);
String singerName = jsonObject.getString("singerName");
kugouMusicInfo.setSingerName(singerName);
String fileSize = jsonObject.getString("fileSize");
kugouMusicInfo.setFileSize(fileSize);
String musicUrl = jsonObject.getString("url");
kugouMusicInfo.setMusicUrl(musicUrl);
String imgUrl = jsonObject.getString("imgUrl");
kugouMusicInfo.setImgUrl(imgUrl);
String extName = jsonObject.getString("extName");//音乐类型
kugouMusicInfo.setExtName(extName);
String timeLength = jsonObject.getString("timeLength");
kugouMusicInfo.setTimeLength(timeLength);
System.out.println(kugouMusicInfo.toString());
kugouMusicInfosList.add(kugouMusicInfo);
//使用ui线程将数据显示在界面上
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText(kugouMusicInfo.toString());
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
}