如何使活动输出字符串成为另一个活动输入字符串

时间:2015-05-29 19:48:08

标签: android

我在功能后创建了第一个吐司字符串的两个活动 第二个活动必须从第一个活动中获取此字符串,使其在TextView

中输入

这是我的第一个活动

package com.example.project;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;


import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class  AirportActivity extends Activity implements OnMapClickListener, OnMapLongClickListener, OnMarkerClickListener{    
    boolean markerClicked;
     PolylineOptions rectOptions;
     Polyline polyline;
      GoogleMap googleMap;
      List<LatLng> points;
     List<Polyline> polylines;
     String f = "" ;
      String[] placeNames = {"Cairo International Airport","Alexandria International Airport","Borg El Arab Airport",
                "Marsa Matrouh Airport","Sharm el-Sheikh International Airport","Taba International Airport","El Kharga Airport",
                "Assiut Airport","Luxor International Airport","Aswan International Airport","El Arish International Airport",
                "St. Catherine International Airport","Sharq Al-Owainat Airport","Abu Simbel Airport","Sohag International Airport",
                "Port Said Airport","El Tor Airport","Dakhla Oasis Airport","Marsa Alam International Airport","Cairo West Air Base","Almaza Air Force Base"};
         String[] placeNamesSnippet = {"Cairo International Airport1","Alexandria International Airport2","Borg El Arab Airport3", "Marsa Matrouh Airport4","Sharm el-Sheikh International Airport5","Taba International Airport6","El Kharga Airport7", "Assiut Airport8","Luxor International Airport9","Aswan International Airport10","El Arish International Airport11", "St. Catherine International Airport12","Sharq Al-Owainat Airport13","Abu Simbel Airport14","Sohag International Airport15", "Port Said Airport16","El Tor Airport17","Dakhla Oasis Airport18","Marsa Alam International Airpor19t","Cairo West Air Bas20e","Almaza Air Force Base21"};
         Double[] placeLatitude =  {30.111370, 31.192553, 30.917138,31.324435,27.978620,29.590988,27.188222,27.047695, 25.670264,
                23.960397,31.076449,28.684537,22.580600,22.375813,26.331926,31.281150,28.208842,25.688581,25.558141,
                30.116704,30.095975};
         Double[] placeLongitude = {31.413910, 29.953141,29.693375, 27.222200,34.393354,34.778946 , 33.800840, 31.013473 , 32.704063,
                32.821163,33.832256,34.062882, 28.720754, 31.611667,31.728437,32.242223,33.645257,28.972356,34.582821,
                30.916667,31.362748};

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
    setContentView(R.layout.airportactivity);

    googleMap = ((MapFragment)getFragmentManager().findFragmentById(
            R.id.mapView)).getMap();
    //googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//  googleMap.animateCamera(CameraUpdateFactory.newLatLng(point));
    points = new ArrayList<LatLng>();
    polylines = new ArrayList<Polyline>();
    setmap();


}   private void setmap()
{
    for(int i = 0 ; i<21;i++)
      {
          googleMap.addMarker(new MarkerOptions()
                  .snippet(placeNamesSnippet[i])
                  .position(new LatLng(placeLatitude[i], placeLongitude[i]))
                  .title(placeNames[i]));

        points.add(new LatLng(placeLatitude[i], placeLongitude[i]));
      }
     markerClicked = false; 
      googleMap.setOnMapLongClickListener(this);
      googleMap.setOnMarkerClickListener(new OnMarkerClickListener() {

        @Override
        public boolean onMarkerClick(Marker arg0) {
            // TODO Auto-generated method stub
            points.add(arg0.getPosition());
            googleMap.clear();
            setmap();
             FindShortestPath();
              markerClicked = true;
            return false;
        }
    });
 }
