为Android手机设置唯一ID

发布于 2025-01-03 19:38:01 字数 6499 浏览 1 评论 0原文

我试图为手机设置一个唯一的 ID,但每次用户启动按钮时,它都会生成一个新 ID 并将其发送到数据库。该应用程序将跟踪用户的位置,我想设置一次 ID,以便每次启动跟踪时,用户将始终拥有相同的 ID。现在,程序将发送 ID,并且每次发送时都会保持不变。然而,当用户返回主屏幕并返回屏幕以启动跟踪时,就会出现问题。以下是事件示例:

  1. 用户启动跟踪
  2. 用户返回主屏幕(原始 ID 丢失)
  3. 用户返回屏幕并使用按钮启动跟踪
  4. 用户再次启动跟踪(这会生成新 ID)

我想保留该 ID每次用户启动跟踪时都会生成一个新的跟踪。关于如何做到这一点有什么想法吗?这是一些可能有帮助的代码。

public class SendAlert extends Activity {


    private Button help_button;
    private TextView latitude; 
    private TextView longitude;
    private TextView id;
    Button sendButton;
    EditText msgTextField;

    String uuid = UUID.randomUUID().toString();

    private LocationManager locManager;
    private LocationListener locListener;

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

        SharedPreferences shared = getSharedPreferences("PEOPLE_PREFERENCES", MODE_PRIVATE);
        final String first = shared.getString("FIRSTNAME", "");
        final String last = shared.getString("LASTNAME", "");
        final long phone = shared.getLong("PHONE", 0);
        final String city = shared.getString("CITY", "");
        final int zip = shared.getInt("ZIP", 0);

        help_button = (Button)findViewById(R.id.button1);
        latitude = (TextView)findViewById(R.id.label_latitude);
        longitude = (TextView)findViewById(R.id.label_longitude);
        id = (TextView)findViewById(R.id.label_id);

        help_button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                startLocation();
                //id.setText(String.valueOf(uuid));

                sendId(first, last, phone, city, zip);
            }
        });
    }

    private void startLocation()
    {

        //We get a reference to the LocationManager
        locManager = 
            (LocationManager)getSystemService(Context.LOCATION_SERVICE);

        //We get the last known position
        Location loc = 
            locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        //We show the last known position
        showPosition(loc);

        //We checked to receive updates from the position
        locListener = new LocationListener() {
            public void onLocationChanged(Location location) {
                showPosition(location);
            }
            public void onProviderDisabled(String provider){
                //labelState.setText("Provider OFF");
            }
            public void onProviderEnabled(String provider){
                //labelState.setText("Provider ON ");
            }
            public void onStatusChanged(String provider, int status, Bundle extras){
                //Log.i("", "Provider Status: " + status);
                //labelState.setText("Provider Status: " + status);
            }
        };

        locManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER, 0, 0, locListener);
    }

    private void showPosition(Location loc) {
        if(loc != null)
        {
            latitude.setText(String.valueOf(loc.getLatitude()));
            longitude.setText(String.valueOf(loc.getLongitude()));
            id.setText(String.valueOf(uuid));
            Log.i("", String.valueOf(loc.getLatitude() + " - " + String.valueOf(loc.getLongitude())));


            send(latitude);


        }
        else
        {
            latitude.setText("Latitude: No Data");
            longitude.setText("Longitude: No Data");
        }   
    }

    private void send(View v)
    {
        // get the message from the message text box
        //String msg = latitude.getText().toString() + "," + longitude.getText().toString(); s
        String lat = latitude.getText().toString(); 
        String lon = longitude.getText().toString(); 

        // make sure the fields are not empty
        //if (lat.length()>0)
        if (lat != "0" && lon != "0")   
        {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://www.example.com/receive.php");
         try {
           List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); //changed to 4
           nameValuePairs.add(new BasicNameValuePair("lat", lat)); //changed "message" to "lat" changed "msg" to "lat"
           nameValuePairs.add(new BasicNameValuePair("lon", lon)); //added this line
           nameValuePairs.add(new BasicNameValuePair("id", uuid));
           httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
           httpclient.execute(httppost);
           //msgTextField.setText(""); // clear text box
         } catch (ClientProtocolException e) {
             // TODO Auto-generated catch block
         } catch (IOException e) {
             // TODO Auto-generated catch block
         }

        }
        else
        {
            // display message if text fields are empty
            Toast.makeText(getBaseContext(),"All field are required",Toast.LENGTH_SHORT).show();
        }

    }

    private void sendId(String first, String last, long phone, String city, int zip)
    {
        // get the message from the message text box
        String user_id = id.getText().toString(); 

        // make sure the fields are not empty
        //if (lat.length()>0)
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://www.example.com/receive_user.php");
         try {
           List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); //changed to 4
           nameValuePairs.add(new BasicNameValuePair("id", user_id));
           nameValuePairs.add(new BasicNameValuePair("firstname", first));
           nameValuePairs.add(new BasicNameValuePair("lastname", last));
           nameValuePairs.add(new BasicNameValuePair("phone", Long.toString(phone)));
           nameValuePairs.add(new BasicNameValuePair("city", city));
           nameValuePairs.add(new BasicNameValuePair("zip", Integer.toString(zip)));

           httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
           httpclient.execute(httppost);
           //msgTextField.setText(""); // clear text box
         } catch (ClientProtocolException e) {
             // TODO Auto-generated catch block
         } catch (IOException e) {
             // TODO Auto-generated catch block
         }

        }

    }

