【问题标题】:send String from one class to a activity将字符串从一个类发送到一个活动
【发布时间】:2016-02-03 20:55:45
【问题描述】:

我的应用程序在输入位置时使用地理围栏通知用户,当用户输入位置时会显示通知。 我试图让触发地理围栏将它们转换为字符串,然后将它们发送到另一个活动,以便它们可以显示在列表视图中。 我已经在线观看了有关如何制作列表视图以及如何使用意图发送数据的教程,但我尝试做的似乎不起作用。

编辑 我正在使用另一个类 MainActivity 的 startActivity 意图启动列表视图 PageActivity。

目标

如果用户从任何地方(尤其是应用程序外部)单击通知,它将打开应用程序,列表视图中填充有地理围栏详细信息。如果用户打开应用程序只是从启动器打开应用程序,那么同样会发生。要填充已触发的任何地理围栏的列表。

GeofenceTransitionsIntentService 类:

public class GeofenceTransitionsIntentService extends IntentService {

    protected static final String TAG = "GeofenceTransitionsIS";



    /**
     * This constructor is required, and calls the super IntentService(String)
     * constructor with the name for a worker thread.
     */
    public GeofenceTransitionsIntentService() {
        // Use the TAG to name the worker thread.
        super(TAG);
    }


    @Override
    public void onCreate() {
        super.onCreate();
    }

    /**
     * Handles incoming intents.
     * @param intent sent by Location Services. This Intent is provided to Location
     *               Services (inside a PendingIntent) when addGeofences() is called.
     */
    @Override
    protected void onHandleIntent(Intent intent) {

        GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
        if (geofencingEvent.hasError()){
            String errorMessage = GeofenceErrorMessages.getErrorString(this,
                    geofencingEvent.getErrorCode());
            Log.e(TAG, errorMessage);
            return;
        }

        // Get the Transistion Type
        int geofenceTransition = geofencingEvent.getGeofenceTransition();

        // Test that the reported transisition was of interest.
        if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER ||
                geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {

            // Get the geofences that were triggered. A single event can trigger multiple geofences.
            List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences();

            // Get the transistion details as a String.
            String geofenceTransitionDetails = getGeofenceTransitionDetails(
                    this,
                    geofenceTransition,
                    triggeringGeofences
            );


            headsUpSmsNotifaction(geofenceTransitionDetails);


            Intent i = new Intent(this, listPageActivty.class);
            i.putExtra("intentKey",geofenceTransitionDetails);



            Log.i(TAG, geofenceTransitionDetails);
        } else{
            // Log the error
            Log.e(TAG, getString(R.string.geofence_transition_invalid_type, geofenceTransition));

        }

    }


    /**
     * Gets transition details and returns them as a formatted string.
     *
     * @param context               The app context.
     * @param geofenceTransition    The ID of the geofence transition.
     * @param triggeringGeofences   The geofence(s) triggered.
     * @return                      The transition details formatted as String.
     */

    private String getGeofenceTransitionDetails(Context context, int geofenceTransition, List<Geofence> triggeringGeofences) {
        String geofenceTransitionString = getTransitionString(geofenceTransition);

        // Get the Ids of each geofence that was triggered.
        ArrayList triggeringGeofencesIdsList = new ArrayList();
        for (Geofence geofence : triggeringGeofences) {
            triggeringGeofencesIdsList.add(geofence.getRequestId());
        }

        String triggeringGeofencesIdsString = TextUtils.join(", ", triggeringGeofencesIdsList);


        return  geofenceTransitionString + ": "  + triggeringGeofencesIdsString;
    }

    /**
     * Posts a notification in the notification bar when a transition is detected.
     * If the user clicks the notification, control goes to the MainActivity.
     */


    private void headsUpSmsNotifaction(String notificationDetails){

        // Create an explicit content Intent that starts the main Activity.
        Intent notificationIntent = new Intent(this, sendSmsReceiver.class);
        PendingIntent notificationPendingIntent = PendingIntent.getBroadcast(this,44,notificationIntent,0);

        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat mdfromat = new SimpleDateFormat("hh:ss | dd/ MM / yyyy");
        String strDate = mdfromat.format(calendar.getTime());



        // Get a notification builder that's compatible with platform versions >= 4
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

        // Define the notification settings.
        builder.setSmallIcon(R.mipmap.ic_launcher)
                // In a real app, you may want to use a library like Volley
                // to decode the Bitmap.
                .setLargeIcon(BitmapFactory.decodeResource(getResources(),
                        R.mipmap.ic_launcher))
                .setColor(Color.RED)
                .setPriority(NotificationCompat.PRIORITY_MAX)
                .setVibrate(new long[]{10,10,10})
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                .setContentTitle(notificationDetails)
                .setContentText(strDate)
                .addAction(R.mipmap.ic_launcher,"send",notificationPendingIntent)

                .setContentIntent(notificationPendingIntent);


        // Dismiss notification once the user touches it.
        //builder.setAutoCancel(true);

        // Get an instance of the Notification manager
        NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        // Issue the notification
        mNotificationManager.notify(0, builder.build());
    }



