android - 打开通知时如何在 map 上显示经纬度点?

标签 android google-maps android-notifications

我正在开发一个应用程序,因为我想在打开通知时显示 map ,我成功收到通知,但当我打开通知时,没有打开具有该经纬度值的 map 。

GCMintent 服务类

 public class GcmIntentService extends IntentService{

Context context;
public static int notify_no=0;

//System.currentTimeMillis();

private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
public static final String TAG = "GCM NOTIFICATION";

public GcmIntentService() {
    super("GcmIntentService");
    // TODO Auto-generated constructor stub
}

@Override
protected void onHandleIntent(Intent intent) {
    // TODO Auto-generated method stub
    Bundle extras = intent.getExtras();
    String msg = intent.getStringExtra("message");
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
    String messageType = gcm.getMessageType(intent);


     if (!extras.isEmpty()) {

         if (GoogleCloudMessaging.
                    MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
               // sendNotification(RegIdDTO.REG_ID,"Send error: " + extras.toString());
             sendNotification(this,msg);
            } else if (GoogleCloudMessaging.
                    MESSAGE_TYPE_DELETED.equals(messageType)) {
               // sendNotification(RegIdDTO.REG_ID,"Deleted messages on server: " +
               //         extras.toString());
                sendNotification(this,msg);
            // If it's a regular GCM message, do some work.
            } else if (GoogleCloudMessaging.
                    MESSAGE_TYPE_MESSAGE.equals(messageType)) {
                // This loop represents the service doing some work.
                for (int i=0; i<5; i++) {
                    Log.i(TAG, "Working... " + (i+1)
                            + "/5 @ " + SystemClock.elapsedRealtime());
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                    }
                }
                Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
                // Post notification of received message.
                //sendNotification("Received: " + extras.toString());
               // sendNotification(RegIdDTO.REG_ID,msg);
                sendNotification(this,msg);
                Log.i(TAG, "Received: " + extras.toString());
            }
        }
     GcmBroadcastReceiver.completeWakefulIntent(intent);
}


private static void sendNotification(Context context,String message) {
    int icon = R.drawable.ic_stat_gcm;
    long when = System.currentTimeMillis();
    NotificationCompat.Builder nBuilder;
    Uri alarmSound = RingtoneManager
            .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    nBuilder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("header")
            .setLights(Color.BLUE, 500, 500).setContentText(message)
            .setAutoCancel(true).setTicker("Notification from Traffic")
            .setVibrate(new long[] { 100, 250, 100, 250, 100, 250 })
            .setSound(alarmSound);
    String consumerid = null;
    Integer position = null;
           // write your click event here
       Intent resultIntent = new Intent(context, ShowMapActivity.class);

       resultIntent.putExtra("message", message);
      // resultIntent.setData(Uri.parse("content://"+when));


PendingIntent resultPendingIntent = PendingIntent.getActivity(context,
        notify_no, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        // Show the max number of notifications here
if (notify_no < 9) {
    notify_no = notify_no + 1;
} else {
    notify_no = 0;
}
 nBuilder.setContentIntent(resultPendingIntent);
 NotificationManager nNotifyMgr = (NotificationManager) context
        .getSystemService(context.NOTIFICATION_SERVICE);
 nNotifyMgr.notify(notify_no + 2, nBuilder.build());
}

}

显示 map 类

 public class ShowMapActivity extends FragmentActivity implements LocationListener {

     GoogleMap _googleMap;

    LatLng myPosition;
    LocationManager locationManger;


    TextView addressTextView,cTimeTextView;

        JSONObject json;
        GcmIntentService serv;
        Context mContext;

    Intent noticeIntent = getIntent();

    String lat;
    String lng;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_show_map);

    //addressTextView = (TextView)findViewById(R.id.addressId);
    //cTimeTextView   = (TextView)findViewById(R.id.ctimeId);

    String message = noticeIntent.getExtras().getString("message");

    try {
        json = new JSONObject(message);
        lat = json.getString("lat");

         Log.e("LLOONNGG", ""+lat);
        lng = json.getString("lng");

         Log.e("LLOONNGG", ""+lng);
        String adr = json.getString("address");
        addressTextView.setText(adr);


        String ctime = json.getString("ctime");
        cTimeTextView.setText(ctime);


    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


    _googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(
            R.id.map)).getMap(); 

    LocationManager service = (LocationManager)getSystemService(LOCATION_SERVICE);

    boolean enableGPS = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
    boolean enableWiFi= service.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

    if(!enableGPS || !enableWiFi){
        Toast.makeText(ShowMapActivity.this, "GPS signal not found", Toast.LENGTH_LONG).show();
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        startActivity(intent);
    }

    locationManger = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String provider = service.getBestProvider(criteria, true);


    service.requestLocationUpdates(provider, 0, 0, this);


    if(_googleMap==null){
        Toast.makeText(getApplicationContext(), "Google Map Not Available", Toast.LENGTH_LONG).show();
        }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.show_map, menu);
    return true;
}