I'm trying to set a unique ID for a phone, but each time the user initiates the button, it generates a new ID and sends it to the database. The app will track the user's location and I'd like to set the ID once so that each time the tracking is initiated, the user will always have the same ID. Right now, the program will send the ID and it will stay the same each time it is sent. The problem however, occurs when a user goes back to the main screen, and returns to the screen to initiate tracking. Here is an example of events:

  1. User initiates tracking
  2. User goes back to main screen (original ID is lost)
  3. User returns to screen with button to initiate tracking
  4. User initiates tracking again (this generates a new ID)

I would like to retain the ID instead of generating a new one each time the user initiates tracking. Any thoughts on how to do this? Here is some code that may help.

public class SendAlert extends Activity {


    private Button help_button;
    private TextView latitude; 
    private TextView longitude;
    private TextView id;
    Button sendButton;
    EditText msgTextField;

    String uuid = UUID.randomUUID().toString();

    private LocationManager locManager;
    private LocationListener locListener;

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

        SharedPreferences shared = getSharedPreferences("PEOPLE_PREFERENCES", MODE_PRIVATE);
        final String first = shared.getString("FIRSTNAME", "");
        final String last = shared.getString("LASTNAME", "");
        final long phone = shared.getLong("PHONE", 0);
        final String city = shared.getString("CITY", "");
        final int zip = shared.getInt("ZIP", 0);

        help_button = (Button)findViewById(R.id.button1);
        latitude = (TextView)findViewById(R.id.label_latitude);
        longitude = (TextView)findViewById(R.id.label_longitude);
        id = (TextView)findViewById(R.id.label_id);

        help_button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                startLocation();
                //id.setText(String.valueOf(uuid));