public void dis (int[] p)
{
    double x = 0 ;
    double s= 0;
    int numOfNodes = points.size();
    for (int index = 0 ; index < numOfNodes-1 ; index++)
    {

    x  = distance2(points.get(p[index]).latitude,points.get(p[index]).longitude , points.get(p[index+1]).latitude,points.get(p[index+1]).longitude, 'K');
    s = s+x ;
    }
    Toast.makeText(this, "Total distance of path  = " + s+"KM" , Toast.LENGTH_SHORT).show();
    f = String.valueOf(s); 
    }
        /*::  are available at http://www.geodatasource.com                          :*/
        /*::  Official Web site: http://www.geodatasource.com                        :*/

        private double distance2(double lat1, double lon1, double lat2, double lon2, char unit) {
        double theta = lon1 - lon2;

        double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
        dist = Math.acos(dist);

        dist = rad2deg(dist);

        dist = dist * 60 * 1.1515;
        if (unit == 'K') {

        dist = dist * 1.609344;

        } 
        return (dist);

        }

        /*::  This function converts decimal degrees to radians             :*/

        private double deg2rad(double deg) {

        return (deg * Math.PI / 180.0);

        }
        /*::  This function converts radians to decimal degrees             :*/
        /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
        private double rad2deg(double rad) {
        return (rad * 180 / Math.PI);
        }

public void onClick(View view) {
    startActivity(new Intent("net.learn2develop.MAIN"));
    }    
public static double distance(LatLng StartP, LatLng EndP) {
    double lat1 = StartP.latitude;
    double lat2 = EndP.latitude;
    double lon1 = StartP.longitude;
    double lon2 = EndP.longitude;
    double dLat = Math.toRadians(lat2-lat1);
    double dLon = Math.toRadians(lon2-lon1);
    double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
    Math.sin(dLon/2) * Math.sin(dLon/2);
    double c = 2 * Math.asin(Math.sqrt(a));
    return 6366000 * c;
}
// calculate distances matrix then get shortest path then call draw
public void FindShortestPath()
{
TSPNearestNeighbour tsp = new TSPNearestNeighbour();
int adjacencyMatrix[][] = new int[points.size()][];
int counter = 0,innerCounter ;
int[] result = new int[points.size()];

for(LatLng point : points)
{
    innerCounter=0;
    adjacencyMatrix[counter] = new int[points.size()];
    for(LatLng point1 : points)
    {
        if(point.equals(point1))
        {
            adjacencyMatrix[counter][innerCounter] =  0;
        }
        else 
            adjacencyMatrix[counter][innerCounter] =(int) distance(point,point1);
            innerCounter ++;
    }
    counter ++;
}
result = tsp.tsp(adjacencyMatrix);
DrawShortestPath(result);
dis(result);

}
//draws the shortest path with markers 
public void DrawShortestPath(int[] path)
{

    googleMap.clear();

int numOfNodes = points.size();
for(LatLng point : points)
{
    googleMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
               .position(point));
}
for (int index = 0 ; index < numOfNodes-1 ; index++)
{
     googleMap.addPolyline(new PolylineOptions()
.add(points.get(path[index]), points.get(path[index+1]))
.width(3)
.color(Color.RED));
}
}
class TSPNearestNeighbour
{
private int numberOfNodes;
private Stack<Integer> stack;

public TSPNearestNeighbour()
{
    stack = new Stack<Integer>();
}

public int[] tsp(int adjacencyMatrix[][])
{
    numberOfNodes = adjacencyMatrix[0].length ;
    int[] result = new int[adjacencyMatrix[0].length];
    int resultCounter = 1;
    int[] visited = new int[numberOfNodes];
    visited[0] = 1;
    stack.push(0);
    int element, dst = 0, i;
    int min = Integer.MAX_VALUE;
    boolean minFlag = false;
    result[0] = 0;

    //System.out.print(1 + "\t");

    while (!stack.isEmpty())
    {
        element = stack.peek();
        i = 0;
        min = Integer.MAX_VALUE;
        while (i < numberOfNodes)
        {
            if (adjacencyMatrix[element][i] > 1 && visited[i] == 0)
            {
                if (min > adjacencyMatrix[element][i])
                {
                    min = adjacencyMatrix[element][i];
                    dst = i;
                    minFlag = true;
                }
            }
            i++;
        }
        if (minFlag)
        {
            visited[dst] = 1;
            stack.push(dst);
            result[resultCounter] = dst;
            resultCounter++;
            //System.out.print(dst + "\t");
            minFlag = false;
            continue;
        }
        stack.pop();
    }
    return result;
}

}
@Override
public void onMapClick(LatLng arg0) {
    // TODO Auto-generated method stub

}


