【问题标题】:Sending data with intent-filter使用意图过滤器发送数据
【发布时间】:2014-12-20 23:58:43
【问题描述】:

google play 等市场如何与Intent-filter 配合使用?
我对intent-filter有点了解,但我不知道如何使用它发送数据?
如何使用相关的应用数据启动一个活动?从Broadcast Receiver 使用吗?
当我浏览应用 X 并想下载它时,我的已安装市场启动时会显示来自 complete using action 对话框的 X 应用信息。
我没有知道如何导航到相关页面吗?
谁能解释一下或提供一些例子?
谢谢

【问题讨论】:

    标签: android android-intent broadcastreceiver intentfilter


    【解决方案1】:

    字符串文件名 = sourceFileUri;

        HttpURLConnection conn = null;
        DataOutputStream dos = null; 
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        File sourceFile = new File(sourceFileUri);
    
        if (!sourceFile.isFile()) {
            dialog = ProgressDialog.show(CameraPhotoCapture.this, "", "Uploading file...", true);
            dialog.dismiss();
    
            Log.e("uploadFile", "Source File not exist :" );
    
            runOnUiThread(new Runnable() {
                public void run() {
                    //   messageText.setText("Source File not exist :"                             +uploadFilePath + "" + uploadFileName);
                }
            });
    
            return 0;
        }
        else
        {
            try {
    
                // open a URL connection to the Servlet
                FileInputStream fileInputStream = new FileInputStream(sourceFile);
                URL url = new URL(upLoadServerUri);
    
    
    
    
                conn = (HttpURLConnection) url.openConnection();
                conn.setDoInput(true); 
                conn.setDoOutput(true);
                conn.setUseCaches(false); 
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                conn.setRequestProperty("uploaded_file", fileName);
    
                dos = new DataOutputStream(conn.getOutputStream());
    
                dos.writeBytes(twoHyphens + boundary + lineEnd);
                dos.writeBytes("Content-Disposition: form-data; name=uploaded_file;filename="
                        + fileName + "" + lineEnd);
    
                dos.writeBytes(lineEnd);
    
                // create a buffer of  maximum size
                bytesAvailable = fileInputStream.available();
    
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];
    
                // read file and write it into form...
                bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
    
                while (bytesRead > 0) {
    
                    dos.write(buffer, 0, bufferSize);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);  
    
                }
    
                // send multipart form data necesssary after file data...
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
    
                // Responses from the server (code and message)
                serverResponseCode = conn.getResponseCode();
                String serverResponseMessage = conn.getResponseMessage();
    
                Log.i("uploadFile", "HTTP Response is : "
                        + serverResponseMessage + ": " + serverResponseCode);
    
                if(serverResponseCode == 200){
    
                    runOnUiThread(new Runnable() {
                        public void run() {
    
    
                            File se = new File(full_path_name);
    
                            String ser = se.getName();
    
                            String string =full_path_name;
                            String[] parts = string.split("/");
                            String part1 = parts[0]; // 004
                            String part2 = parts[1]; 
                            String part3 = parts[2];
                            String part4 = parts[3];
                            String msg = "http://172.17.2.139/manimca/smartcomplaints/images/"+part4;
    
    
                            //    messageText.setText(msg);
                            Toast.makeText(CameraPhotoCapture.this, "File Upload Complete.",
                                    Toast.LENGTH_SHORT).show();
    
    
    
    
    
    
                            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    
                            nameValuePairs.add(new BasicNameValuePair("complaint_type", $complaint_type));
                            nameValuePairs.add(new BasicNameValuePair("complaint_details", $complaint_details));
                            nameValuePairs.add(new BasicNameValuePair("image_details", $image_details));
                            nameValuePairs.add(new BasicNameValuePair("latitude",$latitude));
                            nameValuePairs.add(new BasicNameValuePair("longitude", $longitude));
                            nameValuePairs.add(new BasicNameValuePair("area", $area));
                            nameValuePairs.add(new  BasicNameValuePair("datetime", myDate));
                            nameValuePairs.add(new  BasicNameValuePair("people_name", $people_name));
                            nameValuePairs.add(new  BasicNameValuePair("people_email", $people_email));
                            nameValuePairs.add(new  BasicNameValuePair("people_address", $people_address));
                            nameValuePairs.add(new  BasicNameValuePair("phoneno", $phoneno));
    
    
                            try
                            {
                                HttpClient httpclient = new DefaultHttpClient();
                                HttpPost httppost = new HttpPost("http://172.17.2.139/manimca/smartcomplaints/complaint_informations.php");
                                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                                HttpResponse response = httpclient.execute(httppost); 
                                HttpEntity entity = response.getEntity();
                                is = entity.getContent();
                                Log.e("pass 1", "connection success ");
                            }
    
                            catch(Exception e)
                            {
                                Log.e("Fail 1", e.toString());
                                Toast.makeText(getApplicationContext(), "Invalid IP Address",
                                        Toast.LENGTH_LONG).show();
                            }     
    
                            try
                            {
                                BufferedReader reader = new BufferedReader
                                        (new InputStreamReader(is,"iso-8859-1"),8);
                                StringBuilder sb = new StringBuilder();
                                while ((line = reader.readLine()) != null)
                                {
                                    sb.append(line + "\n");
                                }
                                is.close();
                                result = sb.toString();
                                Log.e("pass 2", "connection success ");
                            }
                            catch(Exception e)
                            {
                                Log.e("Fail 2", e.toString());
                            }     
    
                            try
                            {
                                JSONObject json_data = new JSONObject(result);
                                code=(json_data.getInt("code"));
    
                                if(code==1)
                                {
                                    Toast.makeText(getBaseContext(), "Inserted Successfully",
                                            Toast.LENGTH_SHORT).show();
                                }
                                else
                                {
                                    Toast.makeText(getBaseContext(), "Sorry, Try Again",
                                            Toast.LENGTH_LONG).show();
                                }
                            }
                            catch(Exception e)
                            {
                                Log.e("Fail 3", e.toString());
                            }
                        }
                    });               
                }   
                //close the streams //
                fileInputStream.close();
                dos.flush();
                dos.close();
                finish();
    
            } catch (MalformedURLException ex) {
    
                dialog.dismiss(); 
                ex.printStackTrace();
    
                runOnUiThread(new Runnable() {
                    public void run() {
                        //      messageText.setText("MalformedURLException Exception : check script url.");
                        Toast.makeText(CameraPhotoCapture.this, "MalformedURLException",
                                Toast.LENGTH_SHORT).show();
                    }
                });
    
                Log.e("Upload file to server", "error: " + ex.getMessage(), ex); 
            } catch (Exception e) {
    
                dialog.dismiss(); 
                e.printStackTrace();
    
                runOnUiThread(new Runnable() {
                    public void run() {
                        //    messageText.setText("Got Exception : see logcat ");
                        Toast.makeText(CameraPhotoCapture.this, "No Internet Connection ",
                                Toast.LENGTH_SHORT).show();
                    }
                });
                Log.e("Upload file to server Exception", "Exception : "
                        + e.getMessage(), e); 
            }
            dialog.dismiss();      
            return serverResponseCode;
    
        } // End else block
    }
    
    
    public void showMessgeAlert(String Message)
    {
        Toast.makeText(getApplicationContext(), Message, Toast.LENGTH_SHORT).show();
    }
    

    【讨论】:

      【解决方案2】:

      意图过滤器例如: 在以下代码中,用于将数据发送到另一个活动。

      活动一:

        Intent myintent=new Intent(this,MyListActivity.class);
          myintent.putExtra("latitude", latit);
          myintent.putExtra("longtitude", longet);
          myintent.putExtra("city", cityname);
          myintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
          startActivity(myintent);
      

      活动二:

          lat=getIntent().getExtras().getString("latitude").toString();
          longet=getIntent().getExtras().getString("longtitude").toString();
          city=getIntent().getExtras().getString("city").toString();
      

      【讨论】:

      • 感谢您的回复,但我想将数据从浏览器发送到我的应用程序。让我再次解释一下:假设您导航到 viber 主页并且想要下载它,当触摸获取 viber 按钮时,complete action using 对话框出现,当点击 google play 等市场时,您启动了带有相关 viber 页面的 google play 应用程序。不知道怎么弄?
      • 我理解你的想法。这是可能的。我正在将我的应用程序之间的图像上传到网站。我使用的是 php webservice。
      • 我正在获取该代码。为方便起见,请参考此代码。
      【解决方案3】:

      在 manifest 的 Activity 标签中添加 Intent 过滤器,这可以让其他应用在请求相应操作时转到相同的 Activity:

       <activity android:name="ShareActivity">
             <!-- filter for sending text or images; accepts SEND action and text or image data -->
              <intent-filter>
                  <action android:name="android.intent.action.SEND"/>
                  <category android:name="android.intent.category.DEFAULT"/>
                  <data android:mimeType="image/*"/>
                  <data android:mimeType="text/plain"/>
              </intent-filter>
          </activity>
      

      然后在您的活动中,处理意图:

      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
      
          setContentView(R.layout.main);
      
          // Get the intent that started this activity
          Intent intent = getIntent();
          Uri data = intent.getData();
      
          // Figure out what to do based on the intent type
          if (intent.getType().indexOf("image/") != -1) {
              // Handle intents with image data ...
          } else if (intent.getType().equals("text/plain")) {
              // Handle intents with text ...
          }
      }
      

      您还可以将结果返回给调用者活动(即,当其他应用程序使用 startActivityForResult 调用您的活动时):

      Intent result = new Intent("com.example.RESULT_ACTION", Uri.parse("content://result_uri");
      setResult(Activity.RESULT_OK, result);
      finish();
      

      【讨论】:

      • 感谢您的回复,我得到它是空的。如何从浏览器检测它?我不知道你的代码是什么意思。你能提供更多细节吗?
      • 与您从意图过滤器中捕获的操作相同吗?以下是您可以从其他应用中捕获的操作列表:sdk/platforms/android-x/data/broadcast_actions.txt
      • "如何从浏览器中检测到它?"如果浏览器使用 startActivity() 调用您的应用程序,则不能。但是,如果浏览器使用 getCallingActivity() 通过 startActivityForResult() 调用您的应用程序,您就可以获得它。 developer.android.com/reference/android/app/…
      • 如果你只想要包名,你有getCallingPackage()
      猜你喜欢
      • 2015-10-23
      • 2012-07-17
      • 2021-05-31
      • 2020-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-08
      • 1970-01-01
      相关资源
      最近更新 更多