                sendId(first, last, phone, city, zip);
            }
        });
    }

    private void startLocation()
    {

        //We get a reference to the LocationManager
        locManager = 
            (LocationManager)getSystemService(Context.LOCATION_SERVICE);

        //We get the last known position
        Location loc = 
            locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        //We show the last known position
        showPosition(loc);

        //We checked to receive updates from the position
        locListener = new LocationListener() {
            public void onLocationChanged(Location location) {
                showPosition(location);
            }
            public void onProviderDisabled(String provider){
                //labelState.setText("Provider OFF");
            }
            public void onProviderEnabled(String provider){
                //labelState.setText("Provider ON ");
            }
            public void onStatusChanged(String provider, int status, Bundle extras){
                //Log.i("", "Provider Status: " + status);
                //labelState.setText("Provider Status: " + status);
            }
        };

        locManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER, 0, 0, locListener);
    }

    private void showPosition(Location loc) {
        if(loc != null)
        {
            latitude.setText(String.valueOf(loc.getLatitude()));
            longitude.setText(String.valueOf(loc.getLongitude()));
            id.setText(String.valueOf(uuid));
            Log.i("", String.valueOf(loc.getLatitude() + " - " + String.valueOf(loc.getLongitude())));


            send(latitude);


        }
        else
        {
            latitude.setText("Latitude: No Data");
            longitude.setText("Longitude: No Data");
        }   
    }

    private void send(View v)
    {
        // get the message from the message text box
        //String msg = latitude.getText().toString() + "," + longitude.getText().toString(); s
        String lat = latitude.getText().toString(); 
        String lon = longitude.getText().toString(); 

        // make sure the fields are not empty
        //if (lat.length()>0)
        if (lat != "0" && lon != "0")   
        {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://www.example.com/receive.php");
         try {
           List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); //changed to 4
           nameValuePairs.add(new BasicNameValuePair("lat", lat)); //changed "message" to "lat" changed "msg" to "lat"
           nameValuePairs.add(new BasicNameValuePair("lon", lon)); //added this line
           nameValuePairs.add(new BasicNameValuePair("id", uuid));
           httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
           httpclient.execute(httppost);
           //msgTextField.setText(""); // clear text box
         } catch (ClientProtocolException e) {
             // TODO Auto-generated catch block
         } catch (IOException e) {
             // TODO Auto-generated catch block
         }

        }
        else
        {
            // display message if text fields are empty
            Toast.makeText(getBaseContext(),"All field are required",Toast.LENGTH_SHORT).show();
        }

    }

    private void sendId(String first, String last, long phone, String city, int zip)
    {
        // get the message from the message text box
        String user_id = id.getText().toString(); 

        // make sure the fields are not empty
        //if (lat.length()>0)
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://www.example.com/receive_user.php");
         try {
           List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); //changed to 4
           nameValuePairs.add(new BasicNameValuePair("id", user_id));
           nameValuePairs.add(new BasicNameValuePair("firstname", first));
           nameValuePairs.add(new BasicNameValuePair("lastname", last));
           nameValuePairs.add(new BasicNameValuePair("phone", Long.toString(phone)));
           nameValuePairs.add(new BasicNameValuePair("city", city));
           nameValuePairs.add(new BasicNameValuePair("zip", Integer.toString(zip)));

           httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
           httpclient.execute(httppost);
           //msgTextField.setText(""); // clear text box
         } catch (ClientProtocolException e) {
             // TODO Auto-generated catch block
         } catch (IOException e) {
             // TODO Auto-generated catch block
         }

        }

    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

煞人兵器 2025-01-10 19:38:01

正如之前的海报所指出的,您可以访问 TelephonyManager 等并获取唯一的设备标识符。但值得注意的是,此信息的存在因设备而异 - 上述 TelephonyManager.getID() 可能返回 null。

如果您的设备具有电话功能(例如,目前没有 SIM 卡的某些平板电脑或手机则不具备电话功能),那么它可能具有 IMSI 和 IMEI,您可以将其用作唯一 ID 的基础。最佳实践应该是您不要直接使用它,因为它是个人信息 - 也许使用它的哈希值或校验和。

上述方法(而不是纯粹的专有计算)的优点是 ID 唯一性的可能性很高 - 因为源(例如 IMEI)已知是唯一的 - 并且它可以动态重复计算,而不是通过可以存储在任何地方。

As a previous poster points out, you can access e.g. TelephonyManager and get a unique device identifier. However it is important to note that the presence of this information varies by device - the aforementioned TelephonyManager.getID() may return null.

If your device is capable of telephony - and for example some tablets or phones currently without SIM are not - then it is likely to have an IMSI and IMEI which you could use as the basis for a unique ID. Best practice should be that you do NOT use this directly because it is personal information - perhaps use a hash or checksum of it.

The advantage of the above, rather than a purely proprietary calculation, is the high chance of uniqueness of the ID - because the source (e.g. IMEI) is already known to be unique - and that it can be repeatably calculated on the fly rather than having to be stored anywhere.

つ可否回来 2025-01-10 19:38:01

仅生成一次 ID 并将其保存在某个位置(文件、数据库...)。

  1. 检查已保存的 ID 是否存在。
  2. 如果是的话,请阅读它。转至步骤 5。
  3. 生成 ID。
  4. 保存身份证。
  5. 发送身份证。

Generate ID only once and save it somewhere (file, DB...).

  1. Check if a saved ID exists.
  2. If it does, read it. Go to step 5.
  3. Generate ID.
  4. Save ID.
  5. Send ID.
如痴如狂 2025-01-10 19:38:01

这是一种非常不同的方法,您可能不会喜欢它,因为每个 Android 设备都有一个唯一的 id,只需使用该 id,您可以从 telephonymanager 对象并调用 getid 方法获取此 id。当您收到该 id 时,将该 id 保存在共享首选项中并在需要时使用它

its a very different approach may be u will not like it , as every android device have a unique id just use that id , you can get this id from telephonymanager object and calling getid method. when u receive that id save that id in sharedpreferences and use it whenever is required

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文