@Override
public void onLocationChanged(Location location) {
    // TODO Auto-generated method stub

    //locationManger.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
    _googleMap.clear();
    ArrayList<HashMap<String, String>> arl = (ArrayList<HashMap<String, String>>) 
            getIntent().getSerializableExtra("arrayList");


    /*if(location!=null){
        double latitude = location.getLatitude();
        double langitude = location.getLongitude();

        LatLng latlang = new LatLng(latitude, langitude);
        //LatLngBounds curScreen =    
            _googleMap.getProjection().getVisibleRegion().latLngBounds;
        //curScreen.contains(latlang);
        myPosition = new LatLng(latitude, langitude);

             // Show only Current Location

        _googleMap.moveCamera(CameraUpdateFactory.newLatLng(myPosition)); 
        _googleMap.addMarker(new 
         MarkerOptions().position(myPosition).title("start"));

    }*/

    if ( !lat.trim().equals("") && !lng.trim().equals("") ) {
        double Hlat = Double.parseDouble(lat.trim());
        double Hlong= Double.parseDouble(lng.trim());

        LatLng dabaseLocations =new LatLng(Hlat, Hlong);

        Log.e("LLAATTAA", ""+Hlat);
        Log.e("LLOONNGG", ""+Hlong);


        // Show current location with database locations

          _googleMap.moveCamera(CameraUpdateFactory.newLatLng(dabaseLocations)); 
         _googleMap.addMarker(new    
       MarkerOptions().position(dabaseLocations).title("start"));
          }
}

@Override
public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub

}
@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    serv=new GcmIntentService();
    //serv.CancelNotification(getApplicationContext());

}

 }

我的Logcat

03-06 13:03:40.187: E/AndroidRuntime(18546): java.lang.RuntimeException: Unable to start activity 

日志猫

    ComponentInfo{com.technowellServices.traffic/com.technowellServices.traffic.ShowMapActivity}:   
        java.lang.NullPointerException
        03-06 13:03:40.187: E/AndroidRuntime(18546):    at 
       android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1728)
        03-06 13:03:40.187: E/AndroidRuntime(18546):    at 
         android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1747)
        03-06 13:03:40.187: E/AndroidRuntime(18546):    at 
         android.app.ActivityThread.access$1500(ActivityThread.java:155)
        03-06 13:03:40.187: E/AndroidRuntime(18546):    at 
       android.app.ActivityThread$H.handleMessage(ActivityThread.java:993)
    03-06 13:03:40.187: E/AndroidRuntime(18546):    at 
   android.os.Handler.dispatchMessage(Handler.java:130)
    03-06 13:03:40.187: E/AndroidRuntime(18546):    at android.os.Looper.loop(SourceFile:351)
    03-06 13:03:40.187: E/AndroidRuntime(18546):    at 
      android.app.ActivityThread.main(ActivityThread.java:3814)
    03-06 13:03:40.187: E/AndroidRuntime(18546):    at 
      java.lang.reflect.Method.invokeNative(Native Method)
    03-06 13:03:40.187: E/AndroidRuntime(18546):    at j
    ava.lang.reflect.Method.invoke(Method.java:538)
    03-06 13:03:40.187: E/AndroidRuntime(18546):    at 
   com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
    03-06 13:03:40.187: E/AndroidRuntime(18546):    at 
   com.android.internal.os.ZygoteInit.main(ZygoteInit.java:659)
    03-06 13:03:40.187: E/AndroidRuntime(18546):    at dalvik.system.NativeStart.main(Native 
   Method)
    03-06 13:03:40.187: E/AndroidRuntime(18546): Caused by: java.lang.NullPointerException
    03-06 13:03:40.187: E/AndroidRuntime(18546):    at 
    com.technowellServices.traffic.ShowMapActivity.onCreate(ShowMapActivity.java:66)
    03-06 13:03:40.187: E/AndroidRuntime(18546):    at 
    android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1082)
    03-06 13:03:40.187: E/AndroidRuntime(18546):    at 
   android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1692)

最佳答案

你不能调用这个

 Intent noticeIntent = getIntent();

在 onCreate() 方法之前。

您应该将其放在 onCreate() 方法中。

 @Override
 protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_show_map);
     Intent noticeIntent = getIntent();  
     // ...
 }

将其更改为

  String message = noticeIntent.getExtras().getString("message");

 String message = noticeIntent.getStringExtras("message");

关于android - 打开通知时如何在 map 上显示经纬度点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22217838/

相关文章:

android - 我在哪里找到由 android 应用程序修改的文件

java - 如何在没有 root 的情况下可靠地模拟 Android 上的触摸事件(如 Automate 和 Tasker)?

Android Auto - 如何显式打开谷歌地图进行导航以显示在汽车屏幕上(intent.setPackage 不起作用)

javascript - 使用地理编码服务无法显示 Google map

android - 从 GPS 数据中找到最佳匹配路线

java - 如何从内存中的流式 zip 文件访问 zipEntry

Android:将文本添加到位图

Android:状态栏中的多个通知作为单个列表

android - 为 One Activity Many Fragment App 构建 fragment 堆栈

android - 在 onMessageReceived 中显示默认通知