@Override
public void onMapLongClick(LatLng arg0) {
    // TODO Auto-generated method stub

}
@Override
public boolean onMarkerClick(Marker arg0) {
    // TODO Auto-generated method stub
    return false;
}
}

注意:输出“s”是double,我将其转换为字符串

第二项活动

package com.example.project;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.gsm.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class SMS extends Activity 
{
    Button btnSendSMS;
    EditText txtPhoneNo;
    AirportActivity air =  new AirportActivity();

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);        
        btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
        txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
        final TextView ltextview=(TextView) findViewById(R.id.textView1); 
        /*
        Intent sendIntent = new Intent(Intent.ACTION_VIEW);
        sendIntent.putExtra("sms_body", "Content of the SMS goes here..."); 
        sendIntent.setType("vnd.android-dir/mms-sms");
        startActivity(sendIntent);
        */
        ltextview.setText(air.f); 
        btnSendSMS.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View v) 
            {               
                String phoneNo = txtPhoneNo.getText().toString();
                air.f = ltextview.getText().toString(); 

                if (phoneNo.length()>0 && air.f.length()>0)                
                    sendSMS(phoneNo, air.f);                
                else
                    Toast.makeText(getBaseContext(), 
                        "Please enter both phone number and message.", 
                        Toast.LENGTH_SHORT).show();
            }
        });        
    }
    public String take(String s)
    {
        air.f = s;

        return air.f;

    }
    //---sends a SMS message to another device---
    private void sendSMS(String phoneNumber, String message)
    {      
        /*
        PendingIntent pi = PendingIntent.getActivity(this, 0,
                new Intent(this, test.class), 0);                
            SmsManager sms = SmsManager.getDefault();
            sms.sendTextMessage(phoneNumber, null, message, pi, null);        
        */

        String SENT = "SMS_SENT";
        String DELIVERED = "SMS_DELIVERED";

        PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
            new Intent(SENT), 0);

        PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
            new Intent(DELIVERED), 0);

        //---when the SMS has been sent---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS sent", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        Toast.makeText(getBaseContext(), "Generic failure", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NO_SERVICE:
                        Toast.makeText(getBaseContext(), "No service", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NULL_PDU:
                        Toast.makeText(getBaseContext(), "Null PDU", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                        Toast.makeText(getBaseContext(), "Radio off", 
                                Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }, new IntentFilter(SENT));

        //---when the SMS has been delivered---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS delivered", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case Activity.RESULT_CANCELED:
                        Toast.makeText(getBaseContext(), "SMS not delivered", 
                                Toast.LENGTH_SHORT).show();
                        break;                      
                }
            }
        }, new IntentFilter(DELIVERED));        

        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);               
    }    
}

我必须做些什么来使消息成为第一个活动的祝酒词? 抱歉英文不好

1 个答案:

答案 0 :(得分:0)

使用Intents传递数据, 你要做的是:创建一个Intent对象并用你的字符串加载它作为额外的,然后开始新的活动,如下所示:

Intent intent = new Intent("ActivityA.this", "ActivityB.class");
intent.putExtra("key", "your string");
startActivity(intent);

在第二个活动中获取您已经发送的额外内容并按照您的要求执行:

String myString = getIntents().getExtras().getString("key");

注意&#34;键&#34;是您的字符串值的键,或者您可以将其视为从其他附加项中标识字符串的标记,因此您可以将其命名为与String相关的内容。

您还可以访问http://developer.android.com/guide/components/intents-filters.html了解有关Intents的更多信息。