    /**
     * Maps geofence transition types to their human-readable equivalents.
     *
     * @param transitionType    A transition type constant defined in Geofence
     * @return                  A String indicating the type of transition
     */

    private String getTransitionString(int transitionType) {
        switch (transitionType) {
            case Geofence.GEOFENCE_TRANSITION_ENTER:
                return getString(R.string.geofence_transition_entered);
            case Geofence.GEOFENCE_TRANSITION_EXIT:
                return getString(R.string.geofence_transition_exited);
            default:
                return getString(R.string.unknown_geofence_transition);
        }

    }
}

listPageActivty 类:

public class listPageActivty extends AppCompatActivity {

    ListView listView;
    String[] ListElements = new String[]{"Android","PHP"};
    String item = "one";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_page_activty);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        listView = (ListView) findViewById(R.id.listView2);
        Button addBtn = (Button) findViewById(R.id.addBtn);

        final List<String> ListElementsArrayList = new ArrayList<String>(Arrays.asList(ListElements));
        final ArrayAdapter<String> adapter = new ArrayAdapter<String>(listPageActivty.this,android.R.layout.simple_list_item_1,ListElementsArrayList);

        listView.setAdapter(adapter);

      Bundle bundleData = getIntent().getExtras();
        if (bundleData == null){
            return;
        }

        String intentItem = bundleData.getString("intentKey");
        ListElementsArrayList.add(intentItem);


        addBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                ListElementsArrayList.add(item);
                adapter.notifyDataSetChanged();
            }
        });


    }

}

任何帮助将不胜感激,谢谢。

【问题讨论】:

  • 我建议开始一个新的 Android 项目只是为了帮助您了解如何在活动之间发送数据。
  • 我已经做到了,我正在尝试使用该项目中的代码并将该代码带入该项目
  • “我试图做的事情似乎不起作用。”当你运行你的应用程序时会发生什么?实际结果与您的预期有何不同?

标签: java android string android-intent android-geofence


【解决方案1】:

你必须改变这个:

Intent i = new Intent(this, listPageActivty.class);
i.putExtra("intentKey",geofenceTransitionDetails);

到这个:

Intent i = new Intent(this, listPageActivty.class);
i.putExtra("intentKey",geofenceTransitionDetails);
this.startActivity(i);

我想你刚刚离开了startActivity()

而在另一个Activity 中,你会得到这样的值:

String GeoTransitionDetails = getIntent().getExtras().getString("intentKey");

【讨论】:

  • 谢谢你这对我有用:) 这是因为我没有 startActivity 以我想使用的相同意图。不认为我需要它,因为我在不同的类中以不同的意图使用 startActivity。谢谢
  • 只是另一个简单的问题,当我从 listPage Activity 中出来然后再回到它时,那里的地理围栏列表项消失了。我必须做些什么才能让它持续存在吗?
  • 如果你愿意,可以将它保存在共享首选项中,明天我会帮你我现在去睡觉对不起
  • 因为没有机会看它,今晚将尝试共享偏好。现在必须做大学工作。不过谢谢你的回复,我稍后再回复你
  • 如果您遇到一些问题并在 StackOverflow 上提出问题,请随时给我链接,我会尽力解决您的疑问。 :)
【解决方案2】:

开始listPageActivty 活动你无处可去

替换

Intent i = new Intent(this, listPageActivty.class);
i.putExtra("intentKey",geofenceTransitionDetails);

Intent i = new Intent(getBaseContext(), listPageActivty.class);
i.putExtra("intentKey",geofenceTransitionDetails);
getApplication().startActivity(dialogIntent);

【讨论】:

  • 我在不同的活动“主要活动”中使用意图来启动 listPage 活动。我应该从该活动中添加额外内容吗?
  • 是的,你应该这样做。除非你打电话给startActivity
  • 那么将数据发送到主要活动,然后从他们的列表视图页面活动?
  • 为什么不能在有数据的情况下从这里开始活动。
猜你喜欢
  • 2018-09-24
  • 1970-01-01
  • 2014-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-11
  • 1970-01-01
  • 2013-09-28
相关资源
最近更新 更多