使用intent-filter发送数据

时间:2014-10-25 06:32:12

标签: android android-intent broadcastreceiver intentfilter

Google Play等市场如何与Intent-filter一起使用?
我对intent-filter有一点了解,但我不知道如何发送数据?
如何使用相关应用数据启动活动?从Broadcast Receiver使用?
当我浏览应用 X ,并且我想下载它时,我的已安装市场使用complete using action对话框中的 X 应用信息启动。
我不知道如何导航到相关页面? 任何人都可以解释一下或提供一些例子吗?
感谢

3 个答案:

答案 0 :(得分:0)

意图过滤器Ex: 在下面的代码中用于将数据发送到另一个活动。

活动1:

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

活动2:

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

答案 1 :(得分:0)

String fileName = 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 :(得分:-1)

在清单的活动代码中添加意图过滤器,这可让其他应用在请求相应操作时转到同一活动:

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