android应用程序分享,蓝牙文件传输(代码)

    由于多数客户是手机盲,不知道如何快速安装apk软件到android手机上,故而公司提出开发一个利用无线在两台android手机上分享已安装软件的需求。
        近段时间在网上搜索关于蓝牙分享软件的例子,未果!
        发现android自带的examples里有个bluetoothChat的例子,里面关于蓝牙的调用例子看起来非常繁琐,先判断是否支持蓝牙,再判断蓝牙是否打开,再去搜索蓝牙设备,然后在配对,配对后发送信息。在两个手机上分别装了试试,发现根本无法发送信息。几天下来一无所获。最后无意中google了一下,看到一段极端简单的代码调用android自带的ACTION_SEND,居然可以了。
         避免更多的人绕弯路,现把android手机之间分享已安装软件的代码贴出,供大家参考。
 
主要代码:         
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.SimpleAdapter.ViewBinder;

public class MainActivity extends Activity implements OnClickListener{
    public static final String TAG = "AppListActivity";
    private ListView listView;
    private List<Map<String,Object>> list;

    /* (non-Javadoc)
     * @see android.app.Activity#onCreate(android.os.Bundle)
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.v(TAG,"created");
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.app_list);
        listView = (ListView)this.findViewById(R.id.listView1);
        list = new ArrayList<Map<String,Object>>();
        List<PackageInfo> appListInfo=this.getPackageManager().getInstalledPackages(0);
        for (PackageInfo p : appListInfo) {
            if(p.applicationInfo.sourceDir.startsWith("/system/app/")){
                continue;
            }
            Map<String,Object> map = new HashMap<String,Object>();
            Drawable icon = null;
            String appName= "";
            try{
                appName = this.getPackageManager().getApplicationLabel(p.applicationInfo).toString();
                icon = this.getPackageManager().getApplicationIcon(p.applicationInfo.packageName);
            }catch(Exception e){
                e.printStackTrace();
            }
            map.put("name", appName);
            map.put("package", p.applicationInfo.packageName);
            map.put("sourceDir", p.applicationInfo.sourceDir);
            map.put("icon",icon);
            list.add(map);
        }
        SimpleAdapter adapter = new SimpleAdapter(this,list,R.layout.app_list_item, new String[]{"name","icon"}, new int[]{R.id.tv_name,R.id.iv_icon});
        adapter.setViewBinder(new ViewBinder() {  
            public boolean setViewValue(View view, Object data, String textRepresentation) {  
            //判断是否为我们要处理的对象  
            if(view instanceof ImageView && data instanceof Drawable){  
                ImageView iv = (ImageView) view;  
                iv.setImageDrawable((Drawable)data);
                return true;  
            }else  
                return false;  
            }  
        });  
        listView.setAdapter(adapter);
        listView.setOnItemLongClickListener(new OnItemLongClickListener(){

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                if(list.get(position).get("sourceDir")!=null){
                    File f = new File(list.get(position).get("sourceDir").toString());
                    //调用android分享窗口
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_SEND);
                    intent.setType("*/*");
                    intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f));
                    startActivity(intent);
                }
                return false;
            }


        });
    }

    /* (non-Javadoc)
     * @see android.app.Activity#onDestroy()
     */
    @Override
    protected void onDestroy() {
        Log.v(TAG, "destroy");
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {

    }

}
 
界面截图:
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是一个示例代码,用于在 Android 平台上使用蓝牙传输文件并显示传输进度: ```java public class BluetoothTransferActivity extends AppCompatActivity { private static final int REQUEST_ENABLE_BLUETOOTH = 1; private static final int REQUEST_SELECT_FILE = 2; private BluetoothAdapter mBluetoothAdapter; private BluetoothDevice mBluetoothDevice; private BluetoothSocket mBluetoothSocket; private ProgressBar mProgressBar; private TextView mProgressText; private File mSelectedFile; private long mFileSize; private boolean mIsTransferInProgress; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_bluetooth_transfer); mProgressBar = findViewById(R.id.progress_bar); mProgressText = findViewById(R.id.progress_text); mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) { Toast.makeText(this, "Bluetooth is not available on this device", Toast.LENGTH_SHORT).show(); finish(); return; } if (!mBluetoothAdapter.isEnabled()) { Intent enableBluetoothIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBluetoothIntent, REQUEST_ENABLE_BLUETOOTH); return; } selectFile(); } private void selectFile() { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("*/*"); startActivityForResult(intent, REQUEST_SELECT_FILE); } private void setupBluetoothConnection() { mBluetoothDevice = mBluetoothAdapter.getRemoteDevice("00:11:22:33:44:55"); // Replace with your device address try { mBluetoothSocket = mBluetoothDevice.createRfcommSocketToServiceRecord(UUID.randomUUID()); mBluetoothSocket.connect(); } catch (IOException e) { Toast.makeText(this, "Failed to connect to Bluetooth device", Toast.LENGTH_SHORT).show(); e.printStackTrace(); finish(); } } private void startTransfer() { mIsTransferInProgress = true; try { InputStream inputStream = new FileInputStream(mSelectedFile); OutputStream outputStream = mBluetoothSocket.getOutputStream(); byte[] buffer = new byte[1024]; int length; long totalBytesRead = 0; while ((length = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, length); totalBytesRead += length; int progress = (int) (totalBytesRead * 100 / mFileSize); updateProgress(progress); } outputStream.flush(); inputStream.close(); outputStream.close(); mIsTransferInProgress = false; Toast.makeText(this, "File transfer complete", Toast.LENGTH_SHORT).show(); finish(); } catch (IOException e) { mIsTransferInProgress = false; Toast.makeText(this, "File transfer failed", Toast.LENGTH_SHORT).show(); e.printStackTrace(); finish(); } } private void updateProgress(final int progress) { runOnUiThread(new Runnable() { @Override public void run() { mProgressBar.setProgress(progress); mProgressText.setText(progress + "%"); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_ENABLE_BLUETOOTH) { if (resultCode == RESULT_OK) { selectFile(); } else { Toast.makeText(this, "Bluetooth must be enabled to transfer files", Toast.LENGTH_SHORT).show(); finish(); } } if (requestCode == REQUEST_SELECT_FILE) { if (resultCode == RESULT_OK) { Uri fileUri = data.getData(); String filePath = getRealPathFromUri(fileUri); mSelectedFile = new File(filePath); mFileSize = mSelectedFile.length(); mProgressBar.setMax(100); setupBluetoothConnection(); startTransfer(); } else { finish(); } } } private String getRealPathFromUri(Uri uri) { String[] projection = {MediaStore.Images.Media.DATA}; Cursor cursor = getContentResolver().query(uri, projection, null, null, null); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); String filePath = cursor.getString(column_index); cursor.close(); return filePath; } @Override protected void onDestroy() { super.onDestroy(); if (mIsTransferInProgress) { try { mBluetoothSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } } ``` 这个示例代码包含以下步骤: 1. 检查设备是否支持蓝牙,如果不支持则退出应用程序。 2. 检查蓝牙是否启用,如果未启用则请求启用。 3. 选择待传输的文件。 4. 连接到蓝牙设备。 5. 开始传输文件,更新进度条和进度文本。 6. 当传输完成或失败时,显示适当的消息并退出应用程序。 请注意,此示例代码仅用于演示目的。在实际应用程序中,您应该添加错误处理并确保正确关闭蓝牙连接。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

安果移不